我正在尝试创建一个 JFrame,其中我希望按钮(选择设备)位于顶部,文本消息( Activity )以标签形式位于底部。我无法做到这一点,而且他们都在同一条线上,彼此相邻。
JFrame f= new JFrame("AutoV");
f.setVisible(true);
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setBackground(Color.gray);
JButton b=new JButton("Select the Device");
JLabel lab=new JLabel("Active");
lab.setVerticalAlignment(SwingConstants.BOTTOM);
//p.add(b);
p.add(lab);
p.setBorder(BorderFactory.createLineBorder(Color.black));
f.add(p);
Dimension dim1 = Toolkit.getDefaultToolkit().getScreenSize();
f.setLocation(dim1.width/2-f.getSize().width/2, dim1.height/2-f.getSize().height/2);
最佳答案
您应该查找不同的布局。许多组件的默认布局是 FlowLayout,它只是水平对齐所有元素,并且尽可能小。将面板布局设置为框或网格布局应该可以解决问题。
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
关于java - 在 JFrame 上对齐 JButton 和 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33242427/