A.Bal
A.Bal

Reputation: 1

How do I add a line in Java GUI?

I'm trying to add a line into my program, it runs however displays nothing, how do I fix this?

I've watched tutorials and I've come up with the following code, but it doesn't display anything. How do I fix this?

    public void paint(Graphics g)
   {
      g.drawLine(0, 0, 100, 100);
   }

Here is my full program:

import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;

public class GuiLine {

private JFrame frame;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GuiLine window = new GuiLine();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public GuiLine() {
    initialize();

}
public void paint(Graphics g)
   {
      g.drawLine(0, 0, 100, 100);
   }

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Upvotes: 0

Views: 1064

Answers (1)

Kayaman
Kayaman

Reputation: 73578

Your class GuiLine has the method paint(Graphics g), but it will never be called since the class isn't a component (nor is it added to the frame, so it wouldn't be visible).

You can make the class extend JPanel and in your initialize method call frame.add(this);. Then you can continue reading some more tutorials.

Upvotes: 1

Related Questions