如何在 JComponent 的底部绘制一个白色矩形?

How to draw a white rectangle at the bottom of a JComponent?

在我的代码中我有:

一个带有 JScrolledPane 的 Gui 包含一个包含一些 JPanel 的盒子(如果需要,它们可以重构为 JComponent)。

见图 1:

我正在尝试:

找到在它们之间添加白色 space 的最佳方法。

我尝试使用 Box.createVerticalStruct,但它使管理变得复杂。 我也不想向代表 coloredPanel 的对象添加一个新的白色面板,所以我用谷歌搜索了一下,在我看来还有其他两种方法:使用 inset 或重写 paint 方法。

你认为对我来说最好的方法是什么? 如果您建议使用 paintComponent 方法,我如何检索底角位置以绘制特定高度的白色矩形?

最终结果应该是这样的:

这里有一些代码你可以用来做一些尝试(这是故意写的,所以不要太在意好的写作技巧):

public class TheMotherPuckerGlue2 {

    public static void main(String [] a) {
        final JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setTitle("myCode");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JScrollPane myPane = new JScrollPane();
        myPane.setPreferredSize(new Dimension(350,200));
        myPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel viewPort = new JPanel(new BorderLayout());
        viewPort.setBackground(Color.WHITE);

        Box myBox = Box.createVerticalBox(); 
        myBox.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));

        viewPort.add(myBox,BorderLayout.PAGE_START);

        class ColoredPanel extends JPanel{
            public ColoredPanel(Color aColor){
                super.setBackground(aColor);
                super.setPreferredSize(new Dimension(100,60));
            }

        }

        ColoredPanel panel1 = new ColoredPanel(Color.green);
        ColoredPanel panel2 = new ColoredPanel(Color.yellow);
        ColoredPanel panel3 = new ColoredPanel(Color.red);

        myBox.add(panel1);
        myBox.add(panel2);
        myBox.add(panel3);

        viewPort.add(myBox,BorderLayout.PAGE_START);


        myPane.setViewportView(viewPort);

        frame.add(myPane);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
   }

}

谢谢

我找到了一个很好的方法来重写 paintComponent:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    drawWhiteSpace(g);
    drawBorder(g);
}

drawWhiteSpace 方法将从左下角开始绘制一个白色矩形 corner -6像素,到右下角

private void drawWhiteSpace(Graphics g) {
    int x1 = 0;
    int y1 = this.getSize().height-6;
    int x2 = this.getSize().width;
    int y2 = this.getSize().height;
    g.setColor(Color.WHITE);
    g.fillRect(x1, y1, x2, y2);     
}   

但是边框不太好,所以我不得不将其移除并绘制 我自己从白色的左上角画到右上角space

private void drawBorder(Graphics g) {
    int x1 = 0;
    int y1 = 0;
    int x2 = this.getSize().width-1;
    int y2 = this.getSize().height-6;
    g.setColor(Color.GRAY);
    g.drawRect(x1, y1, x2, y2); 
}