gpt4 book ai didi

java - 如何在java中画一条线?

转载 作者:行者123 更新时间:2023-11-30 06:58:07 24 4
gpt4 key购买 nike

我想在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);
}
}

如何修复该错误?

我的代码适合画线吗?

谢谢。

最佳答案

您没有正确覆盖该方法。 paintComponent 的参数是 Graphics 类型,而不是 Graphics2D,但您可以转换为 Graphics2D。您还需要将 Game 面板作为内容 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();
}

}

关于java - 如何在java中画一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com