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

时间:2015-10-23 08:16:51

标签: java swing paintcomponent

在我的代码中我有:

一个JScrolledPane包含一个包含JPanel的{​​{1}}的Gui(如果需要,它们可以重构为JComponent。)

见图1:

example

我想:

找到在它们之间添加空白区域的最佳方法。

我尝试使用Box.createVerticalStruct,但它使管理变得复杂。 我不想在我的对象上添加一个新的白色面板代表coloredPanel,所以我用Google搜索了它,在我看来还有其他两种方法:使用插入或覆盖绘制方法。

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

最终结果应该是这样的:

enter image description here

以下是一些可以用来尝试的代码(这些代码是故意编写的,所以不要过分关注良好的写作技巧):

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

}

由于

1 个答案:

答案 0 :(得分:0)

我找到了一种很好的方法,通过这种方式重写paintComponent:

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

drawWhiteSpace方法将绘制一个从左下角开始的白色矩形 转角-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);     
}   

然而边界不好,所以我不得不将其移除并绘制它 我自己从左上角到白色空间的右上角绘制

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); 
}
相关问题