So yeah, I'm trying to write a rock paper scissors program with images, but I'm having trouble at putting in the pictures. There seems to only be a small white square on the JPanel.
Here's the code for my Main Class:
public class Practice extends JPanel implements ActionListener {
// Images
final ImageIcon rockPic = new ImageIcon("D:\\JOVO\\RPS\\src\\rock.png");
final ImageIcon paperPic = new ImageIcon("D:\\JOVO\\RPS\\src\\paper.png");
// variables
String results = null;
Image pic = null;
//Image Panel
ImagePanel youPic = new ImagePanel();
public Practice() {
// FRAME
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RPS");
frame.setLayout(new BorderLayout());
frame.setVisible(true);
// SUPER JPANEL
setLayout(new GridBagLayout());
setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
frame.add(this);
// JPANELS - RPS title, JButton, PICTURES
JPanel rpsTitle = new JPanel();
c.fill = GridBagConstraints.CENTER;
c.gridy = 0;
c.gridx = 1;
rpsTitle.setBackground(Color.WHITE);
add(rpsTitle, c);
JPanel jbuts = new JPanel();
c.gridy = 3;
jbuts.setLayout(new BorderLayout());
add(jbuts, c);
// ImagePanels
c.gridy = 2;
c.gridx = 0;
add(youPic,c);
c.gridy = 0;
c.gridx = 1;
// JBUTTONS
JButton rock = new JButton(" Rock ");
JButton paper = new JButton(" Paper ");
JButton scissors = new JButton("Scissors");
jbuts.add(rock, BorderLayout.WEST);
jbuts.add(paper, BorderLayout.CENTER);
jbuts.add(scissors, BorderLayout.EAST);
paper.addActionListener(this);
JButton resultB = new JButton("RES");
c.gridy = 2;
c.weighty = 10;
add(resultB, c);
c.weighty = 0;
// FONTS
Font rps = new Font(null, Font.BOLD, 28);
Font labels = new Font(null, Font.ITALIC, 18);
// JLABELS
JLabel rpsTit = new JLabel("Rock, Paper, Scissors");
rpsTit.setFont(rps);
rpsTitle.add(rpsTit);
JLabel you = new JLabel("You: ");
you.setFont(labels);
JLabel com = new JLabel("Com: ");
com.setFont(labels);
c.gridy = 1;
c.gridx = 0;
add(you, c);
c.gridx = 2;
add(com, c);
// PICTURES
// comPic.setPic(rockPic);
// youPic.setPic(pic);
}
public String test(String name) {
// test the game
return results;
}
public static void main(String[] args) {
// main stuffs
Practice prac = new Practice();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Works");
ImageIcon pic = null;
pic = paperPic;
youPic.setPic(pic);
}
}
And my other class:
public class ImagePanel extends JPanel {
Image pic = null;
public ImagePanel() {
repaint();
}
public void setPic(ImageIcon pic) {
// set picture for painting
this.pic = pic.getImage();
System.out.println("Set Pic");
repaint();
}
public void paintComponent(Graphics g) {
// paint
super.paintComponent(g);
System.out.println("Painting");
g.drawImage(pic, 0, 0, this);
}
}
Thanks in advance! :)
Related
For a simple GUI I am currently making I want a design similar to this.
The blue and the green area are supposed to be just text and numbers.
The red area is supposed to be an image. Currently, I am creating scaled instances of an Image, create an ImageIcon out of this and then add this to a label to fit an image into different spaces.
The problem is, that without a width I can not create a scaled instance of the picture.
My current GridBagLayout code looks like this:
private static void createAndShowUI()
{
JFrame frame = new JFrame();
JLabel map = new javax.swing.JLabel();
JLabel data = new javax.swing.JLabel();
JLabel menu = new javax.swing.JLabel();
GridBagConstraints c;
frame = new JFrame("Risiko");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(new GridBagLayout());
map.setText("MAP");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.75;
c.weighty = 0.75;
frame.getContentPane().add(map, c);
data.setText("DATA");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weighty = 0.25;
frame.getContentPane().add(data, c);
menu.setText("MENU");
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.gridheight = 2;
c.weightx = 0.25;
frame.getContentPane().add(menu, c);
frame.setVisible(true);
}
I create the three areas and now I want to create an image with the exact width and height of the red area.
So my question is, how can I get the width and height of the red area so I can create a scaled instance of the picture so that it fits into this area?
Test the dynamic layout of the following mre by resizing the frame.
The background image used as background for MapPane is resized to fill the JPanels width and height.
This is achieved by overriding paintComponent:
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingTestPane extends JPanel {
public SwingTestPane() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowWeights = new double[]{0.75, .25};
gridBagLayout.columnWeights = new double[]{0.75, 0.25};
setLayout(gridBagLayout);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
JPanel mapPane = new MapPane();
add(mapPane, c);
c.gridx = 0;
c.gridy = 1;
JLabel data = new javax.swing.JLabel("DATA");
JPanel dataPane = new JPanel();
dataPane.add(data);
dataPane.setBackground(Color.YELLOW);
dataPane.setOpaque(true);
add(dataPane, c);
c.gridx = 1;
c.gridy = 0;
c.gridheight = 2;
JLabel menu = new JLabel("MENU");
JPanel menuPane = new JPanel();
menuPane.add(menu);
menuPane.setBackground(Color.GREEN);
menuPane.setOpaque(true);
add(menuPane, c);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400,400);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.getContentPane().add(new SwingTestPane());
frame.pack();
frame.setVisible(true);
}
}
class MapPane extends JPanel {
String imageUrlString = "https://findicons.com/files/icons/345/summer/128/cake.png";
BufferedImage image = null;
MapPane() {
URL url;
try {
url = new URL(imageUrlString);
image = ImageIO.read(url);
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override //Override to paint image as the background
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
I have two panels. The first one looks like this.
public class BoardPanel extends JPanel
{
public BoardPanel()
{
setLayout(null);
this.setOpaque(false);
Button button = new JButton("..");
button.setLocation(...);
button.setSize(...);
add(button);
}
public void paintComponent( Graphics g )
{
/*
* Painting some stuff here.
*/
}
}
The other panel is something like this:
public class OtherPanel extends JPanel
{
public OtherPanel()
{
super();
this.setLayout(null);
this.setOpaque(false);
JPanel panel1 = new JPanel();
panel1.setLocation(...);
panel1.setSize(...);
panel1.setOpaque( .. );
JPanel panel2 = new JPanel();
panel2.setLocation(...);
panel2.setSize(...);
panel2.setOpaque( .. );
add(panel1):
add(panel2);
}
}
After that , I put both my panels in a frame. But I want my BoardPanel to occupy more screen than OtherPanel. So I used GridBagLayout for the frame
public class MainFrame extends JFrame
{
private GridBagLayout aGridLayout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public MainFrame()
{
super("Quoridor");
setLayout(gridLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366, 768);
setVisible(true);
setResizable(false);
this.getContentPane().setBackground(Color.decode("#b2a6a6"));
BoardPanel boardPanel = new BoardPanel();
OtherPanel otherPanel = new OtherPanel();
this.addComponent(boardPanel, 1, 1, 2, 1);
this.addComponent(otherPanel, 1, 3, 1, 1);
}
public void addComponent(Component component , int row , int column , int width
, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
aGridLayout.setConstraints(component, constraints);
add(component);
}
}
The problem is , that the frame gives equal space to both panels , and dont give more space to the boardPanel.
Why is this happening ? Doest it have to do with the bounds of the panels ?
Here is a good tutorial on GridBagLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html . Also see the code below and screenshot. The anchor field positions the component at the first line. The weightx field gives more space to the columns for boardPanel. The ipady field specifies how much to add to the height of the component. Here, boardPanel gets most of the width and all of the height. The otherPanel panel gets half of the height.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridExample {
private JFrame mainFrame;
private JPanel boardPanel, otherPanel;
public GridExample(){
mainFrame = new JFrame();
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
boardPanel = new JPanel();
boardPanel.add(new JLabel("board panel"));
boardPanel.setBackground(Color.yellow);
otherPanel = new JPanel();
otherPanel.add(new JLabel("other panel"));
otherPanel.setBackground(Color.green);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.75;
c.ipady = 400;
c.gridx = 0;
c.gridy = 0;
mainFrame.add(boardPanel, c);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.25;
c.ipady = 200;
c.gridx = 1;
c.gridy = 0;
mainFrame.add(otherPanel, c);
mainFrame.setVisible(true);
}
public static void main(String[] args){
GridExample swingContainerDemo = new GridExample();
}
}
Is there a way that I can set the JFrame to be transparent while still leaving the Buttons / text unaffected?
If not, how can I make the JFrame transparent without using .setUndecorated(true)?
This is a totally different question, but how would I go about adding a gradient as the background color instead of having it be set to one solid color?
Click here to see what the JFrame looks like when the program runs!
class PlayAgain extends JPanel
{
private JFrame nextFrame;
public PlayAgain()
{
nextFrame = new JFrame("Tic-Tac-Toe");
nextFrame.setSize(250,125);
nextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
nextFrame.add(panel);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
nextFrame.dispose();
frame.dispose();
XorOFrameGRID obj = new XorOFrameGRID();
}
}
class ClickNo implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
frame.dispose();
nextFrame.dispose();
}
}
//CREATING BUTTONS & LABELS
JLabel WLT;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
JLabel title = new JLabel("Would you like to play again?");
if (isWin() == 1)
{
WLT = new JLabel("YOU WON!");
panel.add(WLT,c);
}
else if (isWin() == 2)
{
WLT = new JLabel("YOU LOST!");
panel.add(WLT,c);
}
else if (isWin() == 3)
{
WLT = new JLabel("YOU TIED!");
panel.add(WLT,c);
}
JLabel or = new JLabel("or");
JButton yes = new JButton("Yes");
ActionListener listener1 = new ButtonListener();
yes.addActionListener(listener1);
JButton no = new JButton("No");
ActionListener listener2 = new ClickNo();
no.addActionListener(listener2);
c.gridwidth = 0;
//1ST COLUMN
c.anchor = GridBagConstraints.LINE_END;
c.weighty = 10;
c.gridx = 0;
c.gridy = 2;
panel.add(no,c);
//2ND COLUMN
//adds "or"
c.anchor = GridBagConstraints.CENTER;
c.gridx = 1;
c.gridy = 2;
panel.add(or,c);
//adds title
c.weighty = 0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
panel.add(title,c);
//3RD COLUMN
c.gridwidth = 0;
c.weighty = 3; // changes weight
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 2;
c.gridy = 2;
panel.add(yes,c);
nextFrame.pack();
nextFrame.setLocationRelativeTo(null);
nextFrame.setResizable(false);
nextFrame.setVisible(true);
nextFrame.toFront();
}
Here is the Source code for transparent JFrame:
public class Example extends JFrame {
public Example() {
super("TranslucentWindowDemo");
setLayout(new GridBagLayout());
setSize(500,300);
setLocationRelativeTo(null);
setUndecorated(true);
getContentPane().setBackground(Color.blue);
JButton Close = new JButton("Close");
add(Close);
ActionListener al;
al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
};
Close.addActionListener (al);
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}
public static void main(String args[]) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println("Translucency is not supported");
System.exit(0);
}
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Example e = new Example();
e.setOpacity(0.55f);
e.setVisible(true);
}
});
}
}
For the Opacity, you can try Pane.setOpaque(false);
And for the contents you should change to setBackground(new Color(0, 0, 0, 0));
You can read more here
Im trying to create a chess program in Java. Right now, I have the board done together with the pieces present, which I can move with my mouse by dragging and dropping.
What I need is to add coordinates to the squares at the sides, like on a real board. Doesn't have to be anything fancy, just a visual. Since I drew my board not with Graphics, I don't know how to draw on top of the board I have created :/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessGame extends JFrame implements MouseListener,
MouseMotionListener {
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xCoordinate;
int yCoordinate;
public ChessGame() {
Dimension boardSize = new Dimension(600, 600);
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
// adding chess board
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout(new GridLayout(8, 8));
chessBoard.setPreferredSize(boardSize);
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel(new BorderLayout());
chessBoard.add(square);
int row = (i / 8) % 2;
if (row == 0)
square.setBackground(i % 2 == 0 ? new Color(238, 221, 187)
: new Color(204, 136, 68));
else
square.setBackground(i % 2 == 0 ? new Color(204, 136, 68)
: new Color(238, 221, 187));
}
// Black pieces on the board
JLabel piece = new JLabel(new ImageIcon(getClass().getResource(
"Rooka8.png")));
JPanel panel = (JPanel) chessBoard.getComponent(0);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightb8.png")));
panel = (JPanel) chessBoard.getComponent(1);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopc8.png")));
panel = (JPanel) chessBoard.getComponent(2);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Queend8.png")));
panel = (JPanel) chessBoard.getComponent(3);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Kinge8.png")));
panel = (JPanel) chessBoard.getComponent(4);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopf8.png")));
panel = (JPanel) chessBoard.getComponent(5);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightg8.png")));
panel = (JPanel) chessBoard.getComponent(6);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Rookh8.png")));
panel = (JPanel) chessBoard.getComponent(7);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawna7.png")));
panel = (JPanel) chessBoard.getComponent(8);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pb7.png")));
panel = (JPanel) chessBoard.getComponent(9);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnc7.png")));
panel = (JPanel) chessBoard.getComponent(10);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnd7.png")));
panel = (JPanel) chessBoard.getComponent(11);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawne7.png")));
panel = (JPanel) chessBoard.getComponent(12);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnf7.png")));
panel = (JPanel) chessBoard.getComponent(13);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawng7.png")));
panel = (JPanel) chessBoard.getComponent(14);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnh7.png")));
panel = (JPanel) chessBoard.getComponent(15);
panel.add(piece);
// White pieces on the board
piece = new JLabel(new ImageIcon(getClass().getResource("Pawna2.png")));
panel = (JPanel) chessBoard.getComponent(48);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnb2.png")));
panel = (JPanel) chessBoard.getComponent(49);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnc2.png")));
panel = (JPanel) chessBoard.getComponent(50);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnd2.png")));
panel = (JPanel) chessBoard.getComponent(51);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawne2.png")));
panel = (JPanel) chessBoard.getComponent(52);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnf2.png")));
panel = (JPanel) chessBoard.getComponent(53);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawng2.png")));
panel = (JPanel) chessBoard.getComponent(54);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Pawnh2.png")));
panel = (JPanel) chessBoard.getComponent(55);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Rooka1.png")));
panel = (JPanel) chessBoard.getComponent(56);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightb1.png")));
panel = (JPanel) chessBoard.getComponent(57);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopc1.png")));
panel = (JPanel) chessBoard.getComponent(58);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Queend1.png")));
panel = (JPanel) chessBoard.getComponent(59);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Kinge1.png")));
panel = (JPanel) chessBoard.getComponent(60);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Bishopf1.png")));
panel = (JPanel) chessBoard.getComponent(61);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Knightg1.png")));
panel = (JPanel) chessBoard.getComponent(62);
panel.add(piece);
piece = new JLabel(new ImageIcon(getClass().getResource("Rookh1.png")));
panel = (JPanel) chessBoard.getComponent(63);
panel.add(piece);
}
public void mousePressed(MouseEvent e) {
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel)
return;
Point parentLocation = c.getParent().getLocation();
xCoordinate = parentLocation.x - e.getX();
yCoordinate = parentLocation.y - e.getY();
chessPiece = (JLabel) c;
chessPiece.setLocation(e.getX() + xCoordinate, e.getY() + yCoordinate);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
}
// move pieces
public void mouseDragged(MouseEvent me) {
if (chessPiece == null)
return;
chessPiece.setLocation(me.getX() + xCoordinate, me.getY() + yCoordinate);
}
// drop a piece when mouse is released
public void mouseReleased(MouseEvent e) {
if (chessPiece == null)
return;
chessPiece.setVisible(false);
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JLabel) {
Container parent = c.getParent();
parent.remove(0);
parent.add(chessPiece);
}
else
{
Container parent = (Container) c;
parent.add(chessPiece);
}
chessPiece.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new ChessGame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
You should put your chessBoard JPanel into another BorderLayout-using JPanel.
This container JPanel will hold a GridLayout using JPanel on the left and on the bottom.
And these can hold JLabels which hold your row and column labels.
Edit
On second thought, better for the container JPanel to use a GridBagLayout so that the side JPanels will size correctly.
Edit 2
For example:
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ChessGame2 extends JPanel {
private static final int RANKS = 8;
private static final int FILES = RANKS;
private static final int SIDE = 80;
private static final Dimension SQUARE_SIZE = new Dimension(SIDE, SIDE);
private static final Color LIGHT_COLOR = new Color(238, 221, 187);
private static final Color DARK_COLOR = new Color(204, 136, 68);
private static final int GAP = 5;
private JPanel chessBoard = new JPanel(new GridLayout(RANKS, FILES));
public ChessGame2() {
for (int rank = 0; rank < RANKS; rank++) {
for (int file = 0; file < FILES; file++) {
JPanel square = new JPanel();
square.setPreferredSize(SQUARE_SIZE);
Color bg = (rank % 2 == file % 2) ? LIGHT_COLOR : DARK_COLOR;
square.setBackground(bg);
chessBoard.add(square);
}
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 2 * GAP, 0, 2 * GAP);
add(createRankPanel(), gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
add(createRankPanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.insets = new Insets(GAP, 0, GAP, 0);
add(createFilePanel(), gbc);
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.NORTH;
add(createFilePanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(0, 0, 0, 0);
add(chessBoard, gbc);
}
private JPanel createFilePanel() {
JPanel filePanel = new JPanel(new GridLayout(1, 0));
for (int i = 0; i < FILES; i++) {
char fileChar = (char) ('A' + i);
filePanel.add(new JLabel(String.valueOf(fileChar), SwingConstants.CENTER));
}
return filePanel;
}
private JPanel createRankPanel() {
JPanel rankPanel = new JPanel(new GridLayout(0, 1));
for (int i = 0; i < RANKS; i++) {
int row = RANKS - i;
rankPanel.add(new JLabel(String.valueOf(row)));
}
return rankPanel;
}
private static void createAndShowGui() {
ChessGame2 mainPanel = new ChessGame2();
JFrame frame = new JFrame("Chess Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:
The panel that you return from the chess board should be your custom class extending JPanel and in there you will want to override paintComponent().
I've a positioning problem with the GridBagLayout :
I try to place in center (at the top) a label but with my code (for a reason which I didn't see), I've this :
I want that the label Test are at the top of my window and in center. Someone can explain me the reason of this bad positionnement ?
My program :
public class Accueil extends JFrame {
private JPanel home = new JPanel();
private GridBagConstraints grille = new GridBagConstraints();
private JLabel title = new JLabel("Test");
public Accueil() {
home.setLayout(new GridLayout());
init_grille();
init_title();
this.add(home);
this.setSize(600,600);
this.setTitle("Test One");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void init_grille() {
grille.fill = GridBagConstraints.BOTH;
grille.weightx = 2;
grille.weighty = 5;
grille.ipady=grille.anchor=GridBagConstraints.CENTER;;
}
private void init_title() {
grille.fill = GridBagConstraints.HORIZONTAL;
grille.gridx = 0;
grille.gridy = 0;
home.add(title,grille);
}
public static void main(String [] args) {
new Accueil();
}
}
This won't help:
home.setLayout(new GridLayout());
You probably want:
home.setLayout(new GridBagLayout());
Also, these changes should work:
private void init_title() {
grille.fill = GridBagConstraints.NONE;
grille.gridx = 0;
grille.gridy = 0;
grille.anchor = GridBagConstraints.NORTH;
home.add(title,grille);
}