我知道同样的问题已被多次询问,但我真的似乎没有在我的代码中发现阻碍JPanel类型的对象在JFrame中显示的错误。这是扩展JFrame的类的构造函数:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Game extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private Board board;
public Game() {
super("Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.WHITE);
board = new Board();
add(board, BorderLayout.CENTER);
JButton button = new JButton("Start new game");
button.setFocusPainted(false);
button.addActionListener(this);
JPanel control = new JPanel();
control.setBackground(Color.WHITE);
control.add(button);
add(control, BorderLayout.SOUTH);
pack();
setResizable(false);
setVisible(true);
}
这个是扩展JPanel的类的构造函数:
public class Board extends JPanel implements ActionListener {
public Board() {
setBackground(Color.WHITE);
setLayout(new GridLayout(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS));
setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20));
board = new Cell[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
for (int row = 0; row < NUMBER_OF_ROWS; row++) {
for (int column = 0; column < NUMBER_OF_COLUMNS; column++) {
board[row][column] = new Cell(this, row, column);
add(board[row][column]);
}
}
}
当我运行main方法(我没有在这里显示)时,它只显示框架和按钮。如果有人能给出一个暗示,我会非常感激。
答案 0 :(得分:0)
似乎在这个可运行的代码的紧密变体(a MCTaRE)中显示得很好。
请注意,我在GridLayout
中添加了一些空格并更改了颜色以使面板边界更清晰。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Game extends JFrame {
private static final long serialVersionUID = 1L;
private Board board;
public Game() {
super("Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.WHITE);
board = new Board();
add(board, BorderLayout.CENTER);
JButton button = new JButton("Start new game");
button.setFocusPainted(false);
JPanel control = new JPanel();
control.setBackground(Color.GREEN);
control.add(button);
add(control, BorderLayout.SOUTH);
pack();
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new Game();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
/** A pseudo Cell */
class Cell extends JButton {
Cell(JComponent parent, int row, int column) {
super(row + " " + column);
}
}
/** And this one is the constructor of the class that extends JPanel */
class Board extends JPanel {
int NUMBER_OF_ROWS=3;
int NUMBER_OF_COLUMNS=4;
Cell[][] board;
public Board() {
setBackground(Color.RED);
setLayout(new GridLayout(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS, 5, 5));
setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20));
board = new Cell[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
for (int row = 0; row < NUMBER_OF_ROWS; row++) {
for (int column = 0; column < NUMBER_OF_COLUMNS; column++) {
board[row][column] = new Cell(this, row, column);
add(board[row][column]);
}
}
}
}