Hi,
I try to get my screen build up like I want to have it (therefore I choose what I use now). I noticed odd behaviour when programming my timeArea (see code, at about ODD BEHAVIOUR).
When I set the preferred size of the text area to width/8, the code runs as expected. When I set the preferred size of the text area to width/4, the text area is horizontally squashed together. Can someone explain to me why this happens?
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutProblem {
public GridBagLayoutProblem () {
JFrame frame = new JFrame ("GridBagLayoutProblem");
frame.setBackground(Color.WHITE);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int width = dimension.width;
int height = dimension.height - 250;
frame.setBounds (0, 0, width, height);
Container pane = frame.getContentPane();
frame.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel ();
panel.setLayout(new GridBagLayout());
panel.setBorder(BorderFactory.createRaisedBevelBorder());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridheight = 1;
constraints.gridwidth = 2;
JLabel name = new JLabel("Name: Jane Doe");
name.setPreferredSize(new Dimension (width/2, height/20));
name.setAlignmentX(SwingConstants.LEFT);
name.setBackground(Color.WHITE);
name.setBorder(BorderFactory.createRaisedBevelBorder());
panel.add(name, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
JTextArea timeArea = new JTextArea ("10:09:30");
timeArea.setAlignmentX(Component.CENTER_ALIGNMENT);
// ODD BEHAVIOUR?
// timeArea.setPreferredSize(new Dimension ((width/4), (height/20)));
timeArea.setPreferredSize(new Dimension ((width/8), (height/20)));
timeArea.setBackground(Color.WHITE);
timeArea.setEditable(false);
timeArea.setLineWrap(true);
timeArea.setWrapStyleWord(true);
timeArea.setBorder(BorderFactory.createRaisedBevelBorder());
panel.add (timeArea, constraints);
// CSD engineer following the problem
constraints.gridx = 4;
constraints.gridy = 0;
constraints.gridwidth = constraints.REMAINDER;
constraints.gridheight = 1;
JButton changeName = new JButton ("Change name");
JPanel namePanel = new JPanel();
namePanel.setBorder(BorderFactory.createRaisedBevelBorder());
namePanel.setPreferredSize(new Dimension ((width/4), height/20));
namePanel.add(changeName);
panel.add(namePanel, constraints);
frame.add(panel);
// frame.pack();
frame.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
GridBagLayoutProblem myProblem = new GridBagLayoutProblem();
}
}
TIA,
Abel