我在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));
}
答案 0 :(得分:1)
主要问题:
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);
}
}
答案 1 :(得分:0)
根据您提供的代码,我认为canvas = new Canvas()
组件覆盖了整个JFrame,因为您已将其设置与jframe相同,这使得其他组件看起来不显示。