【问题标题】:Rectangle does not center vertically in JPanel with GridLayout矩形不垂直居中在 JPanel 与 GridLayout
【发布时间】:2014-01-17 13:37:23
【问题描述】:

如前所述,我的矩形没有在具有 GridLayout 的 JPanel 中垂直居中。我有 3 列。第一列和第二列有 JLabels,它们居中完美,但我的自定义 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 类中添加其他方法吗? 谢谢你:)

【问题讨论】:

    标签: java swing jpanel orientation


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-06-18
      • 2012-02-02
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 2013-10-15
      • 2014-06-09
      相关资源
      最近更新 更多