Chess GUI - Getting 2 user clicks before calling a funtion - Java - java

I am trying to make a simple chess GUI, that consists only in a gridLayout where each square is made of a button, each button has an ActionListener and works independantly of the actual game, only "printing out" what is happening in the Board class.
private JButton[][] squares = new JButton[8][8];
private Color darkcolor = Color.decode("#D2B48C");
private Color lightcolor = Color.decode("#A0522D");
public ChessGUI(){
super("Chess");
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(lightcolor);
}else{
squares[i][j].setBackground(darkcolor);
}
contents.add(squares[i][j]);
squares[i][j].addActionListener(buttonHandler);
squares[i][j].setSize(75, 75);
}
}
setSize(600, 600);
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
}
private class ButtonHandler implements ActionListener{
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]){
//Pass set of coordinates to game.Move(...)
return;
}
}
}
}
}
I need to pass 2 sets of coordinates, the "from" and the "to" to the game.Move(...) function(function that aplies game movement logic), where each set of coordinates is given by a click in a button.
How should i handle the fact that i need to wait for the user to make 2 clicks before calling the game.Move(...) function? It seems it can only pass 1 set of coordinates at a time.
Any help would be apricieated.

In game object you should probably have field variables that will store the from and to coordinates instead of passing them into game.move function. You can make a counter that starts at 0. When it is 0, it will process the "from" click (set the "from" variable in Game to the coordinate that was clicked), and when it is 1, it will process the "to" click (set "to" variable in Game), call move, and reset counter back to 0.

Related

Trying to add label on panel

I am trying to put a label in every single panel I create but I only get the label in the last panel created. Its for a game of snakes and ladders and I am trying to initiate the board for the game. I need every panel to have a number.
public InitBoard() {
JPanel jPanel1 = new JPanel(new GridLayout(10, 10, 0, 0));
JPanel[][] pa = new JPanel[10][10];
//jPanel1.setSize(1024,1080);
int counter=1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JPanel tiles = new JPanel();
tiles.setBorder(BorderFactory.createLineBorder(Color.BLACK));
number++;
label1.setText(String.valueOf(number));
tiles.add(label1);
if(counter == 1) {
tiles.setBackground(Color.green);
}
if (counter == 2) {
tiles.setBackground(Color.red);
}
if(counter == 3 ){
tiles.setBackground(Color.cyan);
}
counter++;
pa[i][j] = tiles;
jPanel1.add(pa[i][j]);
if(counter ==5){
counter =1;
}
}
}
add(jPanel1, BorderLayout.CENTER);
setSize(960, 960);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
Following image is shown when I run the file.
Any help is appreciated in advance.
I can't see this from the code that you posted, but it seems that you are re-using the same JLabel instance (label1) for all the tiles. This somehow leads to the label being overwritten and re-used for all tiles except the last one.
Just use this line:
tiles.add(new JLabel(String.valueOf(number)));
instead of what you currently have:
label1.setText(String.valueOf(number));
tiles.add(label1);
Making this change, I got your code to work as intended, showing a number on every tile. If the numbers need to be stored somewhere or if you need to be able to change them later, you might want to create an array similar to the one you have for the JPanels (pa).

Make an jButton ImageIcon move between 2 jButtons in an array

I'm trying to make the image icon of ballpos move between two JButtons in my JButton array. These are buttons 99 and 108 on every press of a separate JButton jBAct, so that on every press of jBAct the image will move one down to 99 then once reached 99 will go up to 108 then go back down to 99 again and so on.
Here is what I've tried, i know it's wrong but i think it's along these lines.
if (event.getSource() == jBAct)
{
if (ballpos > 99)
{
jBGame[ballpos-1].setIcon(new ImageIcon("src/ball.png"));
jBGame[ballpos].setIcon(new ImageIcon());
ballpos--;
} else {
if (ballpos < 108){
jBGame[ballpos+1].setIcon(new ImageIcon("src/ball.png"));
jBGame[ballpos].setIcon(new ImageIcon());
ballpos++;
}
}
}
This code segment is in class public class CBabyBallBounce extends JFrame implements ActionListener
and part of method public void actionPerformed(ActionEvent event)
The direction in which the ball moves is not kept anywhere in your code, so when a ball reaches a position between 99 and 108 you can't know in which direction to move it. I suggest keeping this information in the ActionListener responsible for this behavior.
In the following example I have an array of 4 buttons between which the ball moves. I represent the ball with a String, but the concept is the same for an image.
public class Buttons {
JButton[] buttons = new JButton[4];
JButton move = new JButton("Move");
private final String text = "O";
Buttons() {
JPanel panel = new JPanel();
for (int i = 0; i < buttons.length; i++)
panel.add(buttons[i] = new JButton());
buttons[2].setText(text);
move.addActionListener(new ActionListener() {
private int ballpos = 2;
private int dir = 1;
#Override
public void actionPerformed(ActionEvent e) {
buttons[ballpos].setText(null);
ballpos += dir;
buttons[ballpos].setText(text);
if (ballpos == buttons.length - 1)
dir = -1;
else if (ballpos == 0)
dir = 1;
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.add(move, BorderLayout.PAGE_START);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Buttons());
}
}
I would highly recommend to add an ActionListener per button or group of buttons that share the same behavior as I did above. It allows you to encapsulate the behavior of the button. Do not have the frame implement a "global" ActionListener and then find the source of the event by if-else statements. This leads to a mess and more bugs.
The code inside actionPerformed can be slightly cleverer, but I went for readable for this example. If you understand it you can change it in a number of different ways.
As a final note, don't create a new image icon each time. Crate the image once and store it as I did for my string (which, for a string, is redundant, since Strings are special). You can also use null instead of an empty image, again, as I did for the string case.

How to make a copy of an ImageIcon JButton on a current JPanel each time it is clicked?

I am creating a Swing Game GUI, which contains multiple panels that are part of a frame. Each panel contains a number of ImageIcon JButtons. When a JButton is clicked it will randomly position itself on the screen. For this particular panel i am not using a certain LayoutManager(understand the criticism here, but also the frame is not resizable as it fits the entire screen) and I use the randomness of setBounds(x, y, 100, 100) for this image JButton to appear on a random spot inside that panel. My only trouble is to figure it out, how to save the previous position of a certain JButton, so if the user repeatedly clicks it, it will duplicate and will appear on the screen multiple times on a random position, leaving all others displayed.
class ButtonListener implements ActionListener
{
Random randomCoord = new Random();
//random location in on the screen 30-150 x 200-400
int x = randomCoord.nextInt(150-30) + 30;
int y = randomCoord.nextInt(400-200) + 200;
int butnCOUNT = 0;
public void actionPerformed (ActionEvent event)
{
if (event.getSource() == button1)
{
butnCOUNT ++;
JButton[] addButtons = new JButton[butnCount];
for (int i = 0; i < addButtons.length; i++)
{
addButtons[i] = butnCloud; // ImageIcon JButton
addButtons[i].addActionListener(new ButtonListener ());
panel5.add(addButtons[i]);
panel5.setVisible(true);
panel5.setOpaque(false);
panel5.setBounds(x, y, 20, 20);
}
}
}

Adding buttons on a paintComponent drawn shape

My program is consist of two classes(test and paintClass) in different files. In the paintClass class I draw a 5x5 square board by using paintComponent method. I want to add buttons in each small square in the big square. When I run the code I don't get any buttons. I want to have 25(5x5) buttons by using jpanel on a shape drawn by paintComponent. Is this possible? If it is, how I can do it?
EDIT : The problem was the loop. Number had a default value of 0 so the loop didn't work. I defined number at the beginning. It solved the problem. Also one of the invervals were wrong. I changed j = 0 with j = 1.
import javax.swing.*;
import java.awt.*;
public class test
{
public static void main(String[] args)
{
JFrame frame = new JFrame("buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250,250);
PaintClass paint = new PaintClass();
paint.repaint();
f1.getContentPane().add(paint);
frame.pack();
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class PaintClass extends JPanel
{
private Graphics g;
private int interval,side,number;
private JButton button;
public PaintClass()
{
number = 5;
button = new JButton();
setLayout(new GridLayout(5,5));
for(int i = 0; i <= number - 1; i++)
{
for(int j = 1; j <= number - 1; j++)
{
button = new JButton();//ADDED
button.setBounds(i * interval, 0, interval, interval);
add(button);
}
button = new JButton();//ADDED
button.setBounds(0, i * interval, interval, interval);
add(button);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.repaint();
side = 250;
number = 5;
interval = side / number;
g.drawRect(0,0, side, side);
for(int i = 0; i <= number - 1; i++)
{
for(int j = 0; j <= number - 1; j++)
{
g.drawLine(i * interval, 0, i * interval, side);
}
g.drawLine(0, i * interval, side, i * interval);
}
}
}
Choose one or the other: either add the buttons using the GridLayout, or paint the buttons using paintComponent. If the former, you should a) define the loop constraint (right now it is 0) b) create a new JButton for every loop (your code currently reuses the instance) and c) register the appropriate ActionListener to respond to events. If the latter, you need to register the appropriate listener (like MouseListener) to respond to user generated events.
private int interval,side,number;
Number has a default value of 0.
for(int i = 0; i <= number - 1; i++)
Since number is 0, your loop will never execute.
Once you do this the buttons will be added to the panel but they will cover your custom painting. To see background lines you just need to set the background of the panel to Color.BLACK and then create your GridLayout with a gap between the components. Read the API for the method to use.

Changing the position of images on the JFrame

So I am making this ABC learning game , What I want to do is if I click on the A button more than once then , the three Images will change their position, What I want to do is this
![enter image description here][1]
When I click on A button, the three image will appear on the screen, the first is apple as I set it that way in the loop, but the second two images will appear randomly, though sometimes one o them is apple again, I could fix that.
My Question is, how can I change that position of the Apple to the second and second image to the first and third image to the second position if the "A" button is clicked more than once.
SO, the result will be the apple will change position based on the click "A" button and other two picture changes their position and chosed randomly from the array.
So, here is my code for the JPanel, where everything takes place.Most of the code is explained in the comments
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.*;
import java.text.AttributedCharacterIterator;
import java.util.Random;
import javax.swing.ImageIcon;
/**
*
* #author Dip
*/
public class AbcGeniusPanel extends JPanel implements ActionListener {
//Declare the necessary Variables here
private JButton[] buttons; //create an array for buttons
private BorderLayout layout; //Declare object of BorderLayout
private Image image = null;
private boolean showImage = false;
//Initialize all the variables here
static int index = 0;
int randNumber = 0, id = 0;
int q = 0, w = 0;
int buttonClick = 0;
//Store all the imahges that will appear on the screen into an String type array
private static String[] imageList = {"src/Images/1.png", "src/Images/2.png", "src/Images/3.png", "src/Images/4.png", "src/Images/5.png", "src/Images/6.png", "src/Images/7.png", "src/Images/8.png", "src/Images/9.png", "src/Images /10.png",
"src/Images/11.png", "src/Images/12.png", "src/Images/13.png", "src/Images /14.png", "src/Images/15.png",
"src/Images/16.png", "src/Images/17.png", "src/Images/18.png", "src/Images /19.png", "src/Images/20.png",
"src/Images/21.png", "src/Images/22.png", "src/Images/23.png", "src/Images /24.png", "src/Images/25.png",
"src/Images/26.png"
};
//Define the constructor here
public AbcGeniusPanel() {
ImageIcon[] alphabets = new ImageIcon[26];
setBackground(Color.yellow);
//Load the images for alphabet images into the alphabets array using a for loop
for (int i = 0; i < alphabets.length; i++) {
alphabets[i] = new ImageIcon("C:\\Users\\Dip\\Desktop\\Java Projects\\AbcGeniusApp\\src\\Alphabets\\" + (i + 1) + ".png");
}
//Create a JPnael object
JPanel panel = new JPanel();
//Set a layoutManager on the panel
//panel.setLayout(new FlowLayout(FlowLayout.CENTER)); //This is not workling good
panel.setLayout(new GridLayout(2, 13, 5, 5)); //This is good for now
//Create an array for holdoing the buttons
buttons = new JButton[26];
//This Loop will Store the buttons in the buttons array attatching each image for each button
//Try passing Images inside the JButton parameter later.
for (int i = 0; i < 26; i++) {
buttons[i] = new JButton(alphabets[i]);
}
// Now Setting up a new Borderlayout so that we can set the whole gridLayout at the botton of the panel
setLayout(new BorderLayout(2, 0));
//add the panel to the Border layout
add(panel, BorderLayout.SOUTH);
//Add evenHandling mechanism to all the buttons
for (int k = 0; k < 26; k++) {
buttons[k].addActionListener(this);
}
for (int count1 = 0; count1 < 26; count1++) {
panel.add(buttons[count1]);
}
}
//This Method will generate a random Number and return it
public int random_number() {
int rand_num;
Random generator = new Random(System.currentTimeMillis());
rand_num = generator.nextInt(26);
return rand_num;
}
//This method will draw the font on the Panel
public void paintComponent(Graphics g) {
Font font; //Declare Font object here
font = new Font("Wide Latin", Font.BOLD, 22); //Set font
super.paintComponent(g); //Ensure the drawing in super class
g.setFont(font); //Set the font
g.setColor(Color.RED);
String text = "CLICK ON THE RIGHT IMAGE!"; //Display the text
g.drawString(text, 255, 20);
}
//To draw the picture on the screen we need to override the paint Method
#Override
public void paint(Graphics g) {
super.paint(g);
//Here, x and y will determine the x and y position os each image
int x = 0, y = 0;
// the varibale q is declared above
for (q = 0; q < 3; q++) //This loop will generate three images on the screen
{
if (showImage) {
x = x + 265; //X-Position of the image
y = 90; //Y-Position of the image
//q is declared as q=0, so this will always be true
if (w == 1 || q == 0) {
g.drawImage(image, x, y, image.getWidth(null), image.getHeight(null), null); //This method will put the image on the screen
showImage = true;
w = 0;
}
while (true) //this loop will run anyway
{
//go inside this loop only when the generated random
//doesn't match with the index of the button that was pressed
while ((randNumber = random_number()) != index) {
index = randNumber; //Now put the randomVlaue in the index
this.image = new ImageIcon(imageList[randNumber]).getImage();
showImage = true;
//make w=1 so that we can break from the outer loop
w = 1;
//break from the inner loop
break;
}
//Since we have made the w=1, so we are breaking out of the outer loop
if (w == 1) {
break;
}
}
}
}
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
id = 0;
while (true) {
//id is set to zero, for example if the button A (buttons[0])is not pressed then it will go below
//to increase id until it matches the index of the button that we pressed
if (source == buttons[id]) {
//get the image of that same index of the buttons and then set the showImage true
//SO the the paint function above can draw the image
this.image = new ImageIcon(imageList[id]).getImage();
showImage = true;
//save the index of the button that is presed in another variable
//then break from the while loop
index = id;
break;
} else {
id++;
//This is necessary to make sure that id will cross 26
//becasue we have only 26 letters or the array index is 26
//so highest value can be 26 only
id = id % 26;
}
}
repaint();
}
}
Add 3 JLabels or JButtons (whatever will be displaying the images) into a JPanel container. The JPanel will likely use a GridLayout(1, 3, horizontal_gap, 0) layout.
Place all images as ImageIcons into an ArrayList.
Shuffle the ArrayList when needed
After shuffling place the Icons into the JLabels/JButtons in a for loop using the setIcon(...) method.
Note that
your JPanel should override paintComponent, not paint. The paint method is responsible for painting a component's children and borders, and it does not use double buffering by default, making a more dangerous method to override.
Putting in a while (true) loop into your Swing GUI without regard to threading is extremely dangerous.
Putting this into a painting method such as paint is GUI suicide. Never do this since a painting method is a major determinant in the perceived responsiveness of your program. If you slow it down, the program will be perceived as being slow and poorly responsive, and thus it must be lean and fast as possible, and you should have painting and only painting code within it.
Your paint method has program logic in it, something that also shouldn't be done. You don't have full control over whether or even if a painting method will be called, and so program logic should never be placed inside one of these.
As MadProgrammer well notes, don't use the src path for your images as this won't exist once you build your program into a jar file. Better to Create a resource directory in the jar file, and to refer to your images as resources, not as files.

Categories

Resources