Drawing a string on a JFrame

I try to draw a line using Graphics 2D, but then the line appears above all the other components in the JFrame , which makes them invisible. How to fix this problem?

Here is the code:

 import javax.swing.*; import java.awt.*; import java.awt.geom.*; class Success extends JFrame{ public Success(){ JPanel panel=new JPanel(); getContentPane().add(panel); setSize(450,450); JButton button =new JButton("press"); panel.add(button); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Line2D lin = new Line2D.Float(100, 100, 250, 260); g2.draw(lin); } public static void main(String []args){ Success s=new Success(); s.setVisible(true); } } 
+7
source share
1 answer
 import javax.swing.*; import java.awt.*; import java.awt.geom.*; class Success extends JFrame{ public Success(){ JPanel panel=new JPanel(); getContentPane().add(panel); setSize(450,450); JButton button =new JButton("press"); panel.add(button); } public void paint(Graphics g) { super.paint(g); // fixes the immediate problem. Graphics2D g2 = (Graphics2D) g; Line2D lin = new Line2D.Float(100, 100, 250, 260); g2.draw(lin); } public static void main(String []args){ Success s=new Success(); s.setVisible(true); } } 

Additional tips

  • Create a GUI on EDT. See Concurrency in Swing for more details.
  • Use JPanel , as suggested by @nIcEcOw, override paintComponent(Graphics) instead of paint() . Again, call the super method first.
  • Do not expand the frame, just use an instance of one. Set the size according to the volume needed for the components using pack() .
+9
source

All Articles