How to align swing buttons vertically ?
Hello !
I want to create a swing application with a main frame and a panel
containing vertically aligned buttons at the right side. Here is the code:
import java.awt.*;
import javax.swing.*;
public class TestViewer {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
});
}
}
class ViewerFrame extends JFrame {
public ViewerFrame() {
getContentPane().add(new JPanel(), BorderLayout.CENTER);
getContentPane().add(createBtnPanel(), BorderLayout.EAST);
}
private JPanel createBtnPanel() {
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new GridLayout(0, 1));
btnPanel.add(new JButton("Button 1"));
btnPanel.add(new JButton("Button 2"));
btnPanel.add(new JButton("Long Button 3"));
btnPanel.add(new JButton("Button 4"));
btnPanel.add(new JButton("Button 5"));
// Trick here !
// I put the btnPanel at the NORTH of a "dummy" panel to have
// the correct button sizes !!!
// Other solutions ??
JPanel dummyPanel = new JPanel();
dummyPanel.setLayout(new BorderLayout());
dummyPanel.add(btnPanel, BorderLayout.NORTH);
return dummyPanel;
}
}
It works, but is there an other way to avoid the dummyPanel trick ?
Thanks a lot !
Olivier