Re: Simple BorderLayout problem
On 2/16/2010 2:12 PM, Fencer wrote:
The only other thing I might mention is that you have too many fixed
sizes for panels and frames. Usually one creates the content and then
calls pack() on the frame to size your application. That's not always
possible however but given wide range of display resolutions these days,
it is sometimes better to have fixed sizes. My example below uses your
sizes however.
I don't really know how to deal with the problem. I had, for example, to
adjust the width of the "group panel" before the entire titles border
was visible.
TitledBorder has a method to provide the minimum size necessary to
display the complete text, TitledBorder.getMinimumSize(). It appears to
have a bug though and not calculate the height correctly. But even that
can be gotten around by using the original preferred height with the
width returned from the getMinimumSize() method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CG extends JFrame {
public CG() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JPanel p = new JPanel(new GridBagLayout());
TitledBorder tb = new TitledBorder(
"Start an new session by opening a BioModel or laod a" +
" previously saved session");
p.setBorder(tb);
c.gridx = 0;
c.weightx = 1.0;
final JButton b1 = new JButton("Press Me");
p.add(b1,c);
c.gridx = 1;
final JButton b2 = new JButton("Please Don't Press Me");
p.add(b2,c);
b1.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
b1.setPreferredSize(b2.getPreferredSize());
b1.revalidate();
System.out.println(b1.getSize());
System.out.println(b2.getSize());
}
});
c.gridx = c.gridy = 0;
c.weighty = 1.0; // c.weightx is still 1.0
c.anchor = GridBagConstraints.CENTER;
add(p,c);
// this needs to be after all the components are added to JPanel p
p.setPreferredSize(new Dimension(
tb.getMinimumSize(p).width,p.getPreferredSize().height));
c.gridy = 1;
c.weighty = 0.1; // the panel above gets most of the weighty
c.fill = GridBagConstraints.HORIZONTAL; // c.weightx is still 1.0
c.anchor = GridBagConstraints.SOUTH;
JLabel l = new JLabel("Blah Blah Blah Blah Blah Blah");
l.setBorder(BorderFactory.createLineBorder(Color.BLUE,10));
add(l,c);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
CG cg = new CG();
cg.setSize(640,480);
cg.setLocationRelativeTo(null);
cg.setVisible(true);
}
});
}
}
--
Knute Johnson
email s/nospam/knute2010/