【问题标题】:jbuttons and a jtextfield that has an action listenerjbuttons 和一个具有动作监听器的 jtextfield
【发布时间】:2015-04-01 06:45:17
【问题描述】:

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

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

我正在使用:

    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));

【问题讨论】:

    标签: java swing jbutton actionlistener jtextfield


    【解决方案1】:

    尝试使用类似的东西

    textfield.setText(textfield.getText() + "2");
    

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

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

    另外buttonNo1.setBounds(11, 18, 50, 50); 看起来您正在尝试不使用布局管理器。避免使用null 布局,像素完美的布局是现代 ui 设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 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();
            }
        }
    
    }
    

    那么您只需要根据需要添加每个按钮...

    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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        public void append(String str)

        将给定的文本附加到文档的末尾。如果 model 为 null 或字符串为 null 或为空。

        参数: str - 要插入的文本

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-11-22
          • 2013-12-24
          • 2021-03-13
          • 2015-05-12
          • 2014-08-23
          • 2021-07-02
          • 1970-01-01
          相关资源
          最近更新 更多