Domanda

I just started teaching myself the basics of Java's JFrame and JSwing. It's all fun and games.

I've heard that GridBagLayout is THE layout to master if you want to make GUIs with Java, and I do, so I'm tying.

Newly, today, I tried making a GUI for myself, with some good results. However I ran into a problem.

My code is as follows:

String inputText;

public welcomeFrame(String title) {
    super(title);

    Container c = getContentPane();
    GridBagConstraints gc = new GridBagConstraints();

    launchGUI.setMyDefaults(this, 800, 300);

    setLayout(new GridBagLayout());

    gc.weighty = 1;

    gc.anchor = GridBagConstraints.NORTH;

    gc.gridx = 0;
    gc.gridy = 0;

    c.add(intro1, gc);

    gc.gridx = 0;
    gc.gridy = 1;

    c.add(intro2, gc);

    gc.gridx = 0;
    gc.gridy = 2;

    c.add(intro3, gc);

    gc.gridx = 0;
    gc.gridy = 3;

    c.add(intro4, gc);

    gc.gridx = 0;
    gc.gridy = 4;       

    c.add(intro5, gc);

    gc.anchor = GridBagConstraints.SOUTH;

    gc.gridx = 0;
    gc.gridy = 5;       

    c.add(tweets, gc);

    gc.gridx = 1;
    gc.gridy = 5;

    c.add(textFrame, gc);

    textFrame.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            inputText = textFrame.getText();
            dispose();

        }
    });

}

What this gives me is this wonder: enter image description here

Bet you can spot my problem?

Why the heck is my text box all the way over there?

How can I make it stick to my "Enter words:" label? You know, as in just to the right of it?

Thanks all, and please, be gentle, I just stared learning this stuff.

È stato utile?

Soluzione

If i understand your question correctly the easiest solution is to add the JLabel and JTextField to a new JPanel and add that to the overall layout.

for example:

gc.gridx = 0;
gc.gridy = 5;

JPanel panel = new JPanel();
panel.add(tweets);
panel.add(textFrame);

c.add(panel, gc);

You could also try adjusting the gridwidth for the first few rows:

gc.gridwidth = 2;//before adding the intros
...
gc.gridwidth = 1;//right after the last intro
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top