javaswinguser-interfacejpanelflowlayout

Java Swing bars floating instead of starting from the same baseline


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.


Solution

  • 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: