-
Why doesn't this work?
I am trying to get my program to draw a black rectangle in a frame. The frame pops up, but there is no rectangle. Could someone de-bug my program and tell me what I need to do to fix it?
I used Eclipse to write the program, and there were no errors found.
Thanks in advance.
import java.awt.*;
import javax.swing.*;
public class Main1 extends JFrame
{
public Main1()
{
super("Paint");
setSize(1000,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void Paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0, 0, 1000, 500);
}
public static void main(String[] args)
{
@SuppressWarnings("unused")
Main1 thisOne=new Main1();
}
}
-
To override it, your method's must match the old method's signature exactly, and the paint method of a JFrame is not static.
Other suggestions:
1) Don't draw on a JFrame. Instead draw in a JPanel or JComponent and add this to the JFrame's contentPane.
2) When drawing in the component above, override paintComponent, not paint as this will allow for Swing's automatic double buffering.
For instance:
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);
}
public MyPanel() {
setPreferredSize(new Dimension(300, 300));
setBackground(Color.black);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("MyPanel");
frame.getContentPane().add(new MyPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}