Domanda

I have several methods which create their own component, JButton or JLabel in a JPanel. Then I have a separate method which adds all these JPanels the the JFrame. I also use gridx and gridy on the JPanels to position them how I want. This is: lookreply on the left, then top right the title and below in a 2X2 table quit, restart, pickup and hello. However my current code when run displays a weird, random layout.

The lookreply is on the left, but then to the right is quit, a space, restart then hello all vertical. pickup and title aren't seen. I dont know why this is happening.

Please see my code below.:

public class GUI extends JPanel
{
/**
 * Creation of variables used throughout the GUI Class. 
 */
//JPanel panel = new JPanel(new GridBagLayout());

private static final long serialVersionUID = 1L;

public static void main(String[] args)
{
    GUI g = new GUI();

    g.create();
}

private void create()
{
    JFrame screen = new JFrame("Dungeon of Doom");
    screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    screen.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    //set size to full screen. 
    screen.setExtendedState(Frame.MAXIMIZED_BOTH);   

    //Add all JPanes to screen
    screen.add(lookReply(), c);
    c.gridy = 0;
    c.gridx = 0;

    screen.add(title(), c);
    c.gridy = 0;
    c.gridx = 1;
    c.gridwidth = 2;

    screen.add(quit(), c);
    c.gridy = 1;
    c.gridx = 1;

    screen.add(restart(), c);
    c.gridy = 1;
    c.gridx = 2;

    screen.add(pickup(), c);
    c.gridy = 2;
    c.gridx = 1;

    screen.add(hello(), c);
    c.gridy = 2;
    c.gridx = 2;

    screen.setVisible(true);
}

One of the methods (quit)

private JPanel quit()
{
    JPanel quitPanel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    JButton quit = new JButton("QUIT");
    quitPanel.add(quit, c);


    return quitPanel;
}

All the other methods are pretty much the same except the title is a a JLabel and the table iterates to create a 5x5 table of JLabel within its own JPanel. Any help is appreciated!

È stato utile?

Soluzione

I have found what was doing this. As seen in the code I was adding the component before setting the layout.

screen.add(lookReply(), c);
c.gridy = 0;
c.gridx = 0;

whereas it should be

c.gridy = 0;
c.gridx = 0;
screen.add(lookReply(), c);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top