Java 使用paint实例化类以生成正方形
我创建了一个名为Robit(故意拼写错误)的类,它使用Java 使用paint实例化类以生成正方形,java,swing,object,awt,paint,Java,Swing,Object,Awt,Paint,我创建了一个名为Robit(故意拼写错误)的类,它使用paint(Graphics g)方法定义了一个正方形。我正在扩展JFrame,所有的工作都很好,我只是不能让正方形来画画 import java.awt.*; public class Robit { int[] location = new int[4]; double[] vectors = new double[2]; Color mainColor; public Robit(Color color, int x) {
paint(Graphics g)
方法定义了一个正方形。我正在扩展JFrame,所有的工作都很好,我只是不能让正方形来画画
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);
}
}
setLayout(空)代码>Java GUI必须在不同的操作系统、屏幕大小、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或与布局填充和边框一起使用public class Frame扩展了JFrame..
这对于自定义类来说是个糟糕的名字,因为有一个java.awt.Frame
。不如改为RobitsFrame
?