gpt4 book ai didi

java - 我们必须导入一些东西才能使用draw()吗?

转载 作者:行者123 更新时间:2023-12-01 17:07:27 26 4
gpt4 key购买 nike

我试图使用 eclipse 在 java 中绘制一些矩形,并且调用 draw() 方法给我一个错误。我在这里缺少什么吗?

import java.awt.Rectangle;

public class UsingRectangle {
public static void main(String[] args) {
Rectangle box1 = new Rectangle(0, 0, 20, 30);

//error "The method draw() is undefined for the type Rectangle"
box1.draw();
}
}

任何帮助将不胜感激。谢谢。

最佳答案

首先通读:

矩形是形状的表示,它本身没有如何绘制的概念,但可以通过适当的API进行绘制

Rectangle

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class PaintRectangle {

public static void main(String[] args) {
new PaintRectangle();
}

public PaintRectangle() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private Rectangle box1;

public TestPane() {
box1 = new Rectangle(0, 0, 20, 30);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fill(box1);
g2d.setColor(Color.BLUE);
g2d.draw(box1);
g2d.dispose();
}
}

}

关于java - 我们必须导入一些东西才能使用draw()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24857236/

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