Re: Alignment Problem
- From: Knute Johnson <nospam@xxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 28 Apr 2006 22:13:09 -0700
chester_fried@xxxxxxxxxxx wrote:
In this function I'm trying to clear out and refill a panel with
buttons.
I want the buttons to be packed together at the top of the panel but it
keeps drawing them in the center.
Could someone possibly tell me what I'm doing wrong?
public void refreshView(){
removeAll();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
this.setLayout(gbl);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.NORTH;
for(int i=0;i<Buttons.size();i++){
gbl.setConstraints((JButton)Buttons.get(i),gbc);
add((JButton)Buttons.get(i));
gbc.gridy++;
}
invalidate();
validate();
repaint();
}
Look at the program below to see how to get GridBagLayout to put all of your components at the top of the container. The trick is to set the weighty to 0.0 for all rows except the last one. That one gets a weighty of 1.0 causing it to take all of the extra vertical space.
GridBagConstraints is the most powerful layout manager but also the most difficult to master.
As to your other problem, just remove the old components, add the new components and call validate() on the container. That should be all that is required.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JPanel {
public test() {
setPreferredSize(new Dimension(400,300));
setBackground(Color.BLUE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTH;
c.weighty = 0.0;
c.gridy = 0;
JButton[] buttons = new JButton[6];
String[] strs = { "one","two","three","four","five","six" };
for (int i=0; i<buttons.length; i++) {
buttons[i] = new JButton(strs[i]);
add(buttons[i],c);
if (i == 1)
++c.gridy;
if (i == 3) {
++c.gridy;
c.weighty = 1.0;
}
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test t = new test();
f.add(t,BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
--
Knute Johnson
email s/nospam/knute/
.
- References:
- Alignment Problem
- From: chester_fried
- Alignment Problem
- Prev by Date: problem exception with netbeans 4.1
- Next by Date: Java Comm API: How to set Raw Serial Mode
- Previous by thread: Alignment Problem
- Next by thread: problem in thread when calling a class member's method
- Index(es):