Question

as said my rectangle does not center vertically in a JPanel with GridLayout. I have 3 columns. 1st and 2nd column have JLabels and they are centered perfect, but my custom JPanel which is just a rectangle does not. It's y coordinate is always on top of the grid's row.

public class CustomJPanel {
    /**
     * @param args
     */
    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 200);
        frame.setResizable(false);
        JPanel panel = new JPanel(new GridLayout(0,3));
        JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.setBounds(10, 50, 320, 200);
        scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));


        for(int i=0; i<3; i++){
            JLabel nameLabel = new JLabel("Test"+i);
            JLabel timeLabel = new JLabel();
            timeLabel.setText("0h 0m 0s");
            panel.add(nameLabel);
            panel.add(timeLabel);
            panel.add(new Bar());
        }

        frame.add(scrollPane);
        frame.setVisible(true);
    }

    private static class Bar extends JPanel {
        int width = 100;
        Dimension maxDimension = new Dimension(100, 20);

        @Override
        public void paintComponent(Graphics g){
            super.paintComponents(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.BLUE);
            g2.fillRect(0, 0, width, 5);
        }

        @Override
        public Dimension getMaximumSize() {
            return maxDimension;
        }

        @Override
        public Dimension getPreferredSize(){
            return this.getMaximumSize();
        }
    }

}

Do I have to add other methods to my Bar class? Thank you :)

Was it helpful?

Solution

That happens because you draw rectangle from y=0, but you need to draw that at the middle of your panel. You can fill rectanle in the middle like next :

 g2.fillRect(0, getSize().height/2, width, 5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top