I am creating a mini game and I'm stuck. This grid is supposed to be nxn but in this case it's 6x6 until I figure things out.
Anyhow, I'd like to create a transparent border
which will add centered numbers above each cell (on the left side and up, however, later on I must add the rights side and down). What would be a good way to do this? I searched around because I know that chess boards have this kind of "border" and I actually searched them up, but with no luck.
This is a code snippet, the cells are contained in a simple JPanel while everything else is in the 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);
}
}