Re: aligning components within boxes
Duane Evenson wrote:
I'm having trouble getting components to center align in a Box or JPanel
with BoxLayout. The problem component seems to be a JTextField. Here is my
code:
// Text.java
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
Test() {
Box box = Box.createVerticalBox();
box.setAlignmentX((float) 0.5);
box.add(new JLabel("Client"));
box.add(new JTextField(40));
box.add(new JButton("Send"));
Container cp = getContentPane();
cp.add(box);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}
Everybody else gave you excellent examples of how to fix your alignment
problems with BoxLayout. I might suggest for a layout such as this that
you use GridBagLayout. It has several advantages but the one I like
best is that the components stay the same size if you increase the size
of the frame. Not only that but I think it is a simpler layout and
easier to use than BoxLayout.
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
Test() {
JPanel p = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
p.add(new JLabel("Client"),c);
p.add(new JTextField(40),c);
p.add(new JButton("Send"),c);
Container cp = getContentPane();
cp.add(p);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}
--
Knute Johnson
email s/nospam/knute2008/
--
Posted via NewsDemon.com - Premium Uncensored Newsgroup Service
------->>>>>>http://www.NewsDemon.com<<<<<<------
Unlimited Access, Anonymous Accounts, Uncensored Broadband Access