在Java GUI中更改矩形颜色

时间:2016-07-01 17:07:48

标签: java swing user-interface paintcomponent

如何更改矩形的颜色?我想把它变成黄色。我在g.setColor(Color.YELLOW);内添加了rectDraw,但矩形的颜色仍然保持不变。有人能告诉我,我做了什么错吗?

 public class SelectSeat {

    static JFrame frame;

    public JPanel createContentPane() throws IOException
    {

        JPanel totalGUI = new JPanel();
        RectDraw rect= new RectDraw();
        rect.setPreferredSize(new Dimension(330,35)); //for size
        totalGUI.setLayout(null);
        totalGUI.setBackground(Color.WHITE);
        totalGUI.add(rect);
        Dimension d = rect.getPreferredSize();
        rect.setBounds(100, 20, d.width, d.height); // for location
        return totalGUI;
    }

        void setVisible(boolean b) {
        // TODO Auto-generated method stub

    }

    static void createAndShowGUI() throws IOException
    {

        JFrame.setDefaultLookAndFeelDecorated(true);
        frame = new JFrame("Seat Selection");
        //Create and set up the content pane.
        SelectSeat demo = new SelectSeat();
        frame.setContentPane(demo.createContentPane());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(535, 520);
        frame.setLocation(500,220);
        frame.setVisible(true);
    }

    private static class RectDraw extends JPanel
    {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);  
             g.setColor(Color.BLUE);
             g.drawString("Movie Sceen", 130, 20);   
            }


    }

}

enter image description here

1 个答案:

答案 0 :(得分:2)

  

如何更改矩形的颜色?我想把它变成黄色。

您需要将颜色设置为黄色,然后填充组件大小的矩形。

protected void paintComponent(Graphics g) {
    super.paintComponent(g);  
    g.setColor(Color.YELLOW);
    g.fillRect(0,0,getWidth(), getHeight());
    g.setColor(Color.BLUE);
    g.drawString("Movie Sceen", 130, 20);   
}

以及它的价值:

totalGUI.setLayout(null);

我建议不要使用null布局。使用适合该任务的LayoutManager,并记住您可以在Component层次结构中嵌套布局。