Dan*_*iel -8 java user-interface swing
这段代码有什么问题?GUI未显示.这是我实验室项目的4x4图片内存的GUI.任何帮助,将不胜感激 .
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class memory extends JFrame implements ActionListener {
String pictures[]
= {"riven1.jpg", "riven2.jpg", "riven3.jpg", "riven4.jpg", "riven5.jpg", "riven6.jpg", "riven7.jpg", "riven8.jpg"};
JButton button[];
public memory() {
Container c = getContentPane();
setTitle("Memory Game");
panel.setLayout(new GridLayout(4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton(new ImageIcon(pictures[x]));
c.add(button[x]);
button[x].addActionListener(this);
}
setSize(700, 700);
setVisible(true);
setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
new memory();
}
}
Run Code Online (Sandbox Code Playgroud)
有很多问题......
第一:你永远不会初始化 button[]
JButton button[];
public memory() {
Container c = getContentPane();
setTitle("Memory Game");
panel.setLayout(new GridLayout(4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton(new ImageIcon(pictures[x]));
Run Code Online (Sandbox Code Playgroud)
这将导致a NullPointerException
,button
默认为null
和尚未初始化
在for循环之前初始化按钮,例如......
button = new JButton[16];
Run Code Online (Sandbox Code Playgroud)
第二:您将所有按钮添加到内容窗格,其默认布局为BorderLayout.这意味着只有您添加的最后一个按钮才会可见,占据整个窗口.
尝试设置内容窗格的布局管理器...
c.setLayout(new GridLayout(4, 4));
Run Code Online (Sandbox Code Playgroud)
第三:panel
未定义,所以你的例子甚至不应该编译
// I have no idea how this is defined...
panel.setLayout(new GridLayout(4, 4));
Run Code Online (Sandbox Code Playgroud)
附注:避免使用尽可能使用的setSize
地方pack
.这考虑了不同平台如何呈现字体之类的差异.您还应确保在使窗口可见之前设置窗口的状态
// Use pack instead
//setSize(700, 700);
pack();
setLocationRelativeTo(null);
setVisible(true);
Run Code Online (Sandbox Code Playgroud)