我很难包含GridLayout,因此在它上面添加一个JLabel不会甩掉任何东西。我尝试了一些不同的东西,但似乎仍然无法使它正确对齐。
这是一个Tic Tac Toe游戏:
package assg01;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToe extends JFrame {
private static final String TITLE = "Tic Tac Toe";
private static final int WIDTH = 700;
private static final int HEIGHT = 808;
private Container content;
private JLabel result;
private JButton[] cells;
private JButton exitButton;
private JButton initButton;
private CellButtonHandler[] cellHandlers;
private ExitButtonHandler exitHandler;
private InitButtonHandler initHandler;
private boolean noughts;
private boolean gameOver;
private Container panel;
private ImageIcon x,empty,o;
public TicTacToe() {
// Necessary initialization code
setTitle(TITLE);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Get content pane
panel = getContentPane();
//content.setBackground(Color.blue.darker())
// Set layout
panel.setLayout(new GridLayout(3, 3, 5, 5));
// Create cells and handlers
cells = new JButton[9];
cellHandlers = new CellButtonHandler[9];
for (int i = 0; i < 9; i++) {
cells[i] = new JButton();
cellHandlers[i] = new CellButtonHandler();
cells[i].addActionListener(cellHandlers[i]);
}
// Create result label
//result.setForeground(Color.white);
// Add elements to the grid content pane
for (int i = 0; i < 9; i++) {
panel.add((cells[i]));
}
init();
}
public void init() {
// Initialize
JPanel topPanel = new JPanel();
add(topPanel,BorderLayout.NORTH);
JLabel myLabel = new JLabel ("Label") ;
topPanel.add(myLabel);
x=new ImageIcon("images/x.png");
empty=new ImageIcon("images/empty.png");
o=new ImageIcon("images/o.png");
noughts = true;
gameOver = false;
// Initialize text in buttons
for (int i = 0; i < 9; i++) {
char ch = (char) (i + 1);
cells[i].setIcon(empty);
cells[i].setName(""+ch);
}
// Initialize result label
setVisible(true);
}
答案 0 :(得分:4)
我很难包含
GridLayout
,因此在其上方添加JLabel
不会丢弃任何内容。
这里的技巧是结合布局:
JPanel
BorderLayout
GridLayout
添加到CENTER
。{/ li>的BorderLayout
JLabel
添加到PAGE_START
。{/ li>的BorderLayout
另一个选择是为TitledBorder
使用JLabel
(而不是GridLayout
)。