AI. AI. - 5 months ago 8
Java Question

Change rectangle color in Java GUI

How to change the color of rectangle ? I want change it to yellow color. I added

g.setColor(Color.YELLOW);
inside
rectDraw
, but the color of the rectangle still remain the same. Can someone tell me what wrong I did please? Thanks a lot!

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

Answer

How to change the color of rectangle ? I want change it to yellow color.

You need to set the color to yellow, followed by filling a rectangle the size of the component.

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

And for what its worth:

totalGUI.setLayout(null);

I would recommend against using null Layouts. Use a LayoutManager appropriate to the task, and remember that you can nest layouts within the Component hierarchy.

Comments