Reputation: 5697
This code should create a black window, and then add a line and polygon over it.
public class gui extends JFrame {
JPanel pane = new JPanel();
gui(String title){
super(title);
setBounds(100,100,500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
pane.setBackground(new Color(0,0,0));
con.add(pane);
setVisible(true);
}
public void paint(Graphics g){
g.drawLine(100, 100, 400, 400);
Point p1 = new Point(400, 100);
Point p2 = new Point(100, 300);
Point p3 = new Point(200, 400);
int[] xs = { p1.x, p2.x, p3.x };
int[] ys = { p1.y, p2.y, p3.y };
Polygon triangle = new Polygon(xs, ys, xs.length);
g.setColor(new Color(250,0,0));
g.fillPolygon(triangle);
}
}
When I delete the paint()
method, a plain black GUI is created, as expected.
However, when the paint()
method is in place, you get the line and polygon over a white background, not a black background.
How can I make the black background show through?
Upvotes: 0
Views: 433
Reputation: 159754
You need to call
super.paint(g);
in your paint
method.
In Swing the preferred approach is to override paintComponent
although since JFrame
is not actually a JComponent
this method will not be called. To use this approach, the functionality could be moved to a custom JComponent
instead.
Upvotes: 3