jbuttons 和一个具有动作侦听器的 jtextfield

jbuttons and a jtextfield that has an action listener

我有一个由 jbutton 和一个带有动作侦听器的 jtextfield 组成的键盘。当我按下按钮时,数字显示在文本字段中,但下一个数字会覆盖它。谁能告诉我如何将文本附加到长度为 13 的数字以及它何时到达 return.

如果我使用键盘输入数字,我可以输入一串数字,但不能通过按钮输入。

我正在使用:

    JButton buttonNo2 = new JButton("2");
    buttonNo2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textfield.setText("2");
        }

buttonNo1.setBounds(11, 18, 50, 50);
    keyboardPanel.add(buttonNo2);
    buttonNo1.setForeground(Color.BLUE);
    buttonNo1.setFont(new Font("Perpetua", Font.BOLD, 20));

尝试使用类似

的东西
textfield.setText(textfield.getText() + "2");

而不是textfield.setText("2");

setText 就是这样做的,将文本字段的文本设置为您指定的值。

另外 buttonNo1.setBounds(11, 18, 50, 50); 看起来您正在尝试在没有布局管理器的情况下进行操作。避免使用 null 布局,像素完美布局是现代 ui 设计中的一种错觉。影响组件个体大小的因素太多,none 是您可以控制的。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正

您也可以自己简化它,并使用 Action API 代替,这样可以避免重复输入很多...

public class NumberAction extends AbstractAction {

    private JTextField field;
    private int number;

    public NumberAction(JTextField field, int number) {
        this.field = field;
        this.number = number;
        putValue(NAME, Integer.toString(number));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Document doc = field.getDocument();
        try {
            doc.insertString(doc.getLength(), Integer.toString(number), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }

}

那么您只需要将每个按钮添加为 required...

add(new JButton(new NumberAction(textfield, 1)));
add(new JButton(new NumberAction(textfield, 2)));
add(new JButton(new NumberAction(textfield, 3)));

有关详细信息,请参阅 How to Use Actions

您必须先获取文本,然后通过附加上一个和当前文本来设置文本。 public void actionPerformed(ActionEvent e) { 字符串 str = textfield.getText(); textfield.setText(str+打印的数字); }

正如@MadProgrammer 已经发布的如何使用 JTextField 实现它, 您可以选择 JTextArea#append method

public void append(String str)

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

Parameters: str - the text to insert