동일한 패널에 6 개의 도형을 그려야하는 과제가 있습니다. 여러 가지 시도를했지만 동일한 패널에 도형을 그리는 방법을 찾을 수는 없지만 다른 패널에서만 사용할 수 있습니다. 나는의 paintComponent 방법 작성하지 않은 이 클래스에서Java - paintComponent 및 다형성을 사용하여 도형 그리기
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
,하지만 난 속성으로 모양의 배열을 접수에 diffreent 클래스에 작성했습니다 :
이 나는 모양에 대한 수업을 :
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"라는 빈 프레임을 얻습니다. 프레임은이지만 Shapes는 작동하지 않습니다.
왜 paintComponent가 작동하지 않습니까?
감사합니다.
"이 코드가 작동하지 않는 이유"를 묻는 경우 유효한 [mcve]를 작성하고 게시해야합니다. 그렇지 않으면 우리는 추측 할 수 있습니다. –