Java Swing programming framework: should listeners be the source of almost all Swing components?

My question boils down to the following: is this the standard structure in Swing programming to give listeners control over new components (like the new JPanel) for display and input and to let new components listen to new components for display and input, and so on ad infinitum ? Or does Java need to return to some unifying class that binds all Swing components together in procedural order?

Currently, in my application that uses only one JFrame, in my listeners my original JFrame object is passed as a parameter to all my JPanels so that their listeners can call removeall () to clear the frame for the new JPanel. For example, a short code as follows

public class MainFrame {
  JFrame jfrm;
  public MainFrame() {
    jfrm = new JFrame("Main Frame");
    JPanel mainPanel = new MainPanel(jfrm);
  }
}

public class MainPanel extends JPanel {
  public MainPanel(final JFrame mainFrame) {
    JButton example = new JButton("Example");
    example.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent le) {
            mainFrame.removeall();
            JPanel 2ndPanel = new 2ndPanel(mainFrame);
            mainFrame.add(2ndPanel);
            mainFrame.validate();
        }
    });
  }
}

Is this the correct structure - where are the listeners that generate the new panels, and not some kind of unifying class? But if that's the case, how does the Java compiler ever get to mainFrame.validate () if there is a cascading infinity of listeners? I am an old-school programmer trying to program a Swing application in Java, and I suppose I might not have understood the basic concepts of Swing programming. We look forward to any helpful answers and thank you in advance!

+5
4

. Observer Swing , , .

: "" , MainFrame. , . , , , .

, - , . . ( "" ). ( ) . .

: , . . , . , .

- .

+4

, , JPanel it ContentPane.

, . JFrame . , .

, . . SwingUtilities.invokeLater .

JFrame . ?

 final JPanel mainPanel = new MainPanel();     
 JButton example = new JButton("Example");
 example.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent le) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               MainFrame.this.removeAll();
               MainFrame.this.add(mainPanel);
            }
         });;
    }
 });
 add(example);

, , .

, .

+1

. Java, , . JPanel JFrame.

, . , .

Also do less in anonymous inner classes. Detach the event data and call the method that makes sense to include the class as an operation.

+1
source

All Articles