Search code examples
javaswingjframegraphics2d

Drawing a line on another JFrame in a class that extends JFrame


I have a class with two JFrames and am trying to draw a line on a particular frame .

I tried the code below but it only appears in the first frame which is the success frame.

It also appears above all the other components of the success frame thus making all other

components invisible. It does not appear in the comp Frame.

How do I correct this.

Here is the code I have so far :

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;

public class lineGUI{
public static void main(String []args){
Success s=new Success();
s.setVisible(true);
  }
}

class Success extends JFrame{

JPanel alas =new JPanel();
JFrame comp =new JFrame();
public Success(){
JPanel panel=new JPanel();
getContentPane().add(panel);
setSize(450,450);

JButton button =new JButton("press");
panel.add(button);

  comp.setSize(650,500);
  comp.setTitle("View Report");

  JRootPane compPane=comp.getRootPane();
  Container contePane=compPane.getContentPane();
  contePane.add(alas);


    ActionListener action =new ActionListener(){
      public void actionPerformed(ActionEvent e){
        if (e.getSource()==button){
          comp.setVisible(true);
        }
      }
    };
    button.addActionListener(action);

  JButton button2=new JButton("access");
  alas.add(button2);
 }

public void paint(Graphics g) {
comp.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
  }
}

Solution

  • You've got some crazy code up there. Suggestions:

    • Don't draw directly in a JFrame, but in a the paintComponent method of an object derived from JComponent such as JPanel or JComponent itself.
    • Your drawing directly in another component's paint(...) method is not kosher at all. Why not simply share the data between classes, and use the data (the ints) to draw where desired.
    • You would rarely want to have a GUI display more than one JFrame at a time. Usually one window is the main window (the JFrame), and it often owns any other windows which would be dialog windows such as JDialogs.
    • Read the graphics tutorials to learn the correct way to do Swing Graphics