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();
}
});
}
}
Have you studied this ...
http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html
Apply the setALignmentX() to the components (JLabel, JTextField,
JButton) not to the container (Box)
----------------------------------- 8< ----------------------------
public class CentredLayout extends JFrame {
CentredLayout() {
Box box = Box.createVerticalBox();
JLabel label = new JLabel("Client");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
box.add(label);
JTextField textField = new JTextField(40);
textField.setAlignmentX(Component.CENTER_ALIGNMENT);
box.add(textField);
JButton button = new JButton("Send");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
box.add(button);
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 CentredLayout();
}
});
}
}
----------------------------------- 8< ----------------------------
--
RGB