I am working on a project that the application need to be able to contain some images on a buttons. Each button should have the same size in length and width. And there should be around 10 to 20 buttons plus in the application. So then I decided to use JScrollPane to organise all the JButton horizontally. First, I add all of those JButton into JPanel which was set its Layout to GridLayout with 1 column and 10 rows. Then add that JPanel into JScrollPane. As the result, all the buttons have the same size. But the problem is that is that the JScrollBar in JScrollPane was not able to move ( may because it was not enough button to exceed the length of the JScrollPane or GridLayout always resize each button ). So then I tried to add more JButton up to 20 (pic 2). So then the JScrollBar in the JScrollPane was enable and i could move it. But unfortunatly, all the JButton in the JScrollPane was shorter and shorter everytime more buttons had been added.
I think this is because of the GridLayout that I set to JPanel that auto resize each component. So I tried to use FlowLayout but it was not satisfied as expected because the JButton was too small and cannot resize (pic3). I just wanted to keep the size of each button without changning every time more buttons are added or able to set its size.
So did anyone have any experience before about this and could share please?
public class Testing
{
public Testing()
{
JFrame frm = new JFrame();
JPanel panel = new JPanel();
JScrollPane sc = new JScrollPane();
// init frame
frm.setSize(1366, 768);
frm.setLayout(new GridLayout(5, 1, 10, 10));
// init panel
panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
// set some JScrollpane properties
sc.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
sc.setViewportView(panel);
// add few button into panel
for (int i = 0; i < 20; i++)
{
panel.add(new JButton("Button " + i));
}
frm.add(sc);
frm.setVisible(true);
frm.setLocationRelativeTo(null);
}
public static void main(String[] ar)
{
new Testing();
}
}