2014-12-19 47 views
0

我想让JLabel在JFrame调整大小时自动调整大小。我曾尝试做过其他主题上的答案,但所有这些答案仍然显示相同。每当我最大化窗口,JLabel保持相同的大小,并保持在中心。我正在使用GridBagLayout。我也尝试使用线程来不断更新JLabel的大小,但它没有奏效。 JLabel拥有一个ImageIcon,我认为图像的大小可能会导致JLabel无法调整大小。 任何想法?调整JLabel以适合JFrame

编辑:这里是我当前的代码:

setLayout(new GridBagLayout()); 

GridBagConstraints gc=new GridBagConstraints(); 
gc.fill=GridBagConstraints.HORIZONTAL; 
gc.gridx=0; 
gc.gridy=0; 

background=new JLabel(new ImageIcon(getClass().getResource("ingame.gif"))); 
add(background, gc); 
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
background.addMouseMotionListener(this); 

而且JFrame的是这样的:

http://i.stack.imgur.com/i8iJm.png

当后台的JLabel是为了填补整个JFrame中。

+2

*任何想法*是,请分享你尝试过什么,甚至更好的包括[MCVE(HTTP:// WWW。 stackoverflow.com/help/mcve)展示您的问题。 – dic19

+1

根据@ dic19建议的示例获取图像的一种方法是热点链接到[本问答](http://stackoverflow.com/q/19209650/418556)中显示的图像。 –

+0

1.GridBagLayout在这种情况下不起作用。使用BorderLayout。 2.如果您希望调整图像的大小..那么您必须使用面板而不是标签。 –

回答

0

你应该重写你的标签的paintComponent方法,试试这个代码:

import java.awt.Graphics; 
import java.awt.Image; 
import java.io.IOException; 

import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class Test extends JFrame 
{ 
    Image image; 
    JLabel label; 

    public static void main(String[] args) 
    { 
     try 
     { 
      new Test(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public Test() throws IOException 
    { 
     setBounds(100, 100, 500, 400); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     image = ImageIO.read(getClass().getResource("/images/image.gif")); 
     label = new JLabel() 
     { 
      public void paintComponent(Graphics g) 
      { 
       super.paintComponent(g); 
       g.drawImage(image, 0, 0, getWidth(), getHeight(), 0, 0, image.getWidth(null), image.getHeight(null), null); 
      } 
     }; 

     add(label); 
     setVisible(true); 
    } 
} 
0

你为什么不尝试MigLayout。它具有填充整个面板的相当简单的实现。使用MigLayout您的代码会是这个样子,也解决您的问题:?

setLayout(new MigLayout("fill")); 
background=new JLabel(new ImageIcon(getClass().getResource("ingame.gif"))); 
add(background, "cell 0 0"); 
//Rest of your code