组件之间的Java swing通信
我在Swing中连接组件时遇到了一些问题,这些组件可能会相互作用或产生动作流。我的计划是在按下按钮时禁用/启用JTextPane,然后输入数字,以便程序可以开始计算。到目前为止,我的处境是:
private JPanel contentPane;
protected JTextPane txtpnA;
protected JTextPane txtpnB;
protected JTextPane txtpnC;
/* Button 'a' **/
JButton btnA = new JButton("a");
btnA.setBackground(Color.YELLOW);
btnA.setBounds(47, 54, 89, 23);
btnA.setActionCommand("a");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
} {
}
});
contentPane.add(btnA);
/* TextPane 'a' **/
txtpnA = new JTextPane();
txtpnA.setBounds(47, 88, 89, 20);
contentPane.add(txtpnA);
txtpnA.setBorder(BorderFactory.createLineBorder(Color.black));
方法如下:
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if(command.equals("a"))
{
txtpnA.setEnabled(false);
} else if(command.equals("b"))
{
txtpnB.setEnabled(false);
} else if(command.equals("c"))
{
txtpnC.setEnabled(false);
}
}
}
我很难找到关于JComponents之间通信的文章。如果你能提供详细的信息来源,我将不胜感激
# 1 楼答案
如果我正确理解你的问题,你想做一个普通的ActionListener,它会被你的按钮调用
您可以在类中创建一个内部私有类,其中包含这些按钮。并将该内部类的一个实例添加到button的ActionListener
注意:如果你想在多个类中使用ActionListener,你可以在其他类文件中将其声明为公共类
# 2 楼答案
我建议您创建一个新类,该类可以处理您对特定组件的请求,并且不使用匿名事件处理程序:
如何使用它:
其他按钮的操作步骤相同
最后但并非最不重要。安德鲁·汤普森已经提到: