0

So I have window class which extends JFrame and i add GUIPanel objects who extend JPanel. How do I modify Window(for example delete panel in which startbutton is clicked) when my buttons with their ActionListeners are in GUIPanel class. Or is the structure of my GUI wrong?

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

public class Window extends JFrame{
    int a = 10;
    Window() {
        super("Simple Game");
        setLayout(new BorderLayout());
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void main(String[] args) {
        Window window = new Window();
        GUIPanel panel1 = new GUIPanel(new Dimension(600, 350), 0);
        GUIPanel panel2 = new GUIPanel(new Dimension(600, 100), 0);
        GUIPanel panel3 = new GUIPanel(new Dimension(600, 150), 0);
        panel2.addStartButton();
        window.add(panel1, BorderLayout.NORTH);
        window.add(panel2, BorderLayout.CENTER);
        window.add(panel3, BorderLayout.SOUTH);
    }
}


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

class GUIPanel extends JPanel {
    GUIPanel(Dimension dimensions, int layoutIndex) {
        super();
        setPreferredSize(dimensions);
        if(layoutIndex == 0)
            setLayout(new FlowLayout());
        else if(layoutIndex == 1)
            setLayout(new BorderLayout());
    }
    void addStartButton() {
        JButton startButton = new JButton("START");
        startButton.setPreferredSize(new Dimension(300, 60));
        startButton.addActionListener(e -> {
            /* DO THINGS */
        });
        add(startButton);
    }
}
LosBlancoo
  • 113
  • 10
  • 1
    There are lots of ways you "might" achieve, essentially what you should have is some kind of controller which knows what's going on, the current state and how to deal with "actions", it would then orchestrate the process of changing the UI based on the current state and the requested action. This basically decouples your code and makes it eaiser to expand and modify – MadProgrammer May 13 '16 at 22:16
  • 2
    For [example](http://stackoverflow.com/questions/27663306/open-a-jpanel-after-pressing-a-button-in-a-jframe/27663749#27663749), [example](http://stackoverflow.com/questions/29571722/java-application-with-multiple-scenes/29639672#29639672), – MadProgrammer May 13 '16 at 22:18
  • 1
    Try and avoid any solution that requires you to pass a reference of the `Window` to the `GUIPanel` or have any kind of `static` reference/declaration, they are limiting and problematic – MadProgrammer May 13 '16 at 22:18

0 Answers0