【问题标题】:Add text to two textfields with JButtons使用 JButton 将文本添加到两个文本字段
【发布时间】:2012-02-04 12:40:52
【问题描述】:

如果我的问题不是很具体,这就是我想要做的。我有一个计算器,它有两个 JTextField、一个 JLabel ("Answer = ") 和一个 JTextField 作为答案。

我有一个 JButtons 数组(0 到 9),允许用户单击它们以将数字添加到 JTextField 中,其中光标处于活动状态......这是这里的问题。我只能让两个文本字段中的一个向它们添加数字,或者两者都相互添加相同的数字。

例如,如果我单击一个按钮并将addActionListener 设置为(new AddDigitsONE),它将只允许我向第一个JTextField 添加数字。即使在我尝试将光标设置到第二个 JTextField 并使用 JButton 向其添加数字之后,它也会跳回第一个 JTextField。

将JButtons数组添加到JFrame中的JPanel的代码


// input is my JPanel set to BorderLayout.SOUTH

for (int i = 0; i < button.length; i++)
{
    text = Integer.toString(i);
    button[i] = new JButton();
    button[i].setText(text);
    input.add(button[i]);
    button[i].addActionListener(new AddDigitsONE());
}

我的动作监听器的代码:第一个 JTextField

// firstNumber is my first JTextField
// command is the button pressed (0-9)
// command "<" is erasing one character at a time

private class AddDigitsONE implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String text = firstNumber.getText();
        String command = ((JButton)(e.getSource())).getText();

        if (command == "<")
        {
            firstNumber.setText(text.substring(0,text.length()-1));
        }

        else
            firstNumber.setText(text.concat(command));
    }
}

我的动作监听器代码:第二个 JTextField

private class AddDigitsTWO implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String text = secondNumber.getText();
        String command = ((JButton)(e.getSource())).getText();

        if (command == "<")
        {
            secondNumber.setText(text.substring(0,text.length()-1));
        }

        else
            secondNumber.setText(text.concat(command));
    }
}

有没有办法合并两个动作侦听器并区分哪个文本字段中的光标处于活动状态(同时允许我使用 JButton 在两个 JTextField 中输入数字)?

【问题讨论】:

  • 至少对我来说,这似乎是一种非常尴尬的制作计算器的方式。
  • @Max 我知道。我正在研究制作计算器的一些更复杂的方法。前任。有一个文本字段来显示你所有的数字和操作......类似于一个真正的计算器。但其中很多都让我有点不知所措。

标签: java swing actionlistener jtextfield calculator


【解决方案1】:

您可以向按钮添加一个 Action,而不是使用 ActionListener。在这种情况下,您将需要扩展 TextAction,因为它有一个方法可以让您获取最后一个焦点文本组件,以便您可以将数字插入该组件。代码类似于:

class AddDigit extends TextAction
{
    private String digit;

    public AddDigit(String digit)
    {
        super( digit );
        this.digit = digit;
    }

    public void actionPerformed(ActionEvent e)
    {
        JTextComponent component = getFocusedComponent();
        component.replaceSelection( digit );
    }
}

【讨论】:

  • 再次感谢您!我很好奇组件如何知道将一个数字连接到前一个数字的末尾。我已经阅读了JTextComponent,但文档让我摸不着头脑……这与构造函数有什么关系吗?
  • 替换当前插入符号位置的文本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多