I am trying to draw something using paint() on my JFrame. I can't get it to show though. Why?
claass DrawOn extends JFrame{
public static void main(String args[]){
new DrawOn();
}
public DrawOn(){
setVisible(true);
pack();
}
paint(Graphics g){
g.drawOval(10,10,100,100);
}
}
You should draw in a JPanel
:
JPanel panel = new JPanel()
{
@Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
g.drawOval(10, 10, 100, 100);
}
};
Don't forget to add the JPanel
to the JFrame
:
add(panel);
Code:
public DrawOn()
{
JPanel panel = new JPanel()
{
@Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
g.drawOval(10, 10, 100, 100);
}
};
add(panel);
setPreferredSize(new Dimension(200, 200));
setVisible(true);
pack();
}
Note: You could make a class that extends JPanel
instead of using an anonymous class so your code is clearer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.