Domanda

Sorry if my title is a bit vague, but what I'm trying to do is make it so a button leads to another screen. I'm making a basic game so there will be several of these. The one I'm currently trying to do is the options screen. I have found a basic way of doing it using revalidate(), repaint() and multiple panels, but this opens another window each time and doesn't seem very efficient.

This is my code for the options screen, which handles the changing of screens from the main menu to itself.

package menu;

import javax.swing.JFrame;
import javax.swing.JPanel;

import main.Window;

public class Options 
{
JPanel pnlMain = Window.pnlMain;
JFrame frame = new main.Window();
    JPanel pnlOptions = new JPanel();

public static Button graphics = new Button("Graphics");

public Options()
{
    Listener listener = new Listener();

    frame.add(pnlOptions);
    frame.remove(pnlMain);
    pnlMain.revalidate();
    pnlMain.repaint();

    pnlMain.setVisible(false);
    pnlOptions.setVisible(true);

    pnlOptions.add(graphics);

    pnlOptions.revalidate();
    pnlOptions.repaint();

    graphics.addActionListener(listener);
}

}

È stato utile?

Soluzione

CardLayout will help switch content within a frame. Basically we switch panels within a frame, rather than opening a new window. Hope this is what you meant

http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

//yes a root panel must be there. All your cards must be added to it

Jpanel rootPanel = new JPanel(new CardLayout()); 

//to add a panel
Jpanel card1= new Jpanel();
rootPanel.add(card1,"NameofFirstPanel");

//to switch to a card, say on a button press
CardLayout cards = (CardLayout)  rootPanel.getLayout();

cards.show(rootPanel,"nameOfFirstPanel");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top