[英]JPanel(null) not displaying JLabels
我正在将JLabel从Arraylist添加到JPanel,它们仅在我在面板上设置布局时才会显示,但是当我尝试panel = new JPanel(null);
时,我想panel = new JPanel(null);
设置标签的位置panel = new JPanel(null);
没有显示所有标签。
帧:
public static void Frame(){
panel = new JPanel(null);
JFrame frame = new JFrame("New");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
frame.setSize(400,400);
frame.add(panel);
}
ArrayList迭代将标签添加到面板
private static void printArray() {
for(int i = 0; i < food.size(); i++){
component = new JLabel(new Food(food.get(i).getColor(),
food.get(i).getIconHeight(), food.get(i).getIconWidth(),
food.get(i).getLocationX(), food.get(i).getLocationY()));
panel.add(component);
component.setLocation(food.get(i).getLocationX(),
food.get(i).getLocationY());
}
}
我可以从Debug中看到,它肯定是在获取位置信息,所以为什么不将其放在此位置。
将布局设置为null的原因是,我可以更新标签的位置,以便可以通过键盘输入“移动”标签
您需要做的第一件事是了解布局管理器实际执行的工作,因为如果要删除它,则需要接管它的工作。
布局经理负责确定组件的大小和位置。 他们通过多种方法来执行此操作,但是可以利用组件的getPreferred/Minimum/MaximumSize
方法。
因此,这建议您需要对这些值做出自己的决定,例如...
component = new JLabel(new Food(food.get(i).getColor(),
food.get(i).getIconHeight(), food.get(i).getIconWidth(),
food.get(i).getLocationX(), food.get(i).getLocationY()));
component.setSize(component.getPreferredSize());
component.setLocation(food.get(i).getLocationX(), food.get(i).getLocationY());
我还建议在KeyListener
使用Key Bindings ,它不会遇到与焦点相关的相同问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.