使用GridLayout,矩形不会在JPanel中垂直居中

时间:2014-01-17 13:37:23

标签: java swing jpanel orientation

如上所述,我的矩形不会在带有GridLayout的JPanel中垂直居中。我有3列。第1列和第2列有JLabel,它们完美居中,但我的自定义JPanel只是一个矩形。它的y坐标始终位于网格行的顶部。

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();
        }
    }

}

我是否必须在Bar类中添加其他方法? 谢谢:))

1 个答案:

答案 0 :(得分:0)

这是因为您从y=0绘制矩形,但您需要在面板中间绘制矩形。您可以像下一个一样在中间填充rectanle:

 g2.fillRect(0, getSize().height/2, width, 5);