0

I have main JFrame which contains a JPanel and all component on it. I've drawn a diagram on my main Jframe, I've used getGraphics() method to draw shapes on JPanel.I want to convert it into another diagram so the new diagram display on new Jframe but I am not able to draw any shapes on panel of newly created frame .(I've also try to use same getGraphics() method to draw as I've used in main Jframe).

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Transformation extends javax.swing.JFrame {

    private JPanel myPanel;
    public Transformation() {

    this.setSize(500, 500);
    this.setVisible(true);
    myPanel = new JPanel(new FlowLayout());
    myPanel.add(new JButton("Hello"));
    this.getContentPane().add(myPanel);
    Graphics2D g = (Graphics2D) myPanel.getGraphics();
    g.draw(new Line2D.Double(20, 50, 100, 200) );

    }
}

in main Jframe I've called following line in a Jbutton's action listener.

Transformation tfm = new Transformation();

iostream007
  • 107
  • 1
  • 10
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Apr 24 '13 at 10:00
  • 2
    *"I've used getGraphics() method to draw shapes"* That is the wrong way to go about custom graphics unless the method is being called on a `BufferedImage`. See [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) for the right way to do it in components. – Andrew Thompson Apr 24 '13 at 10:01
  • 1
    _I've used getGraphics()_ Very very bad idea. – Guillaume Polet Apr 24 '13 at 10:01
  • @GuillaumePolet I keep wondering where so many people get that bad idea.. :( – Andrew Thompson Apr 24 '13 at 10:04
  • @AndrewThompson to draw each shape i've different class so when i want to draw a shape i use dedicated method like this one Graphics g = MyPanel.getGraphics(); Activity activity = new Activity(); Activity is class that contain its shapes info – iostream007 Apr 24 '13 at 10:19
  • 1
    If you wish to do do incremental drawing, use a `BufferedImage` as seen in [this answer](http://stackoverflow.com/a/10628553/418556). – Andrew Thompson Apr 24 '13 at 10:23
  • @AndrewThompson I wonder that too, though I also wonder why this method was made `public`. It would have probably been better to somehow "hide" the method by changing the visibility or by prefix the name of the method with an underscord if `public` visibility was absolutely necessary. – Guillaume Polet Apr 24 '13 at 11:49

0 Answers0