我想在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
返回void。绘画不必显式调用。请查看https://dev59.com/zW025IYBdhLWcg3wyJCV。 - hotzstpaintComponent
方法的返回类型是void
,我认为这就是错误的原因。 - Tirathpaint2d.add(frame);
和frame.add(Game);
但它们都没有起作用..谢谢。 - user5309808frame.add(paint2d)
- Pshemo