开发者

Controlling components on in JFrame

开发者 https://www.devze.com 2023-03-27 01:34 出处:网络
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:

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.EX开发者_开发问答IT_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.


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.


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 :)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消