我正在尝试使JLabel在JFrame调整大小时自动调整大小。我已经尝试过做其他线程上的答案所说的,但所有这些答案看起来都是一样的。每当我最大化窗口时,JLabel保持相同的大小并保持在中心。我正在使用GridBagLayout。我也尝试使用Thread来不断更新JLabel的大小,但它没有用。 JLabel拥有一个ImageIcon,我认为图像的大小可能导致JLabel无法调整大小。 有什么想法吗?
编辑:这是我目前的代码:
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时。
答案 0 :(得分: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);
}
}
答案 1 :(得分: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