Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to draw a line using the Graphics 2D but then the line appears over all the other components in the JFrame thus making them invisible. How do I correct this problem?

Here's 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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
300 views
Welcome To Ask or Share your Answers For Others

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);
    }
}

Further tips

  1. Create the GUI on the EDT. See Concurrency in Swing for more details.
  2. Use a JPanel as suggested by @nIcEcOw, override paintComponent(Graphics) instead of paint(). Again, call the super method first.
  3. Don't extend frame, just use an instance of one. Set the size according to the space required for the components using pack().

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...