I am having a problem adding graphics to a JPanel. If I change the line from panel.add(new graphics()); to frame.add(new graphics()); and do not add the JPanel to the JFrame, the black rectangle appears on the JFrame. I just cannot get the black rectangle to appear on the JPannel and was wondering if someone could help me with this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Catch{
public class graphics extends JComponent{
public void paintComponent(Graphics g){
super.paintComponents(g);
g.fillRect(200, 62, 30, 10);
}
}
public void createGUI(){
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(500,500);
frame.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint().getX());
System.out.println(e.getPoint().getY());
}
});
panel.add(new graphics());
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args){
Catch GUI= new Catch();
GUI.createGUI();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…