-2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class GraphicsFunda extends JPanel implements ActionListener
{
 Graphics myg;
 JButton jb;
 GraphicsFunda()
{

 jb = new JButton("Draw");
 add(jb);
 setBackground(Color.YELLOW);
 jb.addActionListener(this);
}
public void paintComponent(Graphics g)
{ 
 myg=g;
 g.drawOval(100,300,50,50);
}
public void actionPerformed(ActionEvent ae)
{
 if(ae.getSource()==jb)
 myg.fillRect(10,10,200,200);
}  
public static void main(String... sd)
{
 GraphicsFunda gf = new GraphicsFunda();
 JFrame jf = new JFrame();
 jf.add(gf,BorderLayout.NORTH);
 jf.setBackground(Color.blue);
 jf.setSize(400,400);
 jf.setVisible(true);
}

} Please Help me to solve the problem in it. If we take the reference of Graphics class from paintComponent, then can we use it in drawing other shapes, but it is not working here :(

mKorbel
  • 109,525
  • 20
  • 134
  • 319

3 Answers3

2

You can't keep the instance of Graphics and call it whenever you want like this. Painting should be done exclusively in the paintComponent() method, using the Graphics object passed as argument.

In your actionPerformed() method, change the state of the panel, and call repaint(). Then, in the paintComponent() method, read the state of the panel, and paint accordingly. The state, in your case, could be a list of shapes to paint, for example.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

When you draw on a graphics outside of the paint type methods, then you tend to have problems. All the drawing to a JPanel's Graphics should happen inside of the paintComponent method. Overwise, even if this worked, the changes would get overwritten when the user does something like resize the screen, when repaint is called.

If you can't restructure the program to only do draws in paintComponent, one alternative is to do all of your drawing to a BufferedImage, and then simply redraw the image to the Graphics on a repaint. OF course, this also has problems (such as higher cost to resize if the image isn't big enough), so this should not be the goto method; instead, change your code so the repaint method knows what to draw if at all possible.

resueman
  • 10,572
  • 10
  • 31
  • 45
0

All painting should be done within the context of your paintComponent method (which has already being highlighted), but this raises the question of how?

You should be placing some kind of paintable object in a List, which contains information about what, where and how big.

The easiest solution would be to use something like classes that extend from Shape, these can simply be drawn or filled via the Graphics context

See...

For more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366