我一直在尝试制作一个大小相对于窗口大小的 JLabel,但由于某种原因,该 JLabel 没有出现在屏幕上。
这是我的 MainGUI 类中使用的代码,它包含基本界面:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainGUI extends JFrame{
JPanel core;
GridBagConstraints c;
JLabel[] sts;
public MainGUI(){
core = new JPanel(new GridBagLayout());
getContentPane().add(core, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
sts = new JLabel[10];
int width = (int)(66/100) * getWidth(), height = (int)(75/100) * getHeight(); //problem: due to these sizes the JLabel is not appearing
for(int i = 0; i < sts.length; i++){
sts[i] = new JLabel("test");
sts[i].setOpaque(true);
sts[i].setBackground(Color.BLACK);
sts[i].setForeground(Color.BLACK);
sts[i].setPreferredSize(new Dimension(width,height)); //size being set
}
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
core.add(sts[1], c);
}
}
任何帮助寻找解决方案的人都将不胜感激,提前致谢。
最佳答案
几个问题-
- 标签的前景色和背景色相同
- 您需要在标签上设置一些文本
- 检查首选尺寸是否正确计算,因为如果该行被注释掉,则会显示标签。计算出的高度和宽度为零。
这将始终返回零,因为除法结果是 int-
int width = (int)(66/100) * getWidth();
成功-
int width = (int)(((float)66/100) * getWidth());
关于java - 相对尺寸不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15759165/