我创建了一个名为 Robit 的类(故意拼写错误),它使用 paint(Graphics g)
方法定义了一个正方形。我正在扩展 JFrame,一切正常,我只是无法绘制方 block
import java.awt.*;
public class Robit {
int[] location = new int[4];
double[] vectors = new double[2];
Color mainColor;
public Robit(Color color, int x) {
mainColor = color;
switch (x) {
case 0:
location[0] = 50;
break;
case 1:
location[0] = 700;
break;
default:
location[0] = 350;
break;
}
location[1] = 400;
location[2] = 50;
location[3] = 50;
}
public void paint(Graphics g) {
g.setColor(mainColor);
g.fillRect(location[0], location[1], location[2], location[3]);
}
public int getX() {
return location[0];
}
public int getY() {
return location[1];
}
}
`这就是我实例化的类,这就是我创建它的地方 导入java.awt.Color; 导入 javax.swing.*;
public class Frame extends JFrame {
public Frame(){
setLayout(null);
Robit r1 = new Robit(Color.red, 0);
Robit r2 = new Robit(Color.blue, 1);
}
}
和主类
import javax.swing.JFrame;
public class App {
public static void main(String[] args) {
Frame f = new Frame();
f.setSize(800, 450);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
最佳答案
您没有在 Robit
类上调用 paint
方法。请尝试以下操作:
public class Frame extends JFrame {
protected Robit r1;
protected Robit r2;
public Frame(){
setLayout(null);
r1 = new Robit(Color.red, 0);
r2 = new Robit(Color.blue, 1);
}
public void paint(Graphics g)
{
super.paint(g);
r1.paint(g);
r2.paint(g);
}
}
关于java - 用paint实例化一个类来制作一个正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415694/