任何人都可以告诉我为什么在我的GUI类中调用矩形时不会创建矩形。我想要做的就是根据我的矩形类创建一个矩形,但是我在下面的DataPanel类中得到了这些错误,并且无法找出原因。
Error:(21, 5) java: illegal start of expression
Error:(21, 15) java: illegal start of expression
Error:(21, 25) java: ';' expected
Error:(21, 36) java: ';' expected
public class DrawRooms{
int x,y,width,height;
public DrawRooms() {
x = 0;
y = 0;
width = 0;
height= 0;
}
public DrawRooms(int x, int y, int w, int h){
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
public void draw(Graphics2D g2d) {
g2d.drawRect(x, y, width, height);
}
//sets x coordinate
public void setX(int x) {
this.x = x;
}
//sets y coordinate
public void setY(int y) {
this.y = y;
}
//sets width
public void setWidth(int w) {
this.width = w;
}
//sets height
public void setHeight(int h) {
this.height = h;
}
//gets x
public int getX() {
return x;
}
//gets y
public int getY() {
return y;
}
//gets width
public int getWidth() {
return width;
}
//gets height
public int getHeight() {
return height;
}
//toString to report values
@Override
public String toString(){
String s = "\nX-Coordinate: " + getX() +
"\nY-Coordinate: " + getY() +
"Width: " + getWidth() +
"Height : " + getHeight();
return s;
}
}
public class DataPanel extends JPanel {
public DataPanel() {
repaint();
buildPanel();
setVisible(true);
}
public void buildPanel() {
DrawRooms room = new DrawRooms(50, 100, 600, 600);
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
room.draw(g2d);
}
}
}
答案 0 :(得分:0)
您已将paint-method放入buildPanel(..){..}这是错误的 语法。
所以从buildPanel(...)
执行paint(...)
同样做点什么,
DrawRooms room ;
public void buildPanel() {
room = new DrawRooms(50, 100, 600, 600);
}
protected void paint(Graphics g) { // put this method out of buildPanel()
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
room.draw(g2d);
}