我有一个由 jPanel 组成的网格布局。每个 JPanel 都包含一个 JLabel,它们是 9x9。因为这是一个国际象棋游戏,我需要能够在某些事件(例如可能的移动选项或濒危区域)上突出显示每个 jPanel 或其 jLabel。但是,我只能突出显示设置了图标(图形)的字段,这意味着空的 jLabel 的尺寸可能为零。
这就是我在 jLabel 中放置数字的方式( it sucks ,但它有点工作):
public void drawFigureAt(Figure fg, int x, int y) {
//retrieve the Jlabel from the field array
JLabel pole = policka_l[y*8+x];
//Set icon from file
pole.setIcon(new ImageIcon(fg.imageName()+(fg.color==1?"_white":"_black")+".png"));
//force redraw or whatever it is
pole.revalidate();
}
一些字段现在以非常透明的黑色突出显示,因此我可以看到 JLabels 与它们的图标一样大。
这就是我强调的方式:
public void highlightField(int x, int y, Color color) {
//Get the JLabel obejct
JLabel pole = policka_l[y*8+x];
//Set the color as the background
pole.setBackground(color);
//What is this?
pole.setOpaque(true);
//Another magic
pole.revalidate();
repaint();
}
但是,正如我所说,如果 JLabel 没有图标,它就无法突出显示,这对我来说非常难过。更糟糕的是,这是一个今天早上必须工作的学校项目,因此使用不同的渲染系统是没有问题的。
我找到了一些如何处理它的线索,但是它们不起作用。我对此抱有很大希望:
JLabelinstance.setMinimumSize(new Dimension(70, 70));
不幸的是没有效果。
所以我现在想要的是要么让上面的函数工作,或者甚至更好 - 配置 JLabels 以填充其父 JPanel,以便突出显示看起来不错,而不是愚蠢。
另外,我的图形根本不随窗口调整大小,因此它们往往会溢出。
最佳答案
I have a gridlayout that consist from jPanels.
你可以:
1) 只需将标签直接添加到 GridLayout 中即可。那么标签将是网格的大小
2)将面板的布局管理器设置为BorderLayout,然后标签将调整大小以填充面板的整个空间。
pole.setBackground(color);
pole.setOpaque(true);
//pole.revalidate();
//repaint();
不需要 revalidate() 和 repaint() 方法。当属性更改时,Swing 组件将自动重新绘制自己。
Also my figures do not resize with the window at all, so they tend to overflow.
不要使用setSize()。您应该将图标添加到标签,然后将标签添加到网格。然后 pack() 框架和网格的大小将调整为容纳最大的图标。
关于java - 使 JLabel 适合其父 JPanel 或为其指定最小尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895628/