How to draw a line in java?

11,369

You're not overriding the method correctly. The argument to paintComponent is of type Graphics, not Graphics2D, but you can cast to Graphics2D. Also you need to add the Game panel to the frame as a content pane:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel
{

    @Override
    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.BLACK);
        g2.drawLine(30, 40, 80, 100);
    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(400, 420);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Game game = new Game();
        frame.setContentPane(game);

        frame.setVisible(true);
        frame.invalidate();
    }

}
Share:
11,369
Admin
Author by

Admin

Updated on June 24, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to draw a line in java in eclipse. I made this code but I am getting error in line : paint2d.add(paintComponent());

    import java.awt.Graphics2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Game extends JPanel {
    
        public void paintComponent (Graphics2D g) {
            Graphics2D g2 = (Graphics2D) g;
            g2.drawLine(30, 40, 80, 100);
        }
    
        public static void main(String[] args) {
    
            JFrame frame = new JFrame();
            frame.setSize(400, 420);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Game paint2d = new Game();
            paint2d.add(paintComponent()); // The method paintComponent(Graphics2D) in the type Game is not applicable for the arguments ()
            frame.setVisible(true);
        }
    }
    

    How to fix that error?

    Is my code suitable for the purpose of drawing a line?

    Thanks.