0
我有一个叫做DrawRectangles
的类,它接受一个整数数组。如何使用Java中的循环将多个面板添加到JFrame?
我想要做的是通过数组中的数字和每一个,使用数组中的数字作为面板的宽度和X位置创建一个新面板。
比方说,我通过了[2,4,6,8]。我想创建一个新面板,将其添加到JFrame
中,每个数字都是这样。
所以第一个面板应该从位置2开始,宽度为2.我也有一个随机颜色生成器,它应该为每个面板创建一个新的颜色。以下是我有:
public class DrawRectangles {
JFrame frame;
DrawPanel panel;
Random randomGenerator = new Random();
int red = randomGenerator.nextInt(255);
int green = randomGenerator.nextInt(255);
int blue = randomGenerator.nextInt(255);
Color randomColor;
int[] newWidth;
DrawRectangles(int[] width){
this.newWidth = width;
}
public void setUpFrame(){
frame = new JFrame();
frame.setSize(500,100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(int x = 0; x < newWidth.length; x++){
panel = new DrawPanel(newWidth[x]);
frame.add(panel);
}
}
class DrawPanel extends JPanel{
int newWidth;
DrawPanel(int width){
this.newWidth = width;
System.out.println(newWidth);
}
public void paint(Graphics g) {
super.paint(g);
randomColor = new Color(red,green,blue);
g.setColor(randomColor);
g.fillRect(newWidth, 10, newWidth, 30);
}
}
}
1-帧有一个默认布局('BorderLayout'),它只允许一个组件存在于它的5个预配置位置。 2-你的'DrawPanel'不提供任何类型的大小提示给布局管理器,这意味着(除非他们忽略它),组件的大小将被设置为0x0。 3-你应该重载'paintComponent'而不是'paint' – MadProgrammer