繁体   English   中英

在带有GridLayout的JPanel中,矩形不垂直居中

[英]Rectangle does not center vertically in JPanel with GridLayout

如前所述,我的矩形在带有GridLayout的JPanel中未垂直居中。 我有3栏。 第一列和第二列具有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类中添加其他方法? 谢谢 :)

发生这种情况是因为您从y=0绘制了矩形,但是需要在面板的中间绘制矩形。 您可以像下面这样在中间填充矩形:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM