【发布时间】:2018-05-22 04:50:25
【问题描述】:
我正在尝试将我的 JButton 和 JTextArea 并排对齐到我的代码的底部中间。我遵循了一些教程并来到了这一点。当我执行我的程序时,文本区域和按钮仍然在顶部对齐。救命!
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JButton button = new JButton("Confirm!");
JTextArea text = new JTextArea(1, 20);
public Main() {
super("Battleship!");
setLayout(new FlowLayout());
button.addActionListener(this);
setSize(600, 500);
setResizable(true);
button.setLayout(new FlowLayout(FlowLayout.CENTER));
text.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(text, BorderLayout.SOUTH);
panel.add(button, BorderLayout.SOUTH);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
button.setText(text.getText());
}
}
【问题讨论】:
-
BorderLayout只能在 5 个可用位置中的任何位置管理单个组件。更好的解决方案可能是使用更灵活的布局管理器,例如GridBagLayout -
另一个不错的选择是 JavaFX 库。不能解决您的问题,但我喜欢 JavaFX 库。
-
@JacobB。 “但我喜欢 JavaFX 库” 这不是推荐明显偏离主题的 API 的借口。
-
@AndrewThompson “明显偏离主题”是固执己见的。我认为提供另一个可能的 GUI API 并不是关于 GUI 的问题,特别是如果它只在 cmets 部分中。
标签: java swing alignment layout-manager