2012-04-13 121 views

回答

4

的休息动画图像作为GUI的BG。我使用HTML来调整这个(x3)的大小,但如果它已经是所需的大小,可以直接将它设置为标签的Icon

import java.awt.*; 
import javax.swing.*; 
import javax.swing.border.EmptyBorder; 

class LabelAsBackground { 

    public static final String HTML = 
     "<html>" + 
     "<style type'text/css'>" + 
     "body, html { padding: 0px; margin: 0px; }" + 
     "</style>" + 
     "<body>" + 
     "<img src='http://pscode.org/media/starzoom-thumb.gif'" + 
     " width=320 height=240>" + 
     ""; 

    LabelAsBackground() { 
     JFrame f = new JFrame("Animated Image BG"); 
     f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     JLabel contentPane = new JLabel(HTML); 
     contentPane.setLayout(new GridLayout()); 
     JPanel gui = new JPanel(new GridLayout(3,3,15,15)); 
     gui.setOpaque(false); 
     contentPane.add(gui); 
     gui.setBorder(new EmptyBorder(20,20,20,20)); 
     for (int ii=1; ii<10; ii++) { 
      gui.add(new JButton("" + ii)); 
     } 
     f.setContentPane(contentPane); 
     f.pack(); 
     //f.setResizable(false); // uncomment to see strange effect.. 
     f.setVisible(true); 
    } 

    public static void main(String[] args) { 
     //Create the frame on the event dispatching thread 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       LabelAsBackground lab = new LabelAsBackground(); 
      } 
     }); 
    } 
} 

不确定它是不是'真的'。这似乎是一个需要很多澄清的主观术语。我从来没有用过这种方法,只是把它弄明白,今晚就在摸索。 ;)

+0

这是一个很有希望的开始:-) +1为此,但同样的想法,整个事情可以通过反之亦然,通过正常的步骤来实现。 – 2012-04-13 13:02:03

+0

*“反之亦然,通过正常步骤”*如何? (我的意思是在'我可以算'的代码行)。) – 2012-04-13 13:04:52

+0

不,不,我的不好,只是困惑,介于两者之间。我一直相信的,以及我今天看到的新方法。我从来没有想过'JLabel'是什么,除了显示图像和文本。这种新行为对我来说完全是未知的,似乎我需要时间去接触这个新事物:-)我的眼睛是广阔的,今晚我可能不会睡觉,哈哈 – 2012-04-13 13:15:26

4

是的,有真正的理由想要添加组件到JLabel。由于在JLabel上设置和交换ImageIcons非常容易,因此想要将它们用作GUI的支持图像并不罕见。

编辑
幽州:

AHHA的意思是说,如果我想我的容器有一个特定的背景,那么我必须使用的JLabel为平台,在其上这样的事情可以驻留?我对吗 ?

不,您不必绝对必须使用JLabel,因为如果需要,在JPanel中绘制背景图像相当容易。只需在其paintComponent(...)方法中绘制图像即可。

+0

Ahha的意思是说,如果我想让我的容器具有特定的背景,那么我必须使用'JLabel'作为平台,这样的东西可以驻留?我对吗 ? – 2012-04-13 12:31:39

+0

@nIcEcOw:请参阅编辑 – 2012-04-13 12:33:23

+0

哇,这看起来有趣,毫无疑问像往常一样,翔实的答案:-) – 2012-04-13 12:52:14

5
this seems to me a bit weird, why would one wants to add 
a JPanel to a JLabel, 

肯定这就是正确的

are there any genuine reasons as to such situation can arise, 
so is it just trivial? 

没有,是不平凡的,因为只有JFrame/JDialog/JWindowJPanel已经得到pre_implemented LayoutManager,为 “Custom JComponentyou have to declare proper LayoutManager, programatically

+0

哇,这是一个非常好的示例+1这个:-) – 2012-04-13 12:55:50

+2

@nIcE cOw和我加入盐...... JLabel具有similair性质作为JViewport(我的观点),但JLabel阻止鼠标和键盘输入,例如我无法定义(可切换)JViewport消耗鼠标和键盘输入,但是这个疯狂的JLabel在opaque(true)的API中缺少重绘(),然后在一侧HFOE可能是正确的,但Andrew反对使用Html和图标,我默认忽略所有良好的习惯(一切皆有可能) – mKorbel 2012-04-13 13:04:03

+0

LOL太真了,我很困惑 – 2012-04-13 13:07:53

相关问题