I am making a chess game for a class I have and the chess piece is not displaying correctly.
This is my code:
package SucksLego;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import SucksLego.CheesBoard.CaseEchiquier;
import lejos.nxt.ColorSensor.Color;
public class ChessBoard2 extends JFrame{
private Container contents;
private JButton [][] squares = new JButton [8][8];
private int row = 7;
private int col = 1;
private ImageIcon piece = new ImageIcon ("chess-pawn-f.png");
public ChessBoard2 (){
super("Board");
contents = getContentPane();
contents.setLayout(new GridLayout (8,8));
ButtonHandler buttonHandler = new ButtonHandler();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
squares[i][j] = new JButton();
if((i+j) % 2 != 0){
squares[i][j].setBackground(getBackground().BLACK);
}
contents.add(squares [i][j]);
squares[i][j].addActionListener(buttonHandler);
}
}
squares [row][col].setIcon (piece);
setSize(500,500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
private boolean isValidMove(int i, int j){
System.out.println("I: " + i + " J: " + j);
return true;
}
private void processClick (int i, int j){
if(isValidMove(i,j) == false){
return;
}
squares[row][col].setIcon(null);
squares[i][j].setIcon(piece);
row=i;
col=j;
}
private class ButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if(source == squares[i][j]){
processClick(i,j);
return;
}
}
}
}
}
public static void main(String[] args) {
ChessBoard2 chess = new ChessBoard2();
}
}
The dimension of the icon is 60 x 60.
The icon is being displayed as a very small stip:
You are not getting the image, change your code and add below code to your ChessBoard2() constructor under super("Board");
try{
URL resource = ChessBoard2.class.getClassLoader().getResource("chess-pawn-f.png");
img = ImageIO.read(resource);
piece = new ImageIcon(img);
}
catch (IOException e)
{
e.printStackTrace();
}
Related
I am trying to make a method that disables JButtons.
The JButtons are in an array in the form of a grid, JButton [int][int] and the integers are supposed to be coordinates.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class BS {
public static JFrame f = new JFrame("BS");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
initializeGui();
}
});
}
static void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3,1));
//This is the array of the JButtons in the form of a grid
final JButton[][] coordinates = new JButton[15][15];
JPanel field;
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
field = new JPanel(new GridLayout(0, 15));
field.setBorder(new CompoundBorder(new EmptyBorder(15,15,15,15),new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(field);
gui.add(boardConstrain);
//The making of the grid
for (int ii = 0; ii < coordinates.length; ii++) {
for (int jj = 0; jj < coordinates[ii].length; jj++) {
JButton b = new JButton();
ImageIcon icon = new ImageIcon(
new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
coordinates[jj][ii] = b;
field.add(coordinates[jj][ii]);
}
}
f.add(gui);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
I did some changes in your code:
public static JFrame f = new JFrame("BS"); JFrame shouldn't be static and should have a more meaningful name (like frame for example).
final JButton[][] coordinates = new JButton[15][15]; moved this array as a class member and made it non final and also changed the name to buttons as it's easier to know what it is (coordinates to me, sounds more like an array of Point or int)
After that I added an ActionListener, see How to use Actions tutorial.
private ActionListener listener = e -> {
//Loops through the whole array in both dimensions
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) { //Find the JButton that was clicked
if (isStartButton) { //startButton is a boolean variable that tells us if this is the first button clicked or not
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons(); //Only when we have clicked twice we disable all the buttons in between
}
isStartButton = !isStartButton; //In every button click we change the value of this variable
break; //No need to keep looking if we found our clicked button. Add another one with a condition to skip the outer loop.
}
}
}
};
And a method called disableButtons() which disables all the buttons between the 2 clicked buttons:
private void disableButtons() {
compareCoords(); //This method checks if first button clicked is after 2nd one.
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false); //We disable all buttons in between
}
}
}
At the end our code ends like this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class DisableButtonsInBetween {
private JFrame frame = new JFrame(getClass().getSimpleName());
private JButton[][] buttons;
private int startXCoord = -1;
private int startYCoord = -1;
private int endXCoord = -1;
private int endYCoord = -1;
private boolean isStartButton = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisableButtonsInBetween().initializeGui();
}
});
}
void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3, 1));
// This is the array of the JButtons in the form of a grid
JPanel pane;
buttons = new JButton[15][15];
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
pane = new JPanel(new GridLayout(0, 15));
pane.setBorder(new CompoundBorder(new EmptyBorder(15, 15, 15, 15), new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(pane);
gui.add(boardConstrain);
// The making of the grid
for (int ii = 0; ii < buttons.length; ii++) {
for (int jj = 0; jj < buttons[ii].length; jj++) {
buttons[jj][ii] = new JButton();
ImageIcon icon = new ImageIcon(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
buttons[jj][ii].setIcon(icon);
buttons[jj][ii].addActionListener(listener);
pane.add(buttons[jj][ii]);
}
}
frame.add(gui);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
//The ActionListener is what gets called when you click a JButton
private ActionListener listener = e -> {
//These for loops are done to identify which button was clicked.
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
//We save the coords of the 1st button clicked
startXCoord = i;
startYCoord = j;
} else {
//We save the coords of the 2nd button clicked and call the disableButtons method
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
};
//This method disables all the buttons between the 2 that were clicked
private void disableButtons() {
compareCoords();
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false);
}
}
}
//This method compares the coords if the 2nd button was before (in its coords) than the 1st one it switched their coords
private void compareCoords() {
if (endXCoord < startXCoord) {
int aux = startXCoord;
startXCoord = endXCoord;
endXCoord = aux;
}
if (endYCoord < startYCoord) {
int aux = startYCoord;
startYCoord = endYCoord;
endYCoord = aux;
}
}
}
I hope this is what you were trying to do... if not please clarify.
I do not have the arrow operator, " -> ". I think it requires a higher Java. Is there a way to replace this?
For Java 7 and lower use this for the ActionListener:
private ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
}
};
I created a Class that extends from JFrame which has a table of buttons. In the class constructor I added the buttons to the panel but when I run the main nothing happens and I see only an empty frame. So can you hep me to find the problem?
This is the code:
public class Tita extends JFrame {
JButton ff[][] = new JButton[3][3];
int i = 0, j = 0;
public static void main(String[] args) {
Tita oo = new Tita();
}
public Tita() {
super("Newframe");
setVisible(true);
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
ff[i][j].setText("sss");
this.getContentPane().add(ff[i][i]);
}
}
}
What is happening is that you haven't initialized any JButton, also, when you add the button you have getContentPane().add(ff[i][i]);, when it should be getContentPane().add(ff[i][j]);
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Tita extends JFrame {
JButton ff[][] = new JButton[3][3];
int i = 0, j = 0;
public static void main(String[] args) {
Tita oo = new Tita();
}
public Tita() {
super("Newframe");
setVisible(true);
setLocationRelativeTo(null);
setSize(new Dimension(300, 400));
setLayout(new GridLayout(3, 0));
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
ff[i][j] = new JButton("SSS");
ff[i][j].setSize(30, 10);
getContentPane().add(ff[i][j],i);
}
}
}
}
I have a 2d array of Grids (JPanels) that are added to another JPanel using the GridLayout. That JPanel is added to the JFrame. Whenever a click happens on the JFrame I'm attempting to take the Point of the click and determine if any of those Grids in the 2d array contain that Point.
I'm attempting to do this inside frame.addMouseListener...
I know the frame is registering the mouse clicks. For some reason the Grids don't register that they should be containing that Point. Can anyone explain this? if(theView[i][j].contains(me.getPoint())){ This is the line of code that seems to be failing me.
I originally attempted to have the Grids know when they were clicked on so I wouldn't have to coordinate between the frame and grids, but I couldn't get that to work.
Here's the level designer.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import javax.swing.*;
public class LevelDesigner extends JPanel implements ButtonListener{
private final int SIZE = 12;
private int [][] thePit;
private Grid [][] theView;
private ButtonPanel bp;
public static int val;
private int rows, cols;
private JPanel gridPanel;
private JFrame frame;
public LevelDesigner(int r, int c){
frame = new JFrame();
int h = 10, w = 10;
setVisible(true);
setLayout(new BorderLayout());
setBackground(Color.BLUE);
rows = r;
cols = c;
thePit = new int[r][c];
theView = new Grid[r][c];
gridPanel = new JPanel();
gridPanel.setVisible(true);
gridPanel.setBackground(Color.BLACK);
gridPanel.setPreferredSize(getMaximumSize());
GridLayout gridLayout = new GridLayout();
gridLayout.setColumns(cols);
gridLayout.setRows(rows);
gridPanel.setLayout(gridLayout);
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
theView[i][j] = new Grid(i, j, SIZE, this);
gridPanel.add(theView[i][j]);
}
}
String test [] = {"0", "1","2","3","4","save"};
bp = new ButtonPanel(test, this);
this.add(bp, BorderLayout.SOUTH);
this.add(gridPanel, BorderLayout.CENTER);
frame.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me) {
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
if(theView[i][j].contains(me.getPoint())){
theView[i][j].actionPerformed(null);
return;
}
}
}
}
});
frame.setVisible(true);
frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
frame.setTitle("Epic Crawl - Main Menu");
frame.pack();
frame.setLocationRelativeTo(null);
frame.repaint();
frame.add(this);
}
public String toString(){
int noRows = thePit.length;
int noColumns = thePit[0].length;
String s="";
for (int r=0;r<noRows;r++){
for (int c=0;c<noColumns;c++){
s=s + thePit[r][c] + " ";
}
s=s+"\n";
}
return(s);
}
public void notify( int i, int j){
thePit[i][j] = val;
}
public void print(){
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("."));
int returnVal = fc.showSaveDialog( null);
if( returnVal == JFileChooser.APPROVE_OPTION ){
try{
PrintWriter p = new PrintWriter(
new File( fc.getSelectedFile().getName() ) );
System.out.println(" printing");
p.println( this );
p.close();
}
catch( Exception e){
System.out.println("ERROR: file not saved");
}
}
}
public void buttonPressed(String buttonLabel, int id){
if(id == 5)
print();
else
val = id;
}
public void buttonReleased( String buttonLabel, int buttonId ){}
public void buttonClicked( String buttonLabel, int buttonId ){}
public static void main(String arg[]){
LevelDesigner levelDesigner = new LevelDesigner(4, 4);
}
}
And here is the Grid.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Grid extends JPanel implements ActionListener{
LevelDesigner grid;
int myI, myJ;
private String[] imageNames = {"dirt.png", "grass.png", "Door.png", "woodfloor.png", "32x32WoodFloor.png"};
BufferedImage gridImage;
private String imagePath;
public Grid(int i, int j, int size, LevelDesigner m){
imagePath = "";
grid = m;
myI = i;
myJ = j;
setBackground(Color.RED);
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae){
grid.notify(myI, myJ);
imagePath = "Images/" + imageNames[LevelDesigner.val];
gridImage = null;
InputStream input = this.getClass().getClassLoader().getResourceAsStream(imagePath);
try{
gridImage = ImageIO.read(input);
}catch(Exception e){System.err.println("Failed to load image");}
}
public void paintComponent(Graphics g){
super.paintComponent(g); // Important to call super class method
g.clearRect(0, 0, getWidth(), getHeight()); // Clear the board
g.drawImage(gridImage, 0, 0, getWidth(), getHeight(), null);
}
}
The contains method checks if the Point is within the boundaries of the JPanel but using a coordinate system relative to the JPanel. Instead consider using findComponentAt(Point p).
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class TestMouseListener {
private static final int SIDE_COUNT = 4;
private JPanel mainPanel = new JPanel();
private MyGridCell[][] grid = new MyGridCell[SIDE_COUNT][SIDE_COUNT];
public TestMouseListener() {
mainPanel.setLayout(new GridLayout(SIDE_COUNT, SIDE_COUNT));
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = new MyGridCell();
mainPanel.add(grid[i][j].getMainComponent());
}
}
mainPanel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Component c = mainPanel.findComponentAt(p);
for (MyGridCell[] gridRow : grid) {
for (MyGridCell myGridCell : gridRow) {
if (c == myGridCell.getMainComponent()) {
myGridCell.setLabelText("Pressed!");
} else {
myGridCell.setLabelText("");
}
}
}
}
});
}
public Component getMainComponent() {
return mainPanel;
}
private static void createAndShowGui() {
TestMouseListener mainPanel = new TestMouseListener();
JFrame frame = new JFrame("TestMouseListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel.getMainComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyGridCell {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
#SuppressWarnings("serial")
private JPanel mainPanel = new JPanel() {
public Dimension getPreferredSize() {
return MyGridCell.this.getPreferredSize();
};
};
private JLabel label = new JLabel();
public MyGridCell() {
mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.setLayout(new GridBagLayout());
mainPanel.add(label);
}
public Component getMainComponent() {
return mainPanel;
}
public void setLabelText(String text) {
label.setText(text);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
}
Component#contains "Checks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component"
This means that the contains will only return true if the Point is within the bounds of 0 x 0 x width x height.
So if the component is position at 400x200 and is sized at 200x200 (for example). When you click within in, the mouse point will be between 400x200 and 600x400, which is actually out side of the relative position of the component (200x200) - confused yet...
Basically, you either need to convert the click point to a relative coordinate within the context of the component you are checking...
Point p = SwingUtilities.convertPoint(frame, me.getPoint(), theView[i][j])
if (theView[i][j].contains(p)) {...
Or use the components Rectangle bounds...
if (theView[i][j].getBounds().contains(me.getPoint())) {...
So, remember, mouse events are relative to the component that they were generated for
The code is working fine.When i left click it does everything the code discribes.The only problem is that i don't want to click an the same spot!I can't find a solution to that.Any suggestions?
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
innerCells[i][j] = new JPanel();
innerCells[i][j].setLayout(new BorderLayout());
innerCells[i][j].setBorder(BorderFactory.createLineBorder(lineColor));
innerCells[i][j].setBackground(backgroundColor);
innerCells[i][j].addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
JPanel k = (JPanel) e.getSource();
JLabel l = new JLabel("", JLabel.CENTER);
int x = getRows();
int y = getCols();
for (int r = 0; r < getRows(); r++) {
for (int c = 0; c < getCols(); c++) {
if (innerCells[r][c] == k) {
x = r;
y = c;
}
}
}
if (array[x][y] == 0) {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.white);
k.revalidate();
} else {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.red);
k.revalidate();
}
randomHits();
}
If the panels never need to respond to another mouse click, simply dereigster the associated mouse listener...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class NoMoreClicks {
public static void main(String[] args) {
new NoMoreClicks();
}
public NoMoreClicks() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
add(new JLabel("Single Clicked Pane..."));
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
e.getComponent().removeMouseListener(this);
JOptionPane.showMessageDialog(e.getComponent(), "Was Clicked");
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Guys thanks for help by i manage to find the solution myself!I had to add only one line of code,i mean only one checking!The solution is
if (k.getComponents().length == 0)
that means if its clicked its not 0.Thank you all for trying!
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
innerCells[i][j] = new JPanel();
innerCells[i][j].setLayout(new BorderLayout());
innerCells[i][j].setBorder(BorderFactory.createLineBorder(lineColor));
innerCells[i][j].setBackground(backgroundColor);
innerCells[i][j].addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
JPanel k = (JPanel) e.getSource();
JLabel l = new JLabel("", JLabel.CENTER);
int x = getRows();
int y = getCols();
for (int r = 0; r < getRows(); r++) {
for (int c = 0; c < getCols(); c++) {
if (innerCells[r][c] == k) {
x = r;
y = c;
}
}
}
if (k.getComponents().length == 0) {
if (array[x][y] == 0) {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.white);
k.revalidate();
} else {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.red);
playerhit++;
GameScreen.FinalWinner();
k.revalidate();
}
randomHits();
}
}
I want show on concerned cases (row 2 from the grid), my JLabel contained in my Pawn class.
if(i==1 && (j>-1 && j<8)) { new Pawn(colorr); }
generate the Pawn but on the grid, the JLabel named 'label' isn't showed.
EDIT:I corrected some things like the container usage but my problem about my JLabel showing and to move my Pawn piece is still here.
I would also enjoy to move later the Pawn to another position on the grid.
package coordboutons;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CoordBoutons extends JFrame {
JFrame frame;
private Color colorr=Color.RED;
//private Container[][] cp=new Container[8][8];
CoordBoutons() {
super("GridLayout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contenant = getContentPane();
contenant.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
contenant.add(new CaseEchiquier(i, j));
}
}
pack();
setVisible(true);
}
class CaseEchiquier extends JPanel {
private int lin, col;
protected Color color;
CaseEchiquier(int i, int j) {
lin = i;
col = j;
setPreferredSize(new Dimension(80, 75));
setBackground((i + j) % 2 == 0 ? Color.WHITE : Color.GRAY);
if(i==1 && (j>-1 && j<8)) { new Pawn(colorr); }
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e){
CaseEchiquier current =(CaseEchiquier)e.getSource(); // get the object that the user pressed
// int linX = current.getLin();
// int colY = current.getCol();
System.out.println(lin+" "+col);
}
});
}
public int getCol() {
return col;
}
public int getLin() {
return lin;
}
}
public class ChessPiece
{
Color color;
JLabel label;
}
public class Pawn extends ChessPiece
{
public Pawn(Color c)
{
this.color = c;
setBackground(colorr);
System.out.println("YATAAA !");
this.label = new JLabel(new ImageIcon("bp.png"));
//I need to show this label !;
}
public Color getColor()
{
return this.color;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
CoordBoutons coordBoutons = new CoordBoutons();
}
});
}
}
I like to point out two major problems I saw in your code (there can be more :))
In your CoordButtons constructor you are doing the same thing 64
times. According to what I understood you want to create a grid of
8x8. So set the content pane layout to a 8x8 grid and add panels to
it.
CoordBoutons() {
super("GridLayout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
getContentPane().add(new CaseEchiquier(i, j));
}
}
pack();
setVisible(true);
}
In your CaseEchiquier class just creating a Pawn object will
not help you to display it. Instead add the label of Pawn object to
your JPanel
if(i==1 && (j>-1 && j<8)) {
Pawn p = new Pawn(colorr);
add(p.label);
}