We are learning in school java graphic and now we have to build a game called Kakurasu (https://www.brainbashers.com/showkakurasu.asp)
I'm so stuck and I don't know how to do it.
As far as I came. I've done a frame with a panel inside a panel which has 7x7 buttons that change from 0 to 1 and from white to green when pressed. The idea is that I make the first raw on the top and on the left to be the numbers 1-5 and then on the bottom and right side the random generated numbers.
This is my first code:
import javax.swing.*;
import java.awt.*;
public class Start {
public static JButton[][] gumbi;
public static void main(String[] args) {
buttons = new JButton[7][7];
JFrame window = new JFrame("Kakurasu");
JPanel panel = new JPanel(new BorderLayout());
JPanel playingField = new JPanel(new GridLayout(7, 7));
Listner1 p = new Listner1(buttons);
panel.add(playingField, BorderLayout.CENTER);
window.add(panel);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
buttons[i][j] = new JButton("0");
playingField.add(buttons[i][j], BorderLayout.CENTER);
buttons[i][j].addActionListener(p);
buttons[i][j].setBackground(Color.WHITE);
}
}
window.setVisible(true);
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This is my second code:
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Poslusalec1 implements ActionListener {
public JButton[][] buttons;
public Listner1(JButton[][] gumbi) {
this.buttons = buttons;
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String tmp = button.getText();
int n = Integer.parseInt(tmp);
n += 1;
if (n == 2) {
n = 0;
}
button.setText("" + n);
if (button.getBackground() == Color.WHITE) {
button.setBackground(Color.GREEN);
} else {
button.setBackground(Color.WHITE);
}
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (button == buttons[i][j]) {
System.out.println(i + ", " + j);
}
}
}
}
}
Is it possible to assign different actionlisteners to different buttons inside a gridlayout?
Thanks for any help.
I'm so stuck and I don't know how to do it.
To solve any computer problem, you break the problem down into smaller and smaller problems, until you're comfortable that you can code each small problem.
Generally, when coding a GUI, you should use the model / view / controller pattern.
In Java Swing, this means:
The view may read values from the model.
The view may not update the model.
The controller updates the model.
The controller repaints / revalidates the view.
So, let's create a model for a JButton. The model will hold the across value of the JButton, the down value of the JButton, and the background color of the JButton.
package com.ggl.testing;
import java.awt.Color;
public class KakurasuCell {
private final int acrossValue;
private final int downValue;
private Color backgroundColor;
public KakurasuCell(int acrossValue, int downValue, Color backgroundColor) {
this.acrossValue = acrossValue;
this.downValue = downValue;
this.backgroundColor = backgroundColor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
public int getAcrossValue() {
return acrossValue;
}
public int getDownValue() {
return downValue;
}
}
This is a Java object. It holds multiple types of values.
Now, we create another model for a grid of JButtons. You should recognize this from your code.
package com.ggl.testing;
import java.awt.Color;
public class KakurasuGrid {
private int gridWidth;
private KakurasuCell[][] cells;
public KakurasuGrid(int gridWidth) {
setGridWidth(gridWidth);
}
public int getGridWidth() {
return gridWidth;
}
public void setGridWidth(int gridWidth) {
this.gridWidth = gridWidth;
this.cells = new KakurasuCell[gridWidth][gridWidth];
setCells();
}
public KakurasuCell[][] getCells() {
return cells;
}
private void setCells() {
for (int i = 0; i < gridWidth; i++) {
for (int j = 0; j < gridWidth; j++) {
KakurasuCell cell = new KakurasuCell((j + 1), (i + 1),
Color.GRAY);
cells[i][j] = cell;
}
}
}
}
This should be enough to get you started. You still need to create the answers, create the GUI, and add the controller methods.
Related
I am new to java and am very confused about errors in my code. I have the error at line 48 "local variables referenced from an inner class must be final or effectively final". here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MemoryGame extends JFrame
{
private JButton[][] buttons = new JButton[4][4];
private Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW};
private List<Color> colorList = new ArrayList<>();
private int score = 0;
public MemoryGame()
{
setTitle("Memory Game");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 4));
// populate colorList with two copies of each color
for (int i = 0; i < 2; i++)
{
for (Color color : colors)
{
colorList.add(color);
}
}
// shuffle colorList
Collections.shuffle(colorList);
int index = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
JButton button = new JButton();
button.setBackground(Color.GRAY);
buttons[i][j] = button;
add(button);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
final int currentIndex = index;
JButton clickedButton = (JButton) e.getSource();
Color color = colorList.get(currentIndex);
clickedButton.setBackground(color);
clickedButton.setEnabled(false);
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 4; y++)
{
if (buttons[x][y].getBackground() == color && buttons[x][y] != clickedButton)
{
buttons[x][y].setEnabled(false);
score++;
if (score == 8)
{
JOptionPane.showMessageDialog(MemoryGame.this, "You won!");
System.exit(0);
}
}
}
}
}
});
index++;
}
}
setVisible(true);
}
public static void main(String[] args)
{
new MemoryGame();
}
}
I've tried different things to solve the error and they just result in more errors. the program is meant to have a grid of different squares that can be clicked on to display their colors and matched by the user. when the user matches all of the colors on the grid they win.
The problem is with final int currentIndex = index; as the compiler was telling you in the error message. actionPerformed will run at some unspecified future time and the compiler has no idea what value of index you expect to find there at that time.
What do you want to do? Assign colors to buttons. You can do that more directly with
JButton button = new JButton();
button.setBackground(Color.GRAY);
buttons[i][j] = button;
// let's store the color for later
button.putClientProperty("color", colorList.get(index));
add(button);
outside the handler.
And then retrieving it inside:
public void actionPerformed(ActionEvent e)
{
JButton clickedButton = (JButton) e.getSource();
Color color = (Color)clickedButton.getClientProperty("color");
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;
}
}
}
}
};
So the situation is that I'm making a panel filled with 8*8 buttons, like a matrix, and I'm gonna have to change specific button texts depending on the position of the clicked button. It seemd like a good idea to make my own JButton where I can assign x and y indexes to the button, so I can check easily wich button was clicked by indexes.
Here is the code for that:
import javax.swing.JButton;
public class MatrixButton extends JButton {
private int x;
private int y;
public MatrixButton(int x, int y, String text){
super(text);
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
And it does solve the task, but these Matrix buttons doesn't want to appear until I mouse over them. What could be the problem?
here is the code for the panel wich contains these buttons and handles their actions:
public class PlayField extends JPanel implements ActionListener {
private MatrixButton[][] button = new MatrixButton[8][8];
public PlayField(){
Random rand = new Random();
setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; ++i){
for (int j = 0; j < 8; ++j){
button[i][j] = new MatrixButton(j, i, "" + rand.nextInt(80));
button[i][j].addActionListener(this);
add(button[i][j]);
}
}
}
private String incrementText(MatrixButton mb){
return "" + (Integer.parseInt(mb.getText()) + 1);
}
#Override
public void actionPerformed(ActionEvent e){
MatrixButton mb = (MatrixButton)e.getSource();
for (int i = mb.getY(); i >= 0; --i){
button[i][mb.getX()].setText(incrementText(button[i][mb.getX()]));
}
for (int i = 0; i < 8; ++i){
if (i != mb.getX())
button[mb.getY()][i].setText(incrementText(button[mb.getY()][i]));
}
}
}
PS: if I fill with ordinary JButtons they appear as they should be. Thats why I'm confused, cuz I didn't change much on the JButton extension just added 2 more variables to it.
This is dangerous code:
public int getX() {
return x;
}
public int getY() {
return y;
}
You do realize that this overrides two of JButton's critical methods (actually, the methods are from JButton's parent, JComponent) that help set the placement of the button on the GUI (add #Override above the methods to see that this is so). I strongly suggest that you either change the signature of these methods, perhaps getGridX() and getGridY(), or even better, use composition and not inheritance, since you run into risk of these types of problems -- unwittingly overriding a key method -- when you extend complex classes such as Swing component classes. For this reason I try to avoid extending these classes unless absolutely necessary.
For example:
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PlayField {
private static final int ROWS = 8;
private static final int COLS = ROWS;
private static final int MAX_RAND = 80;
private JPanel mainPanel = new JPanel();
private MatrixButton[][] button = new MatrixButton[ROWS][COLS];
public PlayField(){
Random rand = new Random();
mainPanel.setLayout(new GridLayout(ROWS, COLS));
for (int i = 0; i < ROWS; ++i){
for (int j = 0; j < COLS; ++j){
button[i][j] = new MatrixButton(j, i, rand.nextInt(MAX_RAND));
button[i][j].addActionListener(new MyMatrixListener(i, j));
mainPanel.add(button[i][j].getButton());
}
}
}
private class MyMatrixListener implements ActionListener {
private int i;
private int j;
public MyMatrixListener(int i, int j) {
this.i = i;
this.j = j;
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i2 = 0; i2 < button.length; i2++) {
if (i2 != i) {
int value = button[i2][j].getValue();
value++;
button[i2][j].setValue(value);
}
}
for (int j2 = 0; j2 < button[i].length; j2++) {
if (j2 != j) {
int value = button[i][j2].getValue();
value++;
button[i][j2].setValue(value);
}
}
}
}
public JPanel getMainPanel() {
return mainPanel;
}
private static void createAndShowGui() {
JFrame
frame = new JFrame("PlayField");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new PlayField().getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MatrixButton {
private int column;
private int row;
private JButton button = new JButton();
private int value;
public MatrixButton(int column, int row, int value) {
this.column = column;
this.row = row;
setValue(value);
}
public void addActionListener(ActionListener listener) {
button.addActionListener(listener);
}
public int getColumn() {
return column;
}
public int getRow() {
return row;
}
public JButton getButton() {
return button;
}
public int getValue() {
return value;
}
public final void setValue(int value) {
this.value = value;
button.setText("" + value);
}
}
Better to just use ints and not Strings
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);
}
I'm planning on making an editor for my current project and will need some java swing for it.
Basically I need a grid within some sort of frame; the single elements of the grid should be able to be selected via click and with a dropdown/selector element you should be able to change the color of the grid element
Can anyone tell me what parts of swing I'll need for that? Any help would be really appreciated ;)
Edit: let's go a bit into detail
This editor is planned to generate maps for an android strategy game I develope with some friends of mine
Let's say we have a square field of 16x16 fields which are all by default green.
By selecting the single field I want to be able to change the color of this field to something else.
In addition, every field should be able to return it's value (i.e. the color)
Your question is a little short on details, but perhaps you want a JPanel that uses GridLayout and holds an array of JLabels whose opaque property is true. You could add a MouseListener to the JLabels that shows a JPopupMenu that shows possible colors, and then depending on the selection use it to set the JLabel's background color (which shows since it has been made opaque).
For example:
Main.java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
private static void createAndShowGui() {
int rows = 20;
int cols = 40;
int cellWidth = 20;
ColorGrid mainPanel = new ColorGrid(rows, cols, cellWidth);
JFrame frame = new JFrame("Color Grid Example");
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();
}
});
}
}
ColorGrid.java
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class ColorGrid extends JPanel {
private MyColor[][] myColors;
private JLabel[][] myLabels;
public ColorGrid(int rows, int cols, int cellWidth) {
myColors = new MyColor[rows][cols];
myLabels = new JLabel[rows][cols];
MyMouseListener myListener = new MyMouseListener(this);
Dimension labelPrefSize = new Dimension(cellWidth, cellWidth);
setLayout(new GridLayout(rows, cols));
for (int row = 0; row < myLabels.length; row++) {
for (int col = 0; col < myLabels[row].length; col++) {
JLabel myLabel = new JLabel();
myLabel = new JLabel();
myLabel.setOpaque(true);
MyColor myColor = MyColor.GREEN;
myColors[row][col] = myColor;
myLabel.setBackground(myColor.getColor());
myLabel.addMouseListener(myListener);
myLabel.setPreferredSize(labelPrefSize);
add(myLabel);
myLabels[row][col] = myLabel;
}
}
}
public MyColor[][] getMyColors() {
return myColors;
}
public void labelPressed(JLabel label) {
for (int row = 0; row < myLabels.length; row++) {
for (int col = 0; col < myLabels[row].length; col++) {
if (label == myLabels[row][col]) {
MyColor myColor = myColors[row][col].next();
myColors[row][col] = myColor;
myLabels[row][col].setBackground(myColor.getColor());
}
}
}
}
}
MyColor.java
import java.awt.Color;
public enum MyColor {
GREEN(Color.green, "Green", "g"), RED(Color.red, "Red", "r"),
BLUE(Color.blue, "Blue", "b"), YELLOW(Color.yellow, "Yellow", "y");
private Color color;
private String name;
private String shortName;
private MyColor(Color color, String name, String shortName) {
this.color = color;
this.name = name;
this.shortName = shortName;
}
public MyColor next() {
int index = 0;
for (int i = 0; i < MyColor.values().length; i++) {
if (MyColor.values()[i] == this) {
index = (i + 1) % MyColor.values().length;
}
}
return MyColor.values()[index];
}
public Color getColor() {
return color;
}
public String getName() {
return name;
}
public String getShortName() {
return shortName;
}
#Override
public String toString() {
return shortName;
}
}
MyMouseListener.java
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class MyMouseListener extends MouseAdapter {
private ColorGrid colorGrid;
public MyMouseListener(ColorGrid colorGrid) {
this.colorGrid = colorGrid;
}
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
colorGrid.labelPressed((JLabel)e.getSource());
} else if (e.getButton() == MouseEvent.BUTTON3) {
MyColor[][] myColors = colorGrid.getMyColors();
for (int row = 0; row < myColors.length; row++) {
for (int col = 0; col < myColors[row].length; col++) {
System.out.print(myColors[row][col] + " ");
}
System.out.println();
}
System.out.println();
}
}
}