且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过单击在JButton上添加JTextField?

更新时间:2023-12-05 11:02:22

您可以创建自定义按钮.

You can create a custom button.

一种方法是对按钮使用CardLayout并向其中添加JTextFieldJLabel.在按钮的ActionListener中,如果按下按钮,则显示文本字段并禁用按钮.在字段中输入文本并点击 enter 后,带有show的标签和按钮将被启用.

One way is to use a CardLayout for the button and add a JTextField and a JLabel to it. In the ActionListener of the button, if the button is pressed, you show the text field and disable the button. After you enter your text in the field and hit enter, the label with show, and the button is enabled.

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class TestButtonTextField {
    public TestButtonTextField() {
        JFrame frame = new JFrame();
        frame.add(new TextFieldButton("Hello"));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    protected class TextFieldButton extends JButton {

        private static final String FIELD = "field";
        private static final String LABEL = "label";

        private final CardLayout layout = new CardLayout();
        private final JLabel label;

        public TextFieldButton(String text) {
            super();
            setLayout(layout);

            label = new JLabel(text);
            label.setHorizontalAlignment(SwingConstants.CENTER);
            this.add(label, LABEL);

            final JTextField field = createField();
            this.add(field, FIELD);

            this.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    layout.show(TextFieldButton.this, FIELD);
                    TextFieldButton.this.setEnabled(false);
                }
            });

        }

        private JTextField createField() {
            final JTextField field = new JTextField(5);
            field.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    label.setText(field.getText());
                    field.setText("");
                    layout.show(TextFieldButton.this, LABEL);
                    TextFieldButton.this.setEnabled(true);
                }
            });
            return field;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new TestButtonTextField();
            }
        });
    }
}