首页 > 解决方案 > 组件之间的 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 之间通信的文章。如果您还可以建议一个详细的来源,将不胜感激。

标签: javaswingjbuttonactionlistenerjtextpane

解决方案


我建议您创建一个新类来处理您对特定组件的请求,并且不要使用匿名事件处理程序:

public class ButtonHandler extends AbstractAction {
    private JComponent componentToDisable;
    public ButtonHandler(JComponent comp, String text) {
        super(text);
        componentToDisable = comp;
    }
    public void actionPerformed(ActionEvent event) {
       componentToDisable.setEnabled(false);
    }
}

如何使用它:

/* TextPane 'a' **/
txtpnA = new JTextPane();
txtpnA.setBounds(47, 88, 89, 20);
contentPane.add(txtpnA);
txtpnA.setBorder(BorderFactory.createLineBorder(Color.black));

JButton btnA = new JButton(new ButtonHandler(textpnA, "a"));
btnA.setBackground(Color.YELLOW);
btnA.setBounds(47, 54, 89, 23);
contentPane.add(btnA);

其他按钮的步骤相同。

JButton btnB = new JButton(new ButtonHandler(textpnB, "b"));
JButton btnC = new JButton(new ButtonHandler(textpnC, "c"));

最后但并非最不重要。正如 Andrew Thompson 已经提到的:

Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或者它们的组合以及布局填充和空白边框。


推荐阅读