java - 如何使按钮居中并使标题居中?
问题描述
我试图将这两个Start和Back按钮居中,但无论何时我尝试任何诸如BoxLayout
, .SetLocation
, SwingConstant.CENTER
,.setVerticalAlignment
之类的东西.setHorizonatalAlignment
都不起作用。谁能帮我设置中间中间的两个按钮和框架顶部中心的“蛇”标题?谢谢。
package snake;
public class Start {
public static void main(String[] args) {
startScreen startFrame = new startScreen();
}
}
class startScreen extends JFrame {
// constructor
public startScreen() {
// fonts
Font snakeTitleFont = new Font("Arial", Font.BOLD, 50);
Font buttonFont = new Font("Arial", Font.CENTER_BASELINE, 20);
// text
JLabel snakeTitle = new JLabel("Snake", SwingConstants.CENTER);
snakeTitle.setFont(snakeTitleFont);
add(snakeTitle);
// start button
JButton startButton = new JButton("Start");
startButton.setBackground(Color.MAGENTA);
startButton.setOpaque(true);
startButton.setBorderPainted(false);
startButton.setFont(buttonFont);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.LINE_AXIS));
add(startButton);
// action listener for start btn
startButton.addActionListener(new ActionListener() {
// once this is clicked on, it should call the GUI
@Override
public void actionPerformed(ActionEvent e) {
new Frame();
dispose(); // closes the old form after start is clicked
}
});
// back button
JButton backButton = new JButton("Back");
backButton.setLayout(null);
backButton.setBackground(Color.YELLOW);
backButton.setOpaque(true);
backButton.setBorderPainted(false);
backButton.setFont(buttonFont);
backButton.setBounds(getBounds());
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.LINE_AXIS));
add(backButton);
// action listener for start btn
startButton.addActionListener(new ActionListener() {
// once this is clicked on, it should call the GUI
@Override
public void actionPerformed(ActionEvent e) {
new Frame();
dispose(); // closes the old form after start is clicked
}
});
this.setVisible(true);
this.setSize(800, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
}
解决方案
在这里快速浏览一下。最适合您的应用程序的是BoxLayout或FlowLayout。
对于各自的使用领域,它们都是非常非常强大的工具。
除此之外,试着看看 Java 的布局教程。您应该始终在 Frames 上使用“ getContentPane() ”方法并应用布局并将组件添加到“ContentPane”!
推荐阅读
- scala - Spark Cassandra 连接器:实施 SCD 类型 1
- html - 图像未在 IE 11 中显示。但在 chrome 和 firefox 中工作
- php - 按视图组合 2 个 SQL 查询并在列表中输出
- postgresql - 如何在 PGADMIN III 中刷新导入的 CSV 表
- laravel - Laravel:schedule:finish 做什么?
- ios - InfoPlist.strings 中未检测到俄语的位置权限描述
- c# - 跨线程问题 - 在 List 中的类的两个实例中填充 FlowLayoutPanel
- java - 如何通过意图将新数据添加到数组列表
- reactjs - currentValue.indexOf 不是 Formik 中 getValueForCheckbox 的函数
- kubernetes - 在 Istio 中将跟踪后端配置为 Zipkin