[英]Java GUI Layout Issues
我正在尝试使用Java创建一个简单的程序,该程序需要顶部8个JLabels
,并且在其正下方有一个JButton
。 我尝试使用BoxLayout
然后使用FlowLayout
,但是发生的是JLabels
在程序开始时消失了。 单击该button
,所有内容都会正确显示,但是您必须手动调整窗口大小。 有人可以解释我在做什么错吗? 谢谢!
public class ProgramUI {
private JButton _jbutton;
private ArrayList<JLabel> _jlabels;
private JFrame _jframe;
private JPanel _top, _bottom;
public ProgramUI(){
_jframe = new JFrame ();
_jframe.getContentPane().setLayout(new BoxLayout(_jframe.getContentPane(), BoxLayout.Y_AXIS));
_top = new JPanel();
_jframe.add(_top);
_bottom = new JPanel();
_jframe.add(_bottom);
_top.setLayout(new FlowLayout(FlowLayout.LEFT));
_bottom.setLayout(new FlowLayout(FlowLayout.LEFT));
_jlabels = new ArrayList<JLabel>();
for (int i=0; i<8; i++) {
JLabel label = new JLabel();
_jlabels.add(label);
_top.add(label);
//...rest of code is not relevant
}
_jbutton = new JButton();
_bottom.add(_jbutton);
_jframe.pack();
_jframe.setVisible(true);
_jframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
我不推荐FlowLayout
和BoxLayout
。 BoxLayout
非常简单且不可移植。 FlowLayout
甚至不是一个布局管理器,只是一个玩笑。
我建议使用内置的GroupLayout
或第三方MigLayout
。 您需要花一些时间来学习如何创建良好的布局。
这是您使用MigLayout
的示例。
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import net.miginfocom.swing.MigLayout;
public class ProgramUI extends JFrame {
public ProgramUI() {
initUI();
}
private void initUI() {
setLayout(new MigLayout("nogrid"));
add(new JLabel("Label"));
add(new JLabel("Label"));
add(new JLabel("Label"));
add(new JLabel("Label"));
add(new JLabel("Label"));
add(new JLabel("Label"));
add(new JLabel("Label"));
add(new JLabel("Label"), "wrap");
add(new JButton("Button"));
pack();
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
ProgramUI ex = new ProgramUI();
ex.setVisible(true);
});
}
}
屏幕截图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.