在两个 JPanel 对象之间发送消息

发布于 2024-11-29 17:20:44 字数 137 浏览 0 评论 0原文

我有一个包含 JPanel 的 Java JFrame。在该 JPanel 中,有两个独立的 JPanel。当用户单击第一个 JPanel 中的按钮时,需要向另一个 JPanel 发送一条消息,通知它单击了哪个按钮。在这样的对象之间发送消息的最简单方法是什么?

I have a Java JFrame containing a JPanel. Within that JPanel, there are two separate JPanels. When the user clicks a button in the first JPanel, a message needs to be sent to the other JPanel notifying it which button was clicked. What is the easiest way to send messages between objects like this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

-残月青衣踏尘吟 2024-12-06 17:20:44

对于 mKorbel(以及原始海报):
我建议的是松散耦合,即一个 JPanel 不了解另一个 JPanel,并且所有连接都是通过某种控件完成的。例如,借用您的一些代码:

CopyTextNorthPanel2.java

import java.awt.*;
import javax.swing.*;

public class CopyTextNorthPanel2 extends JPanel {

   private static final long serialVersionUID = 1L;
   public JTextField northField;

   public CopyTextNorthPanel2() {
      northField = new JTextField("Welcome World");
      northField.setFont(new Font("Serif", Font.BOLD, 20));
      northField.setPreferredSize(new Dimension(300, 25));
      add(northField);
   }

   public String getNorthFieldText() {
      return northField.getText();
   }
}

CopyTextSouthPanel2.java

import java.awt.event.*;
import javax.swing.*;

public class CopyTextSouthPanel2 extends JPanel {

   private static final long serialVersionUID = 1L;
   private JTextField firstText = new JTextField("Desired TextField");
   private JButton copyButton = new JButton("Copy text from JTextFields");
   private CopyTextControl2 control;

   public CopyTextSouthPanel2() {
      copyButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (control != null) {
               control.copyAction();
            }
         }
      });

      add(firstText);
      add(copyButton);
   }

   public void setControl(CopyTextControl2 control) {
      this.control = control;
   }

   public void setFirstText(String text) {
      firstText.setText(text);
   }
}

CopyTextControl2.java

public class CopyTextControl2 {
   private CopyTextNorthPanel2 northPanel;
   private CopyTextSouthPanel2 southPanel;

   public void copyAction() {
      if (northPanel != null && southPanel != null) {
         southPanel.setFirstText(northPanel.getNorthFieldText());
      }
   }

   public void setNorthPanel(CopyTextNorthPanel2 northPanel) {
      this.northPanel = northPanel;
   }

   public void setSouthPanel(CopyTextSouthPanel2 southPanel) {
      this.southPanel = southPanel;
   }

}

CopyText2.java

import java.awt.*;
import javax.swing.*;

public class CopyText2 {

   private static void createAndShowUI() {
      CopyTextNorthPanel2 northPanel = new CopyTextNorthPanel2();
      CopyTextSouthPanel2 southPanel = new CopyTextSouthPanel2();
      CopyTextControl2 control = new CopyTextControl2();

      southPanel.setControl(control);
      control.setNorthPanel(northPanel);
      control.setSouthPanel(southPanel);

      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.add(northPanel, BorderLayout.NORTH);
      mainPanel.add(Box.createRigidArea(new Dimension(100, 100)), BorderLayout.CENTER);
      mainPanel.add(southPanel, BorderLayout.SOUTH);

      JFrame frame = new JFrame("Copy Text");
      frame.getContentPane().add(mainPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

For mKorbel (and the original poster):
What I'm recommending is looser coupling, that the one JPanel has no knowledge of the other JPanel and that all connections are done through a control of some sort. For instance, to borrow some of your code:

CopyTextNorthPanel2.java

import java.awt.*;
import javax.swing.*;

public class CopyTextNorthPanel2 extends JPanel {

   private static final long serialVersionUID = 1L;
   public JTextField northField;

   public CopyTextNorthPanel2() {
      northField = new JTextField("Welcome World");
      northField.setFont(new Font("Serif", Font.BOLD, 20));
      northField.setPreferredSize(new Dimension(300, 25));
      add(northField);
   }

   public String getNorthFieldText() {
      return northField.getText();
   }
}

CopyTextSouthPanel2.java

import java.awt.event.*;
import javax.swing.*;

public class CopyTextSouthPanel2 extends JPanel {

   private static final long serialVersionUID = 1L;
   private JTextField firstText = new JTextField("Desired TextField");
   private JButton copyButton = new JButton("Copy text from JTextFields");
   private CopyTextControl2 control;

   public CopyTextSouthPanel2() {
      copyButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (control != null) {
               control.copyAction();
            }
         }
      });

      add(firstText);
      add(copyButton);
   }

   public void setControl(CopyTextControl2 control) {
      this.control = control;
   }

   public void setFirstText(String text) {
      firstText.setText(text);
   }
}

CopyTextControl2.java

public class CopyTextControl2 {
   private CopyTextNorthPanel2 northPanel;
   private CopyTextSouthPanel2 southPanel;

   public void copyAction() {
      if (northPanel != null && southPanel != null) {
         southPanel.setFirstText(northPanel.getNorthFieldText());
      }
   }

   public void setNorthPanel(CopyTextNorthPanel2 northPanel) {
      this.northPanel = northPanel;
   }

   public void setSouthPanel(CopyTextSouthPanel2 southPanel) {
      this.southPanel = southPanel;
   }

}

CopyText2.java

import java.awt.*;
import javax.swing.*;

public class CopyText2 {

   private static void createAndShowUI() {
      CopyTextNorthPanel2 northPanel = new CopyTextNorthPanel2();
      CopyTextSouthPanel2 southPanel = new CopyTextSouthPanel2();
      CopyTextControl2 control = new CopyTextControl2();

      southPanel.setControl(control);
      control.setNorthPanel(northPanel);
      control.setSouthPanel(southPanel);

      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.add(northPanel, BorderLayout.NORTH);
      mainPanel.add(Box.createRigidArea(new Dimension(100, 100)), BorderLayout.CENTER);
      mainPanel.add(southPanel, BorderLayout.SOUTH);

      JFrame frame = new JFrame("Copy Text");
      frame.getContentPane().add(mainPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
短暂陪伴 2024-12-06 17:20:44

您可以创建一个自定义事件,并将一个或多个侦听器附加到该事件。

正确的实现方法是让 Button ActionListener 触发事件,然后让两个面板成为该事件的侦听器。

You could create a custom event, and attach one or more listeners to it.

The proper way to implement is to have the Button ActionListener fire the event and then have your two panels be listeners for that event.

薄情伤 2024-12-06 17:20:44

但实际上

public MyClass implements ActionListener {

...
myButton.addActionListener(this);
...

public void actionPerformed(ActionEvent e) {
      //for example if you have more than one events that you need to handle
      if(e.getSource().equals(myButton) {
           //update your do some work on you jpanels
      }
}

,我认为是时候开始考虑设计模式了。您所描述的内容是 观察者模式和可能的命令模式

at the top of your class

public MyClass implements ActionListener {

...
myButton.addActionListener(this);
...

public void actionPerformed(ActionEvent e) {
      //for example if you have more than one events that you need to handle
      if(e.getSource().equals(myButton) {
           //update your do some work on you jpanels
      }
}

But really, I think it is time to start thinking about design patterns. What you are describing is perfect candidate for the observer pattern and possibly the command pattern

白芷 2024-12-06 17:20:44

例如,通过在类之间使用构造函数或(用于调试问题)使用 getParent() 从所需的 JComponent 中提取值

import java.awt.*;
import javax.swing.*;

public class CopyTextFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    private CopyTextNorthPanel northPanel;
    private CopyTextCenterPanel centerPanel;
    private CopyTextSouthPanel southPanel;

    public void makeUI() {
        northPanel = new CopyTextNorthPanel();
        centerPanel = new CopyTextCenterPanel();
        southPanel = new CopyTextSouthPanel();
        northPanel.setName("northPanel");
        centerPanel.setName("centerPanel");
        southPanel.setName("southPanel");
        centerPanel = new CopyTextCenterPanel();
        centerPanel.setPreferredSize(new Dimension(300, 40));
        southPanel = new CopyTextSouthPanel();
        southPanel.setSourceTextField(northPanel.desText);
        northPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        southPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        setLayout(new BorderLayout(5, 5));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(northPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(southPanel, BorderLayout.SOUTH);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CopyTextFrame().makeUI();
            }
        });
    }
}  

+

import javax.swing.*;

public class CopyTextCenterPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    public CopyTextCenterPanel() {
    }
}

+

import java.awt.*;
import javax.swing.*;

public class CopyTextNorthPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    public JTextField desText;

    public CopyTextNorthPanel() {
        desText = new JTextField("Welcome World");
        desText.setFont(new Font("Serif", Font.BOLD, 20));
        desText.setPreferredSize(new Dimension(300, 25));
        desText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        desText.addComponentListener(null);
        desText.setName("desText");
        add(desText);
    }

    public JTextField getDesText() {
        return desText;
    }
}

+

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class CopyTextSouthPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private JTextField firstText;
    private JButton copyButton;
    private JTextField sourceTextField;
    private String lds = "";

    public CopyTextSouthPanel() {
        firstText = new JTextField("Desired TextField");
        firstText.setMinimumSize(new Dimension(300, 25));
        firstText.setPreferredSize(new Dimension(300, 25));
        firstText.setMaximumSize(new Dimension(300, 25));

        copyButton = new JButton("Copy text from JTextFields");
        copyButton.setMinimumSize(new Dimension(200, 25));
        copyButton.setPreferredSize(new Dimension(200, 25));
        copyButton.setMaximumSize(new Dimension(200, 25));
        copyButton.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }

            private void copyButtonActionPerformed(ActionEvent evt) {
                System.out.print("Button pressed" + "\n");
                Component[] comp = CopyTextSouthPanel.this.getParent().getComponents();
                int nO = comp.length;
                for (int i = 0; i < comp.length; ++i) {
                    if (comp[i] instanceof JPanel) {
                        String name = ((JPanel) comp[i]).getName();
                        if (name.equals("northPanel")) {
                            JPanel panel = (JPanel) comp[i];
                            Component[] comp1 = panel.getComponents();
                            int nO1 = comp1.length;
                            for (int ii = 0; ii < comp1.length; ++ii) {
                                if (comp1[ii] instanceof JTextField) {
                                    String name1 = ((JTextField) comp1[ii]).getName();
                                    if (!(name1 == null)) {
                                        if (name1.equals("desText")) {
                                            JTextField text = (JTextField) comp1[ii];
                                            String str = text.getText();
                                            firstText.setText(str);
                                            System.out.print("set value -> " + str + "\n");
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                lds = sourceTextField.getText();
                if (lds != null || (!(lds.isEmpty()))) {
                    firstText.setText(" Msg -> " + lds);
                }
            }
        });
        add(firstText, BorderLayout.EAST);
        add(copyButton, BorderLayout.WEST);
    }

    public void setSourceTextField(JTextField source) {
        this.sourceTextField = source;
    }
}

for example by using Constructor betweens Classes or (for debuging issue) extract value from desired JComponent(s) by using getParent()

import java.awt.*;
import javax.swing.*;

public class CopyTextFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    private CopyTextNorthPanel northPanel;
    private CopyTextCenterPanel centerPanel;
    private CopyTextSouthPanel southPanel;

    public void makeUI() {
        northPanel = new CopyTextNorthPanel();
        centerPanel = new CopyTextCenterPanel();
        southPanel = new CopyTextSouthPanel();
        northPanel.setName("northPanel");
        centerPanel.setName("centerPanel");
        southPanel.setName("southPanel");
        centerPanel = new CopyTextCenterPanel();
        centerPanel.setPreferredSize(new Dimension(300, 40));
        southPanel = new CopyTextSouthPanel();
        southPanel.setSourceTextField(northPanel.desText);
        northPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        southPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        setLayout(new BorderLayout(5, 5));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(northPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(southPanel, BorderLayout.SOUTH);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CopyTextFrame().makeUI();
            }
        });
    }
}  

+

import javax.swing.*;

public class CopyTextCenterPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    public CopyTextCenterPanel() {
    }
}

+

import java.awt.*;
import javax.swing.*;

public class CopyTextNorthPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    public JTextField desText;

    public CopyTextNorthPanel() {
        desText = new JTextField("Welcome World");
        desText.setFont(new Font("Serif", Font.BOLD, 20));
        desText.setPreferredSize(new Dimension(300, 25));
        desText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        desText.addComponentListener(null);
        desText.setName("desText");
        add(desText);
    }

    public JTextField getDesText() {
        return desText;
    }
}

+

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class CopyTextSouthPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private JTextField firstText;
    private JButton copyButton;
    private JTextField sourceTextField;
    private String lds = "";

    public CopyTextSouthPanel() {
        firstText = new JTextField("Desired TextField");
        firstText.setMinimumSize(new Dimension(300, 25));
        firstText.setPreferredSize(new Dimension(300, 25));
        firstText.setMaximumSize(new Dimension(300, 25));

        copyButton = new JButton("Copy text from JTextFields");
        copyButton.setMinimumSize(new Dimension(200, 25));
        copyButton.setPreferredSize(new Dimension(200, 25));
        copyButton.setMaximumSize(new Dimension(200, 25));
        copyButton.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }

            private void copyButtonActionPerformed(ActionEvent evt) {
                System.out.print("Button pressed" + "\n");
                Component[] comp = CopyTextSouthPanel.this.getParent().getComponents();
                int nO = comp.length;
                for (int i = 0; i < comp.length; ++i) {
                    if (comp[i] instanceof JPanel) {
                        String name = ((JPanel) comp[i]).getName();
                        if (name.equals("northPanel")) {
                            JPanel panel = (JPanel) comp[i];
                            Component[] comp1 = panel.getComponents();
                            int nO1 = comp1.length;
                            for (int ii = 0; ii < comp1.length; ++ii) {
                                if (comp1[ii] instanceof JTextField) {
                                    String name1 = ((JTextField) comp1[ii]).getName();
                                    if (!(name1 == null)) {
                                        if (name1.equals("desText")) {
                                            JTextField text = (JTextField) comp1[ii];
                                            String str = text.getText();
                                            firstText.setText(str);
                                            System.out.print("set value -> " + str + "\n");
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                lds = sourceTextField.getText();
                if (lds != null || (!(lds.isEmpty()))) {
                    firstText.setText(" Msg -> " + lds);
                }
            }
        });
        add(firstText, BorderLayout.EAST);
        add(copyButton, BorderLayout.WEST);
    }

    public void setSourceTextField(JTextField source) {
        this.sourceTextField = source;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文