Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Controlling components on in JFrame

I am struggling controlling my components. I hava a JFrame which contains a JPanel. My components such as JLabel and JTextArea are added to this Panel. So my question is:

How can I control these compontens? I've tried using

GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 1;

But it doesn't seems to work..

Here is my function the initialize my GUI:

public void initGUI()
{

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  

    final JFrame frame = new JFrame("instantINFO!");
                 frame.setSize(screenSize.width, screenSize.height); 
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 frame.setLayout(new GridBagLayout()); 

    final JPanel panel = new JPanel();

    weather = new JTextArea(vær, 6, 20);
    weather.setFont(new Font("Arial", Font.BOLD, 16));
    weather.setLineWrap(true);
    weather.setWrapStyleWord(true);
    weather.setOpaque(false);
    weather.setEditable(false);

    stedLabel = new JLabel(sted);
    dagLabel = new JLabel(dag);

    panel.add(weather);
    panel.add(stedLabel); 
    panel.add(dagLabel); 

    frame.add(panel);
    frame.setVisible(true);

}

For instance I want the weather label to be in the left upper corner, with a few pixels of margin.

Upvotes: 1

Views: 312

Answers (3)

othman
othman

Reputation: 4556

as other answers mentioned you should learn Layout Managers. you can have this work done for you by using java IDE GUI designers. netbeans has a Swing GUI builder that you can use to build your components by drag n drop.

the latest eclipse Indigo release comes now with a nice WindowBuilder tool.

Upvotes: 1

user592704
user592704

Reputation: 3704

You should study Layout Managers to control your components layouts

For instance I want the weather label to be in the left upper corner, with a few pixels of margin.

To control component location by pixels you can use setLocation() method but then you should set absolute layout or just set your component layout to null which supports x,y location control

code like a

aPanel.setLayout(null);
...
aButton.setLocation(10,3);
aPanel.add(aButton);

I liked the example of absolute position controlling so I want to share it example watch it to see the conception

Good luck :)

Upvotes: 2

camickr
camickr

Reputation: 324108

A JPanel uses a FlowLayout by default. And by default components are centered in a row on the panel. If you want the components left aligned then you need to change the flow layout to left align the components. Read the FlowLayout API to see how to do this.

I also suggest you look at the Swing tutorial on Using Layout Managers for working examples.

Upvotes: 4

Related Questions