I would like to know how to make the yellow and magenta squares clickable for the game I am creating. The game is called 1,2, …, 10 if you would like to research/learn how to play.
I tried to use things off of the Internet, but they didn’t work…
What I would like to learn is how to create a button for the yellow and magenta squares, so I am able to click them during the game.
I think there might be something called a Jbutton, but I don’t know how it operates.Sorry that I am ranting, but I can’t post this until I have enough code to text ratio.
Here is my code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import java.awt.Font;
import javax.swing.*;
public class GraphicsPanel extends JPanel{
public GraphicsPanel(){
setPreferredSize(new Dimension(500, 500));
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
//1x10 board for the game:
int count = 0;
int [] board = new int [10];
for (int i = 0; i < board.length; i++) {
g2.drawRect(0 + count, 250, 50, 50);
count += 50;
}
//Labels for each square 1-10:
g2.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g2.drawString("1", 20, 325);
g2.drawString("2", 70, 325);
g2.drawString("3", 120, 325);
g2.drawString("4", 170, 325);
g2.drawString("5", 220, 325);
g2.drawString("6", 270, 325);
g2.drawString("7", 320, 325);
g2.drawString("8", 370, 325);
g2.drawString("9", 420, 325);
g2.drawString("10", 465, 325);
//Title and instructions for players:
g2.drawString("1, 2, …, 10 Game", 175, 25);
g2.drawString("To Play: Players alternate placing either one or two pieces", 10, 60);
g2.drawString("on the leftmost open squares. In this game, we don’t", 30, 85);
g2.drawString("distinguish between players’ pieces, so we’ll call", 40, 110);
g2.drawString("them left and right. Left will go first.", 85, 135);
g2.drawString("The first player to place the tenth piece on the board wins!", 15, 170);
//Buttons for Players to select their move:
g2.setColor(Color.YELLOW);
g2.fillRect(50, 400, 50, 50);
g2.setColor(Color.MAGENTA);
g2.fillRect(100, 400, 50, 50);
g2.setColor(Color.YELLOW);
g2.fillRect(350, 400, 50, 50);
g2.setColor(Color.MAGENTA);
g2.fillRect(400, 400, 50, 50);
g2.setColor(Color.BLACK);
g2.drawRect(50, 400, 50, 50);
g2.drawRect(100, 400, 50, 50);
g2.drawRect(350, 400, 50, 50);
g2.drawRect(400, 400, 50, 50);
//Labels for players buttons:
g2.drawString("Player 1", 67, 385);
g2.drawString("Player 2", 367, 385);
g2.drawString("1", 70, 475);
g2.drawString("2", 120, 475);
g2.drawString("1", 370, 475);
g2.drawString("2", 420, 475);
}
}
Panagiotis Georgopanos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.