java-使用JButton将文本添加到两个文本字段
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-使用JButton将文本添加到两个文本字段,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2179字,纯文字阅读大概需要4分钟。
内容图文
如果我的问题不是很具体,这就是我想要做的.我有一个包含两个JTextField,一个JLabel(“ Answer =”)和一个JTextField作为答案的计算器.
我有一个JButtons数组(0到9),允许用户单击它们以将数字添加到JTextField中,其中的光标处于活动状态…这是这里的问题.我只能让两个文本字段之一向它们添加数字,或者都向彼此添加相同的数字.
例如,如果我单击一个按钮,并且addActionListener设置为(new AddDigitsONE),它将仅允许我向第一个JTextField添加数字.即使我尝试将光标设置为第二个JTextField并使用JButton向其添加数字,它也会跳回到第一个JTextField.
用于将JButton数组添加到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中输入数字)?
解决方法:
您可以将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 );
}
}
内容总结
以上是互联网集市为您收集整理的java-使用JButton将文本添加到两个文本字段全部内容,希望文章能够帮你解决java-使用JButton将文本添加到两个文本字段所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。