我正在创建一个小游戏,但卡住了。这个网格应该是nxn的,但在这种情况下它是6x6,直到我解决问题。
这是一个代码片段,单元格包含在简单的JPanel中,而其他所有内容都在JFrame中。
无论如何,我想创建一个透明边框。
这将在每个单元格上方添加居中的数字(在左侧和上方),但是以后我必须添加右侧和下方。有什么好方法可以做到这一点?我搜索了一下,因为我知道国际象棋棋盘有这种“边框”,实际上我搜索了它们,但没有找到合适的结果。这是一个代码片段,单元格包含在简单的JPanel中,而其他所有内容都在JFrame中。
public GameFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new GamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JMenuBar menubar = new JMenuBar();
JMenu menu1 = new JMenu ("New");
menubar.add(menu1);
JMenu menu2 = new JMenu ("Load");
menubar.add(menu2);
JMenu menu3 = new JMenu ("Save");
menubar.add(menu3);
JMenu menu4 = new JMenu ("Size");
menubar.add(menu4);
JMenu menu5 = new JMenu ("Check");
menubar.add(menu5);
JMenu menu6 = new JMenu ("Solve");
menubar.add(menu6);
frame.setJMenuBar(menubar);
}
});
}
public class GamePanel extends JPanel {
public GamePanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int row = 0; row < 6; row++) {
for (int col = 0; col < 6; col++) {
gbc.gridx = col;
gbc.gridy = row;
CellPanel cellPanel = new CellPanel();
Border border = null;
if (row < 5) {
if (col < 5) {
border = new MatteBorder(1, 1, 0, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 0, 1, Color.GRAY);
}
} else {
if (col < 5) {
border = new MatteBorder(1, 1, 1, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 1, 1, Color.GRAY);
}
}
cellPanel.setBorder(border);
add(cellPanel, gbc);
}
}
}
}
public class CellPanel extends JPanel {
Color defaultBackground;
public CellPanel() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
defaultBackground = getBackground();
if (getBackground().equals(Color.BLUE)) {
setBackground(null);
} else {
setBackground(Color.BLUE);
}
}
});
}
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}
JLabel
。 - pzaengerCellPanels
类。如果您能添加此类,则该程序将可供SO用户测试。 - hamena314new GameFrame();
。我会尝试一下,但我不确定当我尝试分配一个nxn网格时它会有多好的效果。 - Intai'sei