不确定我的问题是什么。我创建了一个 JFrame ,并且有一个面板,其中有 4 个大按钮(带有图形 - 尽管尚未编码)以显示在框架上,但当它尝试运行时出现错误这和面板没有显示在框架中。
更新:没有错误消息,但框架中没有面板或按钮...
public class EasyExpress {
private static JFrame frame = new JFrame("EASY BUTTONS");
private JButton WriteBTN = new JButton("Write Email");
private JButton EmailBTN = new JButton("View Emails");
private JButton SolBTN = new JButton("Play Solsuite Solitaire");
private JButton ShutBTN = new JButton("Shutdown Computer");
private JPanel btnPanel;
public EasyExpress() {
/* try {
Image img = ImageIO.read(getClass().getResource("write.jpg"));
WriteBTN.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}*/
btnPanel = new JPanel(new GridLayout(1,4,1,1));
btnPanel.setBounds(0, 0, 1200, 400);
WriteBTN.setPreferredSize(new Dimension(300,400));
EmailBTN.setPreferredSize(new Dimension(300,400));
SolBTN.setPreferredSize(new Dimension(300,400));
ShutBTN.setPreferredSize(new Dimension(300,400));
btnPanel.add(EmailBTN);
btnPanel.add(WriteBTN);
btnPanel.add(SolBTN);
btnPanel.add(ShutBTN);
frame.add(btnPanel);
frame.add(frame);
}
public static void main(String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setSize(1200,400);
frame.setVisible(true);
}
最佳答案
本质上,您是将一个框架添加到另一个框架,但您根本无法做到这一点
您也没有初始化按钮,这导致了 NullPointerException
。
首先删除extends JFrame
,这只是令人困惑的事情,并且作为一般规则,您应该避免从顶级容器进行扩展。相反,从 JPanel
开始,例如......
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class EasyExpress extends JPanel {
JButton WriteBTN, EmailBTN, SolBTN, ShutBTN;
JPanel btnPanel;
public EasyExpress() {
btnPanel = new JPanel(new GridLayout(1, 4, 1, 1));
btnPanel.setBounds(0, 0, 1200, 400);
WriteBTN = new JButton("1");
EmailBTN = new JButton("2");
SolBTN = new JButton("3");
ShutBTN = new JButton("4");
WriteBTN.setPreferredSize(new Dimension(300, 400));
EmailBTN.setPreferredSize(new Dimension(300, 400));
SolBTN.setPreferredSize(new Dimension(300, 400));
ShutBTN.setPreferredSize(new Dimension(300, 400));
btnPanel.add(EmailBTN);
btnPanel.add(WriteBTN);
btnPanel.add(SolBTN);
btnPanel.add(ShutBTN);
setLayout(new BorderLayout());
add(btnPanel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new EasyExpress());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
关于java - JFrame 不工作 - 内容不出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34217333/