【发布时间】:2019-12-08 09:44:02
【问题描述】:
我的代码有问题:当我运行应用程序时,会显示添加到另一个 JPanel 的 JPanel,但是当父面板重新绘制时,子面板的大小会调整为 10x10 或类似的大小。 这是我的代码:
public class GUIv2 extends JPanel {
Vector<Section> sections = new Vector<>();
String backgroundImage = "";
public GUIv2(String bgImage) {
backgroundImage = bgImage;
}
public void addSection(int id, int x, int y, int width, int height) throws RuntimeException {
for(Section sec : sections) {
if(sec.getId() == id) {
throw new RuntimeException("The given ID is already registered.");
}
}
sections.add(new Section(id));
sections.lastElement().setBounds(100, 100, 100, 100);
this.add(sections.lastElement());
this.repaint();
}
public Section getSection(int id) {
for(Section sec : sections) {
if(sec.getId() == id) {
return sec;
}
}
return null;
}
protected void paintComponent(Graphics g) {
try {
g.drawImage(ImageIO.read(new File(backgroundImage)).getScaledInstance(getWidth(), getHeight(), 100), 0, 0, null);
}
catch(IOException e) {
}
}
}
我希望有人可以帮助我解决这个问题。提前致谢
【问题讨论】:
-
显示添加到另一个 JPanel 的 JPanel, - JPanel 的默认布局管理器是 FlowLayout,它尊重添加到其中的任何组件的首选大小。您没有设置绘画面板的首选尺寸,因此在布局完成后您只能获得 (10 x 10) 正方形。您需要设置首选尺寸。阅读 Custom Painting 上的 Swing 教程中的部分以获取工作演示。从工作演示代码开始,然后根据您的要求进行修改。
标签: java swing resize jpanel repaint