我在 JButtons 上遇到了一些严重的问题。我的问题是,无论我如何尝试,JButton 都不会显示。我已经尝试了一个多小时,但没有任何效果,所以我想是时候在这里提问了。这是我的代码。它只是构造函数,因为整个类真的很大,你不需要看到它。
public Game() {
frame = new JFrame(NAME);
canvas = new Canvas();
canvas.setMinimumSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setPreferredSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setSize(width, height);
frame.add(canvas, BorderLayout.CENTER);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
frame.setFocusable(true);
frame.requestFocus();
JPanel panel = new JPanel();
JButton play = new JButton("Hi");
panel.add(play);
frame.getContentPane().add(panel);
panel.setPreferredSize(new Dimension(width, height));
}
最佳答案
主要问题:
frame.pack();
应在添加所有组件后完成。frame.setVisible(true);
最好放在所有添加、打包和配置之后。
import java.awt.*;
import javax.swing.*;
public class Game {
private JFrame frame = null;
private Canvas canvas = null;
private String NAME = "Moronically Named Game";
int width = 500;
int height = 200;
public Game() {
frame = new JFrame(NAME);
canvas = new Canvas();
canvas.setMinimumSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setPreferredSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setSize(width, height);
frame.add(canvas, BorderLayout.CENTER);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setFocusable(true);
frame.requestFocus();
JPanel panel = new JPanel();
JButton play = new JButton("Hi");
panel.add(play);
frame.getContentPane().add(panel);
panel.setPreferredSize(new Dimension(width, height));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
Game o = new Game();
}
};
SwingUtilities.invokeLater(r);
}
}
其他提示:
- 为了更快地获得更好的帮助,请发布 Minimal, Complete, and Verifiable example或Short, Self Contained, Correct Example 。例如。正如我的回答中所见。您在问题中发布了无法编译的代码片段,我将其转换为 MCVE 作为答案。
- 参见Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (是的。)
- 关于使用提示 (2) 中提到的填充来布局 GUI。提供 ASCII 艺术图或简单的图形用户界面的预期布局,尺寸最小,如果可调整大小,则具有更大的宽度和高度。
关于java - 如何让这个 JButton 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38866049/