使用 JLabel 设置背景图像的问题
Problem with setting background image using JLabel
我正在尝试制作小游戏,这个游戏有选择地图的选项。不同的选择,选择不同的地图。每个选择都有自己的地图(背景图片)。对于背景图像,我使用 JLabel 和方法:setIcon()。
我的问题是,当我设置图像时,我的所有组件都被隐藏了。 This is picture: http://prntscr.com/qi5m8a (你可以看到只能看到图像)。
对于地图选择,我使用这种结构,这里是图片:http://prntscr.com/qi5n4c 有一个播放按钮和这样的事件:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(mapOneRadioButton.isSelected())
{
this.dispose();
GameWindow game = new GameWindow();
game.setVisible(true);
game.setLocationRelativeTo(null);
backgroundLabelGameWin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/earthProject.gif")));
}else if(mapTwoRadioButton.isSelected())
{
}else if(mapTreeRadioButton.isSelected())
{
}else if(mapFourRadioButton.isSelected())
{
}else if(mapFiveRadioButton.isSelected())
{
}
}
我使用 JPanel 为背景图像添加 JLabel,为其余组件使用 JLayeredPanel。
我的 problem/question 是,我怎样才能 change/set 图像而不破坏框架中的顺序??我的意思是,我想 change/set 在背景中显示图像,以便可以看到我的所有组件。
请帮助我,我不知道如何解决这个问题。
如果您更改 JPanel 的背景而不是使用 JLabel 作为图像会更好。您不能直接更改 JPanel 的背景。但是你可以参考下面的link来做
http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm
For background image I useing JLabel and method: setIcon(). My problem is that when I set image, all my components get hide.
两个选项:
将组件添加到 JLabel。然后组件将绘制在图像之上。这种方法的限制是组件必须适合图像内部,因为图像总是以其实际大小绘制。
通过覆盖面板的 paintComponent(...)
方法在 JPanel 上自定义绘制图像,然后调用 Grapics.drawImage(...)
方法。然后将您的组件添加到面板。有关提供此支持的 class,请参阅 Background Panel。这提供了更大的灵活性,因为您可以缩放图像以填充面板。
我正在尝试制作小游戏,这个游戏有选择地图的选项。不同的选择,选择不同的地图。每个选择都有自己的地图(背景图片)。对于背景图像,我使用 JLabel 和方法:setIcon()。 我的问题是,当我设置图像时,我的所有组件都被隐藏了。 This is picture: http://prntscr.com/qi5m8a (你可以看到只能看到图像)。 对于地图选择,我使用这种结构,这里是图片:http://prntscr.com/qi5n4c 有一个播放按钮和这样的事件:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(mapOneRadioButton.isSelected())
{
this.dispose();
GameWindow game = new GameWindow();
game.setVisible(true);
game.setLocationRelativeTo(null);
backgroundLabelGameWin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/earthProject.gif")));
}else if(mapTwoRadioButton.isSelected())
{
}else if(mapTreeRadioButton.isSelected())
{
}else if(mapFourRadioButton.isSelected())
{
}else if(mapFiveRadioButton.isSelected())
{
}
}
我使用 JPanel 为背景图像添加 JLabel,为其余组件使用 JLayeredPanel。
我的 problem/question 是,我怎样才能 change/set 图像而不破坏框架中的顺序??我的意思是,我想 change/set 在背景中显示图像,以便可以看到我的所有组件。 请帮助我,我不知道如何解决这个问题。
如果您更改 JPanel 的背景而不是使用 JLabel 作为图像会更好。您不能直接更改 JPanel 的背景。但是你可以参考下面的link来做 http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm
For background image I useing JLabel and method: setIcon(). My problem is that when I set image, all my components get hide.
两个选项:
将组件添加到 JLabel。然后组件将绘制在图像之上。这种方法的限制是组件必须适合图像内部,因为图像总是以其实际大小绘制。
通过覆盖面板的
paintComponent(...)
方法在 JPanel 上自定义绘制图像,然后调用Grapics.drawImage(...)
方法。然后将您的组件添加到面板。有关提供此支持的 class,请参阅 Background Panel。这提供了更大的灵活性,因为您可以缩放图像以填充面板。