Reputation: 317
I have a custom component called FixtureComponent that extends JPanel, it is basically a JPanel containing a number of controls placed inside it, each with it's own size and location. What I am trying to do is to place a number of FixtureComponent vertically in my JFrame as follows:
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main frame = new main();
FixtureComponent comPanel = new FixtureComponent();
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.setSize(300, 400);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
for (Integer i = 0; i < 20; i++)
{
frame.getContentPane().add(comPanel);
}
frame.setVisible(true);
}
});
}
The problem I am getting is when I run the above code, I get a single FixtureComponent placed at the top of the JFrame instead of getting 20 FixtureComponents placed vertically above each other.
And I would like to also know in case of that I successfully got the above code to work, how to add a scroll bar to scroll across the FixtureComponent?
Thank you.
Upvotes: 0
Views: 731
Reputation: 1164
Create and add a JScrollPane
to the frame, setting the JScrollPane
context to the content you need scrolling, in the example below this is a JPanel
named container
.
Add your FixtureComponent
objects to container
, and boom. Here's the code:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Main frame = new Main();
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
JScrollPane scroller = new JScrollPane(container);
scroller.setPreferredSize(new Dimension(200, 1000));
for (Integer i = 0; i < 20; i++) {
FixtureComponent fixture = new FixtureComponent();
container.add(fixture);
}
frame.setLayout(new BorderLayout());
frame.add(scroller, BorderLayout.WEST);
frame.setSize(300, 400);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
Upvotes: 2