简体   繁体   中英

I created my GUI in a GUI class' constructor. How would I access its Frames, Panels etc. from another class?

First of all, this is a more specific question than it seems to be. To start off: I am currently doing a small application with a rather small GUI, so I decided to make a GUI class, and initialize my whole GUI in this constructor.

This would look like this:

public class GUI extends JFrame{

   public GUI{

       //Initialize GUI here, including its Frames, Panels, Buttons etc.
   }
}

How can I now access the GUIs frame etc. from an external class? If I would create an object of the GUI class, I would simply duplicate my GUI window. I did not come across any other ideas than making the frame, panel and so on static.

I'm somewhat lost right now. Also I'm pretty sure that I am not thinking the right way into this case, but I need someone to point me to the right direction. If someone could help me out, I would be very thankful.

First of all, using static is the worst solution possible, even if your GUI class is a singleton (buf if it is, at least it will work fine).

Why don't you simply create getters and/or setters ? And finally, it is usually not normal that external classes need to access the components of another graphic class. You should wonder if your design is the most fitted for your needs.

Here's a simple GUI to change the background color of a JPanel with a JButton. Generally, this is how you construct a Swing GUI.

package com.ggl.testing;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ChangeDemo implements Runnable {

    private boolean isYellow;

    private JFrame frame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ChangeDemo());
    }

    @Override
    public void run() {
        frame = new JFrame("Change Background Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));

        JPanel namePanel = new JPanel();
        JLabel nameLabel = new JLabel(
                "Click the button to change the background color");
        nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        namePanel.add(nameLabel);

        mainPanel.add(namePanel);

        final JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.setBackground(Color.YELLOW);
        isYellow = true;

        JButton changeButton = new JButton("Change Color");
        changeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                isYellow = !isYellow;

                if (isYellow) buttonPanel.setBackground(Color.YELLOW);
                else buttonPanel.setBackground(Color.RED);
            }
        });

        buttonPanel.add(changeButton);

        mainPanel.add(buttonPanel);

        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

}

You don't access the Swing components of the GUI from other classes. You create other classes to hold the values of the GUI.

Generally, you use the model / view / controller pattern to construct a Swing GUI. That way, you can focus on one part of the GUI at a time.

Take a look at my article, Java Swing File Browser , to see how the MVC pattern works with a typical Swing GUI.

You don't need to make it static or to create a new JFrame object every time.

Have a look at this simple code :

class UseJFrame {
    public static void main(String...args) {
        Scanner sc = new Scanner(System.in);
        JFrame frame = new GUI();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        System.out.println("Press E to exit");
        String ip;
        while(true) {
            System.out.println("Show GUI (Y/N/E)? : ");
            ip = sc.nextLine();
            if(ip.equalsIgnoreCase("y") {
                frame.setVisible(true);
            } else if(ip.equalsIgnoreCase("n") {
                frame.setVisible(false);
            } else {           // E or any other input
                frame.dispose();
            }
        }
    }
}

Note : Don't make GUI visible through constructor or it will show window at the very starting of creation of JFrame object.

If you want to use the same JFrame object at other places too then pool architecture would be better approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM