如何在java中画一条线?

时间:2015-10-05 11:45:25

标签: java graphics2d

我想在eclipse中用java绘制一行。我制作了这段代码,但我收到错误: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);
    }
}

如何修复该错误?

我的代码是否适合绘制线条?

感谢。

2 个答案:

答案 0 :(得分:4)

您没有正确覆盖该方法。 paintComponent的参数类型为Graphics,而不是Graphics2D,但您可以转换为Graphics2D。您还需要将Game面板作为内容窗格添加到框架中:

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

}

答案 1 :(得分:0)

您的代码/方法中存在两个错误:

  1. 方法 paintComponent 有一个图形作为参数,而不是 Graphics2D
  2. 游戏是JPanel,必须添加到要显示的JFrame中。
  3. 下面的源代码解决了这些问题。

    import java.awt.Graphics;
    import java.awt.Graphics2D;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Game extends JPanel {
    
        public void paintComponent (Graphics 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);
    
            // Adds Game panel into JFrame
            frame.add(new Game());
    
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }