【发布时间】:2013-10-16 18:43:32
【问题描述】:
我正在尝试将图像绘制到面板上,该面板包含在框架中。
假设我有一张 320 x 480 的图像。 当我尝试创建一个大小为 320x480 的框架并将面板添加到其中时,我遇到了一个问题。
在不同的操作系统中,320x480 的 JFrame 因标题栏大小不同。 因此,我在 Windows XP 中的正确匹配图像将无法在 Windows8 或 Ubuntu 中正确绘制。
由于图像放置不正确,因此可以看到灰色补丁。 我尝试覆盖绘画方法并使用 ImageIcon。
请提供解决方案。
TIA
代码片段
CLASS PA CONTENTS
setPreferredSize(new Dimension(500,500));
.
.
JLabel image= new JLabel();
ImageIcon background = new ImageIcon(getClass().getClassLoader().getResource("Flower.jpg"));
image.setBounds(0, 0, 500, 500);
image.setIcon(background);
this.add(image); //where "this" is extending from JPanel
CLASS PB CONTENTS
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inserting(frame.getContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
private void inserting(Container pane)
{
cardPanel=new JPanel();
CardLayout cards=new CardLayout();
cardPanel.setLayout(cards);
PA home= new PA();
cardPanel.add(home,"homeScreen");
pane.add(cardPanel);
}
【问题讨论】:
-
为了尽快获得更好的帮助,请提供SSCCE
-
您是否尝试过在您的 JFrame 上调用
pack()而不是明确设置其大小? -
是的,我使用了 pack,因为我明确指定了包含面板的大小。那是问题吗? (添加代码)
-
请看一下这个related example。希望它有所帮助:-)
-
@nIcEcOw 我希望你已经发布了这个作为答案。 :) getPreferredSize 的覆盖正是我所缺乏的。非常感谢!
标签: java image swing jframe paint