Java swing组件之间的通信

标签 java swing jbutton actionlistener jtextpane

我在 Swing 中连接组件时遇到问题,这些组件将交互或施加 Action 流。我的计划是在按下按钮时禁用/启用 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);
    }
  }
}

我很难找到有关 JComponent 之间通信的文章。如果您还可以建议详细的来源,我们将不胜感激。

最佳答案

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

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"));

最后但并非最不重要的一点。正如安德鲁·汤普森已经提到的:

Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.

关于Java swing组件之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080408/

相关文章:

Java:禁用操作应禁用 JButtons 和 JMenuItems

java - 查找 Java JButton 数组的索引

java - Java Executor 框架实现了什么设计模式?

java - 三元字符串到 Node 类

java - 带有安全管理器的 Swing 应用程序导致奇怪的 GUI 刷新问题

Java - 关于 JOptionPane 的问题

java - 当滚动条还不可见时创建最大尺寸的按钮

java - 在android java中访问方法的问题

java - 如何在 SWT 中使用鼠标滚轮滚动滚动的复合 Material

java - 如何在 Swing 中创建单独的屏幕?