I’ve been trying to get my feet wet with Java lately. However, I’m following an example from a book but having trouble getting it to work. Can someone please tell me what I’m doing wrong?
I’m trying to get an orange rectangle to be painted on a window. The code I have is as follows:
import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel {
public static void main(String[] args) {
MyDrawPanel gui = new MyDrawPanel();
gui.go();
}//close main
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setVisible(true);
}//close go
public void paintComponet(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}//close paintComponent
}//close class
From what I understand, the program is supposed to call paintComponent on it’s own; I don’t have to call it. So, why can’t I get an orange rectangle?
I’m taking a guess here as I haven’t really worked with Swing musch, but try calling update() from within the paint method, passing the Graphics object to it.
The JFrame is a regular window that you’d see on your screen. But that’s all it is. You need to add your panel to its content pane in order for your panel to be seen.
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
this.setSize(600,600);
frame.getContentPane().add(this); // right here
frame.setVisible(true);
}//close go
Basic misunderstanding here - the paintComponent you overrode is for your JPanel subclass which you aren’t even displaying. The only function it is serving is to define your main(). You create an independent frame and display it.
You may have intended something like this, or what I see Eegba suggests, which doesn’t completely override the painting of the whole container, like I’m doing here:
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
public class MyFrame extends JFrame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
JFrame frame = new MyFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.show();
} catch (Exception ex) {
System.err.println(ex);
}
}
public void paint(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
}