Reputation: 3
I'm very new to Java Swing and I'm currently trying to make a simple bar chart that visualises bubble sort algorithm. I developed the code to scale the bars depending on user inputted values, but I'm facing a problem where the bars are floating and they seem to be centered in the middle(?) like the image below Floating bars error
My code is as follows:
JPanel barPanel = new JPanel();
barPanel.setLayout(new FlowLayout());
// Default bars
int[] values = {29, 14, 90, 22, 41, 11, 3};
int maxBarHeight = 200; // Maximum height for the bars
for (int value : values) {
int barHeight = (int) ((double) value / Arrays.stream(values).max().getAsInt() * maxBarHeight);
JLabel bar = new JLabel(" ");
bar.setBackground(Color.ORANGE);
bar.setOpaque(true);
bar.setPreferredSize(new Dimension(30, barHeight));
barPanel.add(bar);
}
menuPanel.add(visualizerPanel);
menuPanel.add(barPanel);
Thank you for your help!
This is what I wish to achieve: Simple bar chart
I have tried using BorderLayout and BoxLayout. The former resulted in only one long skinny bar being displayed. The latter didn't work quite as well too as only one bar is displayed.
Upvotes: 0
Views: 69
Reputation: 324167
but I'm facing a problem where the bars are floating and they seem to be centered in the middle(?)
All Swing components have an alignmentX/Y
property which a layout manager can use (or ignore) when doing the layout.
A FlowLayout ignores this property and vertically centers all the components.
I have tried using BoxLayout.
Yes a BoxLayout
will respect the alignment property. You will need to set this property on all the components.
However, the BoxLayout
also respects the "maximum size" so you will also need to set the maximum size equal to the preferred size.
You will need changes like:
//barPanel.setLayout(new FlowLayout());
barPanel.setLayout(new BoxLayout(barPanel, BoxLayout.X_Axis));
...
bar.setPreferredSize(new Dimension(30, barHeight));
bar.setMaximumSize(bar.getPreferredSize() );
However, as mentioned in comments from above, the preferred approach is to do custom painting. It will definitely make animation the bar chart easier.
I included the above information to better help you understand layout managers and how to use them effectively.
Upvotes: 0
Reputation: 9463
This is likely caused by the FlowLayout you are using.
It is much easier to subclass JPanel, then override the paintComponent(Graphics) method to perform custom painting. Advantage: If the area you need is too big for the screen, you can resize the window and easily stuff your custom component into a JScrollPane.
There are lots of examples available, and a fine tutorial as well: https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html
So highlevel your code could look like this:
Main method:
Upvotes: 2