I used the code from Hovercraft Full Of Eels and manipulated it a little to get the numbering as I wanted. It looks good now and I can read the status but I can't figure out how to manipulate the individual checkboxes with my buttons on the form. Can someone help?
package and.lotto;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewLotto extends JPanel {
public static final int GRID_PANEL_ROWS = 3;
public static final int GRID_PANEL_COLS = 4;
public static final int PANELS = 12;
public static final int BOXES = 12;
private static final int GAP = 1;
private CheckBoxGrid[] checkBoxGrid = new CheckBoxGrid[PANELS];
public NewLotto() {
setLayout(new GridLayout(GRID_PANEL_ROWS, GRID_PANEL_COLS, GAP, GAP));
for (int rows = 0; rows < BOXES; rows++) {
checkBoxGrid[rows] = new CheckBoxGrid(rows,0);
add(checkBoxGrid[rows]);
}
}
private static void createAndShowGui() {
NewLotto mainPanel = new NewLotto();
ButtonPanel buttons = new ButtonPanel();
JFrame frame = new JFrame("Lotto");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(buttons,BorderLayout.NORTH);
frame.add(mainPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
JButton generate;
JButton clear;
private ActionListener actionListener = new MyButtonListener();
public ButtonPanel(){
generate = new JButton("Generate numbers");
generate.addActionListener(actionListener);
clear = new JButton("Clear All");
clear.addActionListener(actionListener);
add(generate);
add(clear);
}
private class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Testing");
}
}
}
#SuppressWarnings("serial")
class CheckBoxGrid extends JPanel {
private static final int CHECK_BOXES = 35;
private static final int CHECK_BOX_COLS = 6;
private static final int CHECK_BOX_ROWS = 6;
private static final int GAP = -5;
private JCheckBox[] checkBoxes = new JCheckBox[CHECK_BOXES];
private int gridIndex;
private ItemListener itemListener = new MyCheckBoxListener();
private int row;
private int col;
public CheckBoxGrid(int row, int col) {
this.row = row;
this.col = col;
gridIndex = row + col + 1;
setBorder(BorderFactory.createTitledBorder(String.valueOf(gridIndex)));
setLayout(new GridLayout(CHECK_BOX_ROWS, CHECK_BOX_COLS, GAP, GAP));
for (int cbRow = 0; cbRow < checkBoxes.length; cbRow++) {
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(itemListener);
add(checkBox);
checkBox.setRolloverEnabled(false);
checkBox.setRequestFocusEnabled(false);
checkBoxes[cbRow] = checkBox;
}
checkBoxes[0].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red01.png")));
checkBoxes[0].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red01sel.png")));
checkBoxes[1].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red02.png")));
checkBoxes[1].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red02sel.png")));
checkBoxes[2].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red03.png")));
checkBoxes[2].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red03sel.png")));
checkBoxes[3].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red04.png")));
checkBoxes[3].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red04sel.png")));
checkBoxes[4].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red05.png")));
checkBoxes[4].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red05sel.png")));
checkBoxes[5].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red06.png")));
checkBoxes[5].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red06sel.png")));
checkBoxes[6].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red07.png")));
checkBoxes[6].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red07sel.png")));
checkBoxes[7].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red08.png")));
checkBoxes[7].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red08sel.png")));
checkBoxes[8].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red09.png")));
checkBoxes[8].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red09sel.png")));
checkBoxes[9].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red10.png")));
checkBoxes[9].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red10sel.png")));
checkBoxes[10].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red11.png")));
checkBoxes[10].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red11sel.png")));
checkBoxes[11].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red12.png")));
checkBoxes[11].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red12sel.png")));
checkBoxes[12].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red13.png")));
checkBoxes[12].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red13sel.png")));
checkBoxes[13].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red14.png")));
checkBoxes[13].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red14sel.png")));
checkBoxes[14].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red15.png")));
checkBoxes[14].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red15sel.png")));
checkBoxes[15].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red16.png")));
checkBoxes[15].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red16sel.png")));
checkBoxes[16].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red17.png")));
checkBoxes[16].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red17sel.png")));
checkBoxes[17].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red18.png")));
checkBoxes[17].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red18sel.png")));
checkBoxes[18].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red19.png")));
checkBoxes[18].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red19sel.png")));
checkBoxes[19].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red20.png")));
checkBoxes[19].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red20sel.png")));
checkBoxes[20].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red21.png")));
checkBoxes[20].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red21sel.png")));
checkBoxes[21].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red22.png")));
checkBoxes[21].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red22sel.png")));
checkBoxes[22].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red23.png")));
checkBoxes[22].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red23sel.png")));
checkBoxes[23].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red24.png")));
checkBoxes[23].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red24sel.png")));
checkBoxes[24].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red25.png")));
checkBoxes[24].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red25sel.png")));
checkBoxes[25].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red26.png")));
checkBoxes[25].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red26sel.png")));
checkBoxes[26].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red27.png")));
checkBoxes[26].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red27sel.png")));
checkBoxes[27].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red28.png")));
checkBoxes[27].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red28sel.png")));
checkBoxes[28].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red29.png")));
checkBoxes[28].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red29sel.png")));
checkBoxes[29].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red30.png")));
checkBoxes[29].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red30sel.png")));
checkBoxes[30].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red31.png")));
checkBoxes[30].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red31sel.png")));
checkBoxes[31].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red32.png")));
checkBoxes[31].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red32sel.png")));
checkBoxes[32].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red33.png")));
checkBoxes[32].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red33sel.png")));
checkBoxes[33].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red34.png")));
checkBoxes[33].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red34sel.png")));
checkBoxes[34].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red35.png")));
checkBoxes[34].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red35sel.png")));
}
private class MyCheckBoxListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
JCheckBox source = (JCheckBox) itemEvt.getSource();
boolean selected = source.isSelected();
int cbRow = -1;
for (int r = 0; r < checkBoxes.length; r++) {
if (source.equals(checkBoxes[r])) {
cbRow = r;
}
}
String text = String.format("Grid %d, selected: %b, at %d",
(row + col + 1), selected, cbRow);
System.out.println(text);
}
}
}
Here is the original question:
I am trying to create a layout with an array of 12 JPanels each containing an array of 35 JCheckboxes. The problem I am having is that although the panels and checkboxes all display fine on the form, I have no way of accessing the properties of the individual checkboxes.
Here is part of the code I use:
JPanel panel_south = new JPanel();
contentPane.add(panel_south, BorderLayout.SOUTH);
panel_south.setLayout(new GridLayout(3, 4, 1, 1));
for(Integer i =0; i<12;i++){
Integer title = i+1;
EtchedBorder border = new EtchedBorder(EtchedBorder.LOWERED, null, null);
TitledBorder titled = new TitledBorder(border,title.toString());
row[i] = new JPanel();
row[i].setBorder(titled);
row[i].setLayout(new GridLayout(6, 6, -6, -5));
panel_south.add(row[i]);
JCheckBox[] rad = new JCheckBox[35];
for (int j = 0;j<35;j++){
rad[j] = new JCheckBox();
row[i].add(rad[j]);
}
When I try to use a line like this in the for loop:
row[i].rad[j].setSelected(true);
I get the error: rad cannot be resolved
What am I doing wrong here?
You should refactor out the JPanel that holds a grid of JTextFields, create a separate class for this, one that accepts a number for it's index, and that holds the JCheckBox grid or a JTable.
e.g.,
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class CheckBoxGridMain extends JPanel {
public static final int GRID_PANEL_ROWS = 3;
public static final int GRID_PANEL_COLS = 4;
private static final int GAP = 1;
private CheckBoxGrid[][] checkBoxGrid = new CheckBoxGrid[GRID_PANEL_ROWS][GRID_PANEL_COLS];
public CheckBoxGridMain() {
setLayout(new GridLayout(GRID_PANEL_ROWS, GRID_PANEL_COLS, GAP, GAP));
for (int row = 0; row < checkBoxGrid.length; row++) {
for (int col = 0; col < checkBoxGrid[row].length; col++) {
checkBoxGrid[row][col] = new CheckBoxGrid(row, col);
add(checkBoxGrid[row][col]);
}
}
}
private static void createAndShowGui() {
CheckBoxGridMain mainPanel = new CheckBoxGridMain();
JFrame frame = new JFrame("CheckBox Grid");
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();
}
});
}
}
#SuppressWarnings("serial")
class CheckBoxGrid extends JPanel {
private static final int CHECK_BOX_ROWS = 6;
private static final int CHECK_BOX_COLS = 6;
private static final int GAP = -5;
private JCheckBox[][] checkBoxes = new JCheckBox[CHECK_BOX_ROWS][CHECK_BOX_COLS];
private int gridIndex;
private ItemListener itemListener = new MyCheckBoxListener();
private int row;
private int col;
public CheckBoxGrid(int row, int col) {
this.row = row;
this.col = col;
gridIndex = row + col + 1;
setBorder(BorderFactory.createTitledBorder(String.valueOf(gridIndex)));
setLayout(new GridLayout(CHECK_BOX_ROWS, CHECK_BOX_COLS, GAP, GAP));
for (int cbRow = 0; cbRow < checkBoxes.length; cbRow++) {
for (int cbCol = 0; cbCol < checkBoxes[cbRow].length; cbCol++) {
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(itemListener);
add(checkBox);
checkBoxes[cbRow][cbCol] = checkBox;
}
}
}
private class MyCheckBoxListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
JCheckBox source = (JCheckBox) itemEvt.getSource();
boolean selected = source.isSelected();
int cbRow = -1;
int cbCol = -1;
for (int r = 0; r < checkBoxes.length; r++) {
for (int c = 0; c < checkBoxes[r].length; c++) {
if (source.equals(checkBoxes[r][c])) {
cbRow = r;
cbCol = c;
}
}
}
String text = String.format("Grid %d, selected: %b, at [%d, %d]",
(row + col + 1), selected, cbCol, cbRow); // corrected row/col order
System.out.println(text);
}
}
}
Which displays
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've been trying to follow an MVC pattern on my code and I was creating a system in which I have a JTabbedPane with Jbuttons inside the panel on my View, The content's info in the Model, and a the actionlisteners on my Controller.
The problem I've been having is that I've been trying to put an actionlistener on my Jbuttons but it seems to be only working on my last tab (let's say i have 4 tabs, only the 4th tab with jbuttons work)
Oh, and I should say that I've been using Jbutton arrays
Note that I've been only using only one Jbutton array to place on my panel.
how should this work? I need a sample code for reference.
here is my sample View class
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class View extends JFrame
{
private static final int HEIGHT = 700;
private static final int WIDTH = 700;
private JTabbedPane tabPane = new JTabbedPane();
private JComponent tab1 = makePanel("1");
private JComponent tab2 = makePanel("2");
private JComponent tab3 = makePanel("3");
private JComponent tab4 = makePanel("4");
private JButton[] button;
private String[] buttonlabel;
public View()
{
setLayout(null);
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setResizable(false);
setVisible(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
tabPane.addTab("firstTab", tab1);
tabPane.addTab("secondTab", tab2);
tabPane.addTab("thirdTab", tab3);
tabPane.addTab("fourtTab", tab4);
add(tabPane);
tabPane.setBounds(20, 20, 400, 400);
}
protected JComponent makePanel(String input)
{
JPanel panel = new JPanel(false);
panel.setLayout(null);
if(input == "1")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button1",
"2button1",
"3button1",
"4button1"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2); y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
else if(input == "2")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button2",
"2button2",
"3button2",
"4button2"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2) && y < 5; y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
else if(input == "3")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button3",
"2button3",
"3button3",
"4button3"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2) && y < 5; y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
else if(input == "4")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button4",
"2button4",
"3button4",
"4button4"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2) && y < 5; y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
return panel;
}
public void buttonListener(ActionListener buttonL)
{
for(int x = 0; x < button.length; x++)
{
button[x].addActionListener(buttonL);
}
}
public static void main(String args[])
{
View view = new View();
Controller control = new Controller(view);
view.setVisible(true);
}
}
here is my sample Controller class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller
{
View view = new View();
public Controller(View view)
{
this.view = view;
this.view.buttonListener(new ButtonListener());
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("BUTTON WORKS!");
}
}
}
You're re-filling the button array with each creation of a JTabbedPane, and in doing so, the references for all the previous buttons have been discarded from the array and only the last remains.
I suggest that you create a class for the panel of the JTabbedPane and allow it to be injected from the control. Keep it simple.
One example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class View2 extends JPanel {
private static final long serialVersionUID = 1L;
private static final String[] TAB_NAMES = {"First Tab", "Second Tab", "Third Tab", "Fourth Tab"};
private static final int PREF_W = 400;
private static final int PREF_H = 150;
private JTabbedPane tabbedPane = new JTabbedPane();
private List<MyTab> myTabs = new ArrayList<>();
private Controller2 controller2;
public View2() {
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(tabbedPane, BorderLayout.CENTER);
for (int i = 0; i < TAB_NAMES.length; i++) {
int tabNumber = i + 1;
MyTab myTab = new MyTab(TAB_NAMES[i], tabNumber);
tabbedPane.add(myTab.getTabName(), myTab);
myTabs.add(myTab);
}
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
public Controller2 getController2() {
return controller2;
}
public void setController2(Controller2 controller2) {
this.controller2 = controller2;
for (MyTab myTab : myTabs) {
myTab.setController2(controller2);
}
}
private static void createAndShowGui() {
View2 viewPanel = new View2();
new Controller2(viewPanel);
JFrame frame = new JFrame("View2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(viewPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyTab extends JPanel {
private static final long serialVersionUID = 1L;
private static final int BUTTON_COUNT = 4;
private String tabName;
private int tabNumber;
private List<JButton> buttons = new ArrayList<>();
private Controller2 controller2;
public MyTab(String tabName, int tabNumber) {
this.tabName = tabName;
this.tabNumber = tabNumber;
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new GridLayout(2, 2, 4, 4));
for (int i = 0; i < BUTTON_COUNT; i++) {
String title = (i + 1) + " Button " + tabNumber;
JButton button = new JButton(title);
button.addActionListener(e -> {
if (controller2 != null) {
controller2.buttonAction(e);
}
});
add(button);
buttons.add(button);
}
}
public void setController2(Controller2 controller2) {
this.controller2 = controller2;
}
public String getTabName() {
return tabName;
}
public int getTabNumber() {
return tabNumber;
}
public List<JButton> getButtons() {
return buttons;
}
}
class Controller2 {
private View2 view;
public Controller2(View2 view) {
this.view = view;
view.setController2(this);
}
public void buttonAction(ActionEvent e) {
System.out.println("Button pressed! " + e.getActionCommand());
}
public View2 getView() {
return view;
}
}
This example uses a simple anonymous inner class ActionListener in the view to call a controller method.
I have two classes 'UserInterface' and a 'GameEngine' I have declared a JButton component in the UserInterface and I am trying to use one of the variables i.e use the variable 'button1' from 'UserInterface' in the 'horizontalWin' method from the class 'GameEngine'.
I got this error instead "cannot find symbol - variable button1"
Userinterface:
public class UserInterface implements ActionListener
{
private GameEngine game;
private JFrame frame;
JButton button1 = new JButton("");
JButton button2 = new JButton("");
JButton button3 = new JButton("");
JButton button4 = new JButton("");
JButton button5 = new JButton("");
JButton button6 = new JButton("");
JButton button7 = new JButton("");
JButton button8 = new JButton("");
JButton button9 = new JButton("");
/**
* Create a user interface.
* #param engine The game's engine.
*/
public UserInterface(GameEngine engine)
{
game = engine;
makeFrame();
}
//some methods
}
GameEngine:
public class GameEngine {
private String buttonName;
boolean winner = false;
byte count;
public GameEngine()
{
count = 0;
}
public void horizontalWin()
{
if(button1.getText()==button2.getText() && button2.getText()==button3.getText() && button1.getText()!="" )
{
winner=true;
playAgain(buttonName);
}
// Horizontal win row 2
else if(button4.getText()==button5.getText() && button5.getText()==button6.getText() && button4.getText()!="" )
{
winner=true;
playAgain(buttonName);
}
// horizontal win row 3
else if(button7.getText()==button8.getText() && button8.getText()==button9.getText() && button7.getText()!="")
{
winner=true;
playAgain(buttonName);
}
}
I think that you don't really want to do this, that you don't want your game engine trying to obtain variables from the view. Rather why not have your view notify the engine or "model" (usually through something called a "control", when a button has been pressed. The engine then can keep track of what has been pressed and change its state accordingly. The View can then change in response to changes in the engine's state.
For example:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class TicTacToe {
private static void createAndShowGui() {
View mainPanel = new View();
JFrame frame = new JFrame("TicTacToe");
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();
}
});
}
}
#SuppressWarnings("serial")
class View extends JPanel {
private static final int GAP = 2;
private static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 42);
private JButton[][] gameGrid = new JButton[Engine.ROWS][Engine.ROWS];
private Engine engine = new Engine();
public View() {
engine.addPropertyChangeListener(Engine.GAME_OVER, new GameOverListener());
JPanel gameGridPanel = new JPanel(new GridLayout(Engine.ROWS, Engine.ROWS, GAP, GAP));
for (int i = 0; i < gameGrid.length; i++) {
for (int j = 0; j < gameGrid[i].length; j++) {
gameGrid[i][j] = createGameGridButton(i, j);
gameGridPanel.add(gameGrid[i][j]);
}
}
JButton resetBtn = new JButton(new ResetAction("Reset", KeyEvent.VK_R));
JPanel northPanel = new JPanel();
northPanel.add(resetBtn);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(gameGridPanel, BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
}
private JButton createGameGridButton(int i, int j) {
JButton button = new JButton();
button.setName(String.format("%d,%d", i, j));
button.setText(XO.BLANK.getText());
button.setFont(BTN_FONT);
button.addActionListener(new GridButtonListener(i, j));
return button;
}
private class GridButtonListener implements ActionListener {
private int i;
private int j;
public GridButtonListener(int i, int j) {
this.i = i;
this.j = j;
}
#Override
public void actionPerformed(ActionEvent e) {
if (engine.isGameOver()) {
return;
}
AbstractButton source = (AbstractButton) e.getSource();
String text = source.getText();
if (text.trim().isEmpty()) {
source.setText(engine.getTurn().getText());
engine.setXO(i, j);
}
}
}
private class ResetAction extends AbstractAction {
public ResetAction(String text, int mnemonic) {
super(text);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
engine.reset();
for (JButton[] row : gameGrid) {
for (JButton button : row) {
button.setText(XO.BLANK.getText());
}
}
};
}
private class GameOverListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
JOptionPane.showMessageDialog(View.this, engine.getTurn()
.getText() + " is a winner!", "We Have a Winner!",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
class Engine {
public static final int ROWS = 3;
public static final String GAME_OVER = "game over";
private XO[][] grid = new XO[ROWS][ROWS];
private XO turn = XO.X;
private boolean gameOver = false;
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
this);
public Engine() {
reset();
}
public XO getTurn() {
return turn;
}
public boolean isGameOver() {
return gameOver;
}
public void setXO(int row, int col) {
grid[row][col] = turn;
checkForWin(row, col);
turn = (turn == XO.X) ? XO.O : XO.X;
}
public void reset() {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
grid[r][c] = XO.BLANK;
}
}
turn = XO.X;
gameOver = false;
}
public void checkForWin(int i, int j) {
boolean win = true;
for (int col = 0; col < grid.length; col++) {
if (grid[col][j] != turn) {
win = false;
}
}
if (!win) {
win = true;
for (int row = 0; row < grid[i].length; row++) {
if (grid[i][row] != turn) {
win = false;
}
}
}
if (!win && i == j) {
win = true;
for (int k = 0; k < grid.length; k++) {
if (grid[k][k] != turn) {
win = false;
}
}
}
if (!win && i + j == 2) {
win = true;
for (int k = 0; k < grid.length; k++) {
if (grid[k][2 - k] != turn) {
win = false;
}
}
}
if (win) {
setGameOver(true);
}
}
private void setGameOver(boolean gameOver) {
boolean oldValue = this.gameOver;
boolean newValue = gameOver;
this.gameOver = gameOver;
pcSupport.firePropertyChange(GAME_OVER, oldValue, newValue);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
public void addPropertyChangeListener(String name,
PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(name, listener);
}
public void removePropertyChangeListener(String name,
PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(name, listener);
}
}
enum XO {
X("X"), O("O"), BLANK(" ");
private String text;
private XO(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
My view's ActionListener (here an AbstractAction) notifies the Engine that a certain button has been pushed. The Engine keeps track of which button has been pushed, and when a winner has been determined, sets a gameOver field thereby notifying all listeners that the game is over.
When I set X and Y values for my array of JButtons, I get back the correct values only multiplied by 93. I can solve the problem by dividing the value by 93 but I would rather find out where the bug was in the first place.
I have two classes in the code, one for the actual program, and one for the button object along with the coordinates.
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import java.io.*;
public class ConnectFour implements ActionListener
{
JFrame frame = new JFrame();
Button [][] buttons = new Button[6][7];
public ConnectFour()
{
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(6,7));
frame.setLocationRelativeTo(null);
frame.setTitle("Connect Four");
for(int filler = 0; filler <= 5; filler++)
{
for(int filler2 = 0; filler2 <= 6; filler2++)
{
buttons[filler][filler2] = new Button();
buttons[filler][filler2].setX(filler2);
buttons[filler][filler2].setY(filler);
//System.out.println(buttons[filler][filler2].getX());
//System.out.print(buttons[filler][filler2].getY());
frame.add(buttons[filler][filler2].button);
buttons[filler][filler2].button.addActionListener(this);
}
}
frame.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
JButton pressedButton = (JButton)a.getSource();
System.out.print(pressedButton.getY() / 93);
System.out.print(pressedButton.getX() / 93);
}
public static void main(String args[])
{
ConnectFour gameplay = new ConnectFour();
}
}
Here's the Button class:
import javax.swing.JButton;
public class Button
{
JButton button;
private int x = 0;
private int y = 0;
public Button()
{
button = new JButton();
}
public int getX() {return x;}
public int getY() {return y;}
public void setX(int xIndex)
{
x = xIndex;
}
public void setY(int yIndex)
{
y = yIndex;
}
}
You're mixing your two Button classes.
In this line, you're adding an actionListener to Button.button:
buttons[filler][filler2].button.addActionListener(this);
because JButton also has methods getX and getY, you can call them. When you do:
pressedButton.getX()
you're getting the x position of the JButton, not of your Button.
What I think would be the easiest way to solve this problem is making your button extend JButton and rename x and y to row and column, for instance:
public class Button extends JButton {
private int row = 0;
private int column = 0;
public Button(int row, int column) {
super();
this.row = row;
this.column = column;
}
public int getRow() {return row;}
public int getColumn() {return column;}
}
You can create you buttons as
for(int filler = 0; filler <= 5; filler++) {
for(int filler2 = 0; filler2 <= 6; filler2++) {
buttons[filler][filler2] = new Button(filler2, filler);
frame.add(buttons[filler][filler2]);
buttons[filler][filler2].addActionListener(this);
}
}
And use them in the ActionListener as
public void actionPerformed(ActionEvent a) {
Button pressedButton = (Button)a.getSource();
System.out.print(pressedButton.getColumn());
System.out.print(pressedButton.getRow());
}
I could not figure how to do it using your composition example, but this one works as you might want.
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import java.io.*;
public class ConnectFour implements ActionListener
{
JFrame frame = new JFrame();
CustomButton [][] buttons = new CustomButton[6][7];
public ConnectFour()
{
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(6,7));
frame.setLocationRelativeTo(null);
frame.setTitle("Connect Four");
for(int filler = 0; filler <= 5; filler++)
{
for(int filler2 = 0; filler2 <= 6; filler2++)
{
buttons[filler][filler2] = new CustomButton(filler,filler2);
frame.add(buttons[filler][filler2]);
buttons[filler][filler2].addActionListener(this);
}
}
frame.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
CustomButton pressedButton = (CustomButton)a.getSource();
System.out.println(pressedButton.getRow() + "/" + pressedButton.getCol());
}
public static void main(String args[])
{
ConnectFour gameplay = new ConnectFour();
}
}
class CustomButton extends JButton
{
private int row = 0;
private int col = 0;
public CustomButton(int row, int col)
{
this.row = row;
this.col = col;
}
public int getRow() {return row;}
public int getCol() {return col;}
public void setRow(int row)
{
this.row = row;
}
public void setCol(int col)
{
this.col = col;
}
}
I think x and y are defined in the superclass, try changing the variable names to something else. e.g.
private int myX = 0;
private int myY = 0;
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();
}
}
}