【发布时间】:2017-11-11 22:23:35
【问题描述】:
我有一个任务,我必须在同一个面板上绘制 6 个形状。 我尝试了几件事,但我找不到在同一个面板上绘制形状的方法,但只能在不同的面板上。
我有 Shapes 类:
public abstract class MyShape extends JPanel
public abstract class MyBoundedShape extends MyShape
public class MyOval extends MyBoundedShape
public class MyRectangle extends MyBoundedShape
public class MyLine extends MyShape
在这些类中我没有编写paintComponent方法,但我已经将它写在一个不同的类中,它接收一个形状数组作为属性:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class DrawingShapes extends JPanel implements Cloneable{
private ArrayList<MyShape> Shapes;
public DrawingShapes(ArrayList<MyShape> Shapes){
this.Shapes=Shapes;
initilizePaintComponent(); //draws a frame for the paintComponent
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for (int i = 0; i <Shapes.size(); i++) {
g.setColor(Shapes.get(i).get_color());
if (Shapes.get(i) instanceof MyRectangle){
if (((MyRectangle) Shapes.get(i)).get_isFilled()){
g.fillRect(Shapes.get(i).get_x1(),Shapes.get(i).get_y1(),
Shapes.get(i).get_width(),Shapes.get(i).get_height());
}
else
g.drawRect(Shapes.get(i).get_x1(), Shapes.get(i).get_y1(),
Shapes.get(i).get_width(), Shapes.get(i).get_height());
}
if (Shapes.get(i) instanceof MyOval){
if (((MyRectangle) Shapes.get(i)).get_isFilled()){
g.fillOval(Shapes.get(i).get_x1(),Shapes.get(i).get_y1(),
Shapes.get(i).get_width(),Shapes.get(i).get_height());
}
else
g.drawOval(Shapes.get(i).get_x1(), Shapes.get(i).get_y1(),
Shapes.get(i).get_width(), Shapes.get(i).get_height());
}
else
g.drawLine(Shapes.get(i).get_x1(), Shapes.get(i).get_y1(),
Shapes.get(i).get_width(), Shapes.get(i).get_height());
}
}
public void initilizePaintComponent(){
JFrame frame = new JFrame("Shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
for (int i = 0; i < Shapes.size(); i++) {
frame.add(Shapes.get(i));
frame.setVisible(true);
}
}
}
我的问题是 paintComponent 方法不起作用 - 程序没有绘制单个形状。
运行程序后,我得到一个名为“Shape”的空框架 - 框架确实可以工作,但没有形状。
为什么paintComponent 不起作用?
谢谢!
【问题讨论】:
-
请注意,当询问“为什么这段代码不起作用”时,您几乎必须创建并发布一个有效的minimal reproducible example。否则我们只能猜测。
标签: java swing polymorphism paintcomponent