标签:actionlistener swing jbutton java
好.我不确定问题的标题以及是否使用正确的词.
因为我是一个自学成才的业余爱好者,所以我很难问我的问题,因为我不知道事物的正确术语,因此我将用代码编写一些东西然后问我的问题.我编写时没有导入语句,没有设置布局和滚动条以及其他一些东西,只是为了使其更简单.
public class Foo{
JTextArea text;
public static void main(String[] args){
Foo foo = new Foo;
foo.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
JPanel panel = new JPanel();
frame.setVisible(true);
frame.setSize(600, 300);
frame.getContentPane().add(BorderLayout.EAST, panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(button2);
text = new JTextArea(10, 20);
panel.add(text);
button.addActionListener(new ButtLis());
button2.addActionListener(new ButtLis());
}
class ButtLis implements ActionListener{
@override
// this is where I have the problem
text.append();
}
}
我想要的是一个if语句进入我的内部类(ButtLis),它将确定按下了哪些按钮,然后基于该按钮将某些文本附加到JTextArea.但我不知道该如何呼叫才能找出按下了哪个按钮.
解决方法:
您有两种选择.在当前情况下,JButton对象在构造函数中位于本地范围内,您将需要检查actionCommmand,因为无法使用当前范围从ActionListener访问这些对象.所以你可以这样做
class ButtLis implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("One".equals(command)) {
// do something
}
}
}
如果要比较对象源,则需要给按钮一个全局范围
public class Foo {
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
class ButtLis implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
}
}
}
}
第三种选择是分别注册按钮
public void go() {
...
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
}
在How to use Common Button和How to Write ActionListeners查看更多
标签:actionlistener,swing,jbutton,java 来源: https://codeday.me/bug/20191122/2056469.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。