简体   繁体   中英

Is it possible to set a JPanel's size when creating a new JPanel?

I was wondering if there is a way to change the size of a JPanel when creating one.

My code looks like this:

add(scoreArea, BorderLayout.NORTH);
add(gameArea, BorderLayout.CENTER);
add(new JPanel(), BorderLayout.WEST);
add(new JPanel(), BorderLayout.EAST);
add(new JPanel(), BorderLayout.SOUTH);

I used the JPanels to create a border, but I would like to make them thinner. I am new to swing and I was just wondering if you could change the size in the same statement or if I would have to make JPanel objects and set the size there?

I tried this but it doesn't seem to work:

add(new JPanel(){
    setPreferredSize(new Dimension(10, 300));
}, BorderLayout.EAST);

Is there a way to do something like this?

Edit: Really downvotes? Just asking a question, I dont see the need for a downvote. What a community.

You can set margin for JPanel (contaiter) using EmptyBorder class:

EmptyBorder margin = new EmptyBorder(top, left, bottom, right);
getContentPane().setBorder(border);

Proper way to setup prefered size is:

Dimension size = new Dimension(width, height);
JPanel panel;

add(panel = new JPanel(), BorderLayout.WEST);
panel.setPreferredSize(size); 

add(panel = new JPanel(), BorderLayout.EAST);
panel.setPreferredSize(size); 

add(panel = new JPanel(), BorderLayout.SOUTH);
panel.setPreferredSize(size); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM