我希望两个不同的图像出现在两个不同的帧中。问题是这段代码不显示这两个图像(圆圈),而只显示最后一个。任何帮助将不胜感激!谢谢。
public class MyCanvas extends JPanel {
private static final long serialVersionUID = 1L;
static int paint=0;
public MyCanvas(){
}
public void paintComponent(Graphics graphics){
System.out.println("mpika!!!");
// super.paintComponent(graphics);
if(paint==0){
graphics.setColor(Color.blue);
graphics.drawOval(250,250,250,250);
}
else{
graphics.setColor(Color.red);
graphics.drawOval(150,150,150,150);
}
}
public static void other(){
JFrame frame2 = new JFrame();
MyCanvas canvas2 = new MyCanvas();
frame2.setSize(700, 700);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.add(canvas2);
frame2.setVisible(true);
Graphics graph2 = canvas2.getGraphics();
canvas2.paintComponent(graph2);
}
public static void main(String[] args){
double t;
JFrame frame = new JFrame();
MyCanvas canvas = new MyCanvas();
frame.setSize(700, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(canvas);
frame.setVisible(true);
Scanner input = new Scanner(System.in);
Graphics graph = canvas.getGraphics();
canvas.paintComponent(graph);
// t = input.nextInt();
paint=1;
other();
}
}
答案 0 :(得分:3)
您永远不会在setVisible
上致电frame2
。
同样,paint
是静态的:
static int paint = 0;
你只会看到一种颜色。
解决方案是将其变为MyCanvas
中的成员变量,类似于:
public void setColorFlag(int color)
或更好的仍然传递圆圈颜色(!)。