[英]How to draw a line in java?
I want to draw a line in java in eclipse. 我想在eclipse中用java画一条线。 I made this code but I am getting error in line :
paint2d.add(paintComponent());
我做了这段代码,但是我在一行中遇到错误:
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. 谢谢。
You're not overriding the method correctly. 您没有正确覆盖该方法。 The argument to
paintComponent
is of type Graphics
, not Graphics2D
, but you can cast to Graphics2D
. paintComponent
的参数的类型为Graphics
,而不是Graphics2D
,但是您可以将其Graphics2D
为Graphics2D
。 Also you need to add the Game
panel to the frame as a content pane: 另外,您需要将“
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();
}
}
There are two errors in your code/approach: 您的代码/方法中有两个错误:
The source code below solves the problems. 下面的源代码解决了这些问题。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.