I want to create a JFrame and add panel to it ,the problem in drawing line in this panel

package panel;

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

public class Main {

    public static void main(String[] args) {
      JFrame window = new JFrame();
		window.setSize(200, 200);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                Graphics g =null ;
                g.drawLine(50, 50, 20, 25);
                JPanel panel = new JPanel();
	        panel.paintComponents(g);
		window.add(panel);
		window.setVisible(true);
	}
    }

Your Graphics variable is set to null. Therefore a null object is passed to the paintComponents();

Graphics g=null;

I guess you need to create a new Graphics object like below.

Graphics g= new Graphics();

Your Graphics variable is set to null. Therefore a null object is passed to the paintComponents();

Graphics g=null;

I guess you need to create a new Graphics object like below.

Graphics g= new Graphics();

Graphics is abstract class and if I'm take object from it i must call all methods in her

you have look for method paintComponent, check tutorial Graphics

you have look for method paintComponent, check tutorial Graphics

thank u :D

You can't do drawing in Swing like that, it's not how it works.
Create and use a subclass of JPanel and override its paintComponent method. When Swing needs to display your panel it will call your paintComponent, passing the correct Graphics object (actually an instance of Graphics2D) for you to draw your line on.

You can't do drawing in Swing like that, it's not how it works.
Create and use a subclass of JPanel and override its paintComponent method. When Swing needs to display your panel it will call your paintComponent, passing the correct Graphics object (actually an instance of Graphics2D) for you to draw your line on.

I do that now :D , thank you

public class MyPanel extends JPanel {
   
 @Override
 public void paintComponent(Graphics g)
 {
             super.paintComponent(g);
             g.drawLine(20, 100, 20, 20);
 }

 @Override
   public Dimension getPreferredSize()
  {
   return new Dimension(400, 350);
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.