Reputation: 163
At this site I have found a good example how to apply JScrollPane for a matrix of JButtons. The code is here below provided.
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int x = 10;
int y = 5;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(x, y));
for (int i = 0; i < x * y; i++) {
JButton button = new JButton(String.valueOf(i));
button.setPreferredSize(new Dimension(100, 20));
panel.add(button);
}
JPanel container = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
container.add(panel);
JScrollPane scrollPane = new JScrollPane(container);
f.getContentPane().add(scrollPane);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
How shall I modify the code if I would like my buttons to have arbitrary sizes and arbitrary positions with same scrolling possibilities. Many thanks in advance for any hint or advise.
p.s. I have modified the code above trying to shape the buttons as shown on the picture, but setBounds settings seem to be ignored.
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int x = 10;
int y = 5;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(x, y));
JButton button1 = new JButton("JButton1");
JButton button2 = new JButton("JButton2");
JButton button3 = new JButton("JButton3");
JButton button4 = new JButton("JButton4");
button1.setBounds(0, 0, 100, 50);
button2.setBounds(100, 25, 100, 25);
button3.setBounds(0, 50, 80, 200);
button4.setBounds(80, 50, 250, 60);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
JPanel container = new JPanel(new
FlowLayout(FlowLayout.CENTER, 0, 0));
container.add(panel);
JScrollPane scrollPane = new JScrollPane(container);
f.getContentPane().add(scrollPane);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
The wrong result:
What else shall I change to have the buttons placement as expected?
Upvotes: 0
Views: 40
Reputation: 285405
It's no different from the other problem: you put the JPanel that holds all the JButtons into the JScrollPane's viewport. That's it. The key will be what layout manager(s) will be used by the JPanel(s) that hold the buttons. the specifics will matter, since those panels and layouts will determine the preferred size of the containing jpanel, which will be the scroll pane's viewport's view.
The specifics of your problem will depend on the exact specifics of the irregular buttons that you place, something that you have not told us.
Upvotes: 1