2012-01-07 55 views
0

我想知道如何将图像设置为Java应用程序的背景。我知道在android中它非常直接,而windows builder pro有很多令人惊叹的工具来构建Java gui,所以想知道我是否有办法做到这一点?提前致谢!我的应用程序看起来灰很糟糕......如何在eclipse或windows builder pro中将Java应用程序中的图像设置为背景

+0

你目前使用的是什么GUI库?摇摆?或者,这仍然是你问的Android?你应该为图书馆添加一个标签。 – 2012-01-07 22:36:20

+0

对不起,我正在使用swing组件(JPanel,JFrame等) – user1058210 2012-01-07 22:42:23

+1

然后写了很多关于如何为Swing应用程序制作背景图片的文章。我很惊讶谷歌在这方面没有帮助你。 – 2012-01-07 22:45:44

回答

1

你可以通过调用设置您的组件的颜色:

.setBackground(myColor); 

一些组件如Jlabel之下要求你在它的颜色更改生效称之为:

.setOpaque(true); 

希望这对我有所帮助。

+2

他的问题的标题包含单词“图像”,所以我不认为你的答案解决了他的问题。 – 2012-01-07 22:51:12

2

您不能准确地将背景设置为图像。你需要做的是在绘画过程中在图形上绘制图像。所以你需要继承JPanel并覆盖paintComponent()方法,并在那里绘制图像。

public class ImagePanel extends JPanel { 
    private Image bgImage; 

    public Image getBackgroundImage() { 
     return this.bgImage; 
    } 

    public void setBackgroundImage(Image image) { 
     this.bgImage = image; 
    } 

    protected paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawImage(bgImage, 0, 0, bgImage.getWidth(null), bgImage.getHeight(null), null); 
    } 
} 
+0

是的,这是谷歌会告诉他,如果原来的海报烦恼投入努力。 1+。要么是这样做,要么在使用JLabel作为contentPane后使其不透明,给它一个体面的布局管理器,并为其提供一个带有所需图像的ImageIcon。 – 2012-01-07 23:09:07

+0

感谢chubbard的回应! paintComponent方法的第二行中的图像应该是bgImage?如果我将它更改为bgImage,我会得到一个提示,指出getWidth()和getHeight()需要一个ImageObserver作为它们的参数 - 我该如何放置它?另外,我该如何设置bgImage?谢谢 – user1058210 2012-01-07 23:10:07

+0

只需传递null即可,因为您预计图像在绘制之前已经被加载。 – chubbsondubs 2012-01-07 23:22:50

0

从技术上讲,你可以在整个屏幕上,然后在图标选项CHANE特定背景添加标签:

JLabel lblNewLabel = new JLabel("n"); 
lblNewLabel.setIcon(new ImageIcon("gene.jpg")); 
lblNewLabel.setBounds(0, 0, 434, 261); 
frame.getContentPane().add(lblNewLabel); 

例如,在源

private void initialize() { 
    frame = new JFrame(); 
    frame.setBounds(100, 100, 450, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 

    JButton btnNewButton = new JButton("Let's start!"); 
    btnNewButton.setFont(new Font("David", Font.ITALIC, 12)); 
    btnNewButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      JOptionPane.showMessageDialog(null, "Now we will have to add some code here right =]?"); 
     } 
    } 
                 ); 
    btnNewButton.setBounds(158, 120, 89, 23); 
    frame.getContentPane().add(btnNewButton); 


    JLabel lblNewLabel = new JLabel("n"); 
    lblNewLabel.setIcon(new ImageIcon("gene.jpg")); 
    lblNewLabel.setBounds(0, 0, 434, 261); 
    frame.getContentPane().add(lblNewLabel); 
} 

http://imgur.com/rSTXZLP.jpg

相关问题