Transform my Java Swing program to an MVC program? - java

I was given the task to come up with a small game in Swing and implement it as an MVC (Model View Control) program. I'm new to MVC. So far I've finished the whole program in 1 Java file (View), what code do I need to change and insert in the Model file, in order for it to become MVC?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public class MemoryGameView extends JFrame {
private JPanel gamePanel, settingsPanel, scorePanel;
private JButton[] button = new JButton[16];
private JButton start;
private JPanel buttonPanel, buttonPanel2;
private JPanel difficultyPanel, difficultyPanel2;
private JLabel difficultyLabel;
private ButtonGroup difficultyButtonGroup;
private JRadioButton[] difficultyButton = new JRadioButton[4];
private int difficulty = 0;
private JComboBox guiColorChanger;
private String[] guiColor = new String[2];
private JPanel guiColorChangerPanel;
private JLabel guiColorChangerLabel;
private JPanel currentScorePanel, currentScorePanel2, highScorePanel, highScorePanel2;
private JLabel currentScoreLabel, currentScoreLabel2, highScoreLabel, highScoreLabel2;
private int currentScore;
private int highScore = 0;
private int[] arrayAuto;
private int[] arrayUser;
private int counter;
private Timer timer;
private Color babyBlue = new Color(137, 156, 240);
private Color brightRed = new Color(255, 69, 0);
private Color limeGreen = new Color(50, 205, 50);
private Color whiteBlue = new Color(240, 240, 255);
private Color blackBlue = new Color(0, 0, 15);
public MemoryGameView() {
super();
init();
}
public void init() {
setTitle("Memory Game - by Marc");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1200, 500);
setLocationRelativeTo(null);
setLayout(new GridLayout(1, 3));
settingsPanel = new JPanel(new BorderLayout());
gamePanel = new JPanel(new GridBagLayout());
scorePanel = new JPanel(new BorderLayout());
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
add(settingsPanel);
add(gamePanel);
add(scorePanel);
//GAME PANEL (CENTER) -----------------------------------------------------------------------------------------------------
//GAME GRID PANEL:
buttonPanel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton();
button[x].setBackground(babyBlue);
button[x].setEnabled(false);
button[x].addActionListener(new AttemptMemoryGame());
button[x].setActionCommand(x + "");
buttonPanel.add(button[x]);
}
buttonPanel2 = new JPanel();
buttonPanel2.setBackground(Color.WHITE);
buttonPanel2.setPreferredSize(new Dimension(320, 320));
buttonPanel.setPreferredSize(new Dimension(312, 312));
buttonPanel2.add(buttonPanel);
GridBagConstraints buttonGBC = new GridBagConstraints();
buttonGBC.gridy = 0;
buttonGBC.insets = new Insets(10, 10, 0, 10);
gamePanel.add(buttonPanel2, buttonGBC);
//START BUTTON:
start = new JButton("START");
start.setBackground(Color.ORANGE);
start.setPreferredSize(new Dimension(200, 40));
GridBagConstraints startGBC = new GridBagConstraints();
startGBC.gridy = 1;
startGBC.insets.top = 20;
startGBC.insets.bottom = 20;
gamePanel.add(start, startGBC);
start.addActionListener(new CreateMemoryGame());
timer = new Timer(750, new TimerListener());
//SETTINGS PANEL (LEFT) ----------------------------------------------------------------------------------------------
//GUI COLOR PANEL:
guiColor[0] = "Light";
guiColor[1] = "Dark";
guiColorChangerPanel = new JPanel(new GridBagLayout());
guiColorChangerPanel.setBackground(whiteBlue);
settingsPanel.add(guiColorChangerPanel, BorderLayout.NORTH);
guiColorChanger = new JComboBox(guiColor);
guiColorChanger.setBackground(Color.WHITE);
guiColorChanger.setPreferredSize(new Dimension(200, 30));
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints guiColorChangerGBC = new GridBagConstraints();
guiColorChangerGBC.gridy = 1;
guiColorChangerGBC.insets = new Insets(0, 20, 0, 50);
guiColorChangerGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChanger, guiColorChangerGBC);
guiColorChangerLabel = new JLabel("GUI Color Mode:");
GridBagConstraints guiColorChangerLabelGBC = new GridBagConstraints();
guiColorChangerLabelGBC.gridy = 0;
guiColorChangerLabelGBC.insets = new Insets(30, 20, 5, 0);
guiColorChangerLabelGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChangerLabel, guiColorChangerLabelGBC);
guiColorChanger.addActionListener(new ChangeColorsGUI());
guiColorChanger.setFocusable(false);
//GAME DIFFICULTY PANEL:
difficultyPanel2 = new JPanel(new GridBagLayout());
difficultyPanel2.setBackground(whiteBlue);
settingsPanel.add(difficultyPanel2, BorderLayout.SOUTH);
difficultyLabel = new JLabel("Difficulty:");
GridBagConstraints difficultyLabelGBC = new GridBagConstraints();
difficultyLabelGBC.gridy = 0;
difficultyLabelGBC.insets = new Insets(30, 0, 5, 50);
difficultyLabelGBC.anchor = GridBagConstraints.WEST;
difficultyPanel2.add(difficultyLabel, difficultyLabelGBC);
difficultyPanel = new JPanel(new GridBagLayout());
difficultyPanel.setBackground(Color.WHITE);
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints difficultyPanelGBC = new GridBagConstraints();
difficultyPanelGBC.gridy = 1;
difficultyPanelGBC.insets = new Insets(0, 0, 75, 100);
difficultyPanel2.add(difficultyPanel, difficultyPanelGBC);
GridBagConstraints difficultyGBC = new GridBagConstraints();
difficultyGBC.insets = new Insets(5, 5, 5, 5);
difficultyGBC.anchor = GridBagConstraints.WEST;
difficultyButton[0] = new JRadioButton("Easy [3]");
difficultyButton[1] = new JRadioButton("Normal [5]");
difficultyButton[2] = new JRadioButton("Hard [7]");
difficultyButton[3] = new JRadioButton("Impossible [9]");
difficultyButtonGroup = new ButtonGroup();
for (int x = 0; x < 4; x++) {
difficultyButton[x].setBackground(Color.WHITE);
difficultyButton[x].setActionCommand(x + "");
difficultyGBC.gridy = x;
difficultyPanel.add(difficultyButton[x], difficultyGBC);
difficultyButtonGroup.add(difficultyButton[x]);
difficultyButton[x].addActionListener(new SelectDifficulty());
}
//SCORE PANEL (RIGHT) --------------------------------------------------------------------------------------------------------
//CURRENT SCORE:
currentScorePanel2 = new JPanel(new GridBagLayout());
currentScorePanel2.setBackground(whiteBlue);
scorePanel.add(currentScorePanel2, BorderLayout.NORTH);
currentScoreLabel2 = new JLabel("Score: ");
GridBagConstraints currentScoreLabelGBC = new GridBagConstraints();
currentScoreLabelGBC.gridx = 0;
currentScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
currentScoreLabelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScoreLabel2, currentScoreLabelGBC);
currentScorePanel = new JPanel(new GridBagLayout());
currentScorePanel.setBackground(Color.WHITE);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints currentScorePanelGBC = new GridBagConstraints();
currentScorePanelGBC.insets = new Insets(100, 0, 100, 100);
currentScorePanelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScorePanel, currentScorePanelGBC);
currentScoreLabel = new JLabel(" ");
currentScoreLabelGBC.gridx = 1;
currentScorePanel.add(currentScoreLabel, currentScoreLabelGBC);
//HIGHSCORE:
highScorePanel2 = new JPanel(new GridBagLayout());
highScorePanel2.setBackground(whiteBlue);
scorePanel.add(highScorePanel2, BorderLayout.SOUTH);
highScoreLabel2 = new JLabel("Highscore: ");
GridBagConstraints highScoreLabelGBC = new GridBagConstraints();
highScoreLabelGBC.gridx = 0;
highScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
highScoreLabelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScoreLabel2, highScoreLabelGBC);
highScorePanel = new JPanel(new GridBagLayout());
highScorePanel.setBackground(Color.WHITE);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints highScorePanelGBC = new GridBagConstraints();
highScorePanelGBC.insets = new Insets(100, 0, 100, 100);
highScorePanelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScorePanel, highScorePanelGBC);
highScoreLabel = new JLabel(" ");
highScoreLabelGBC.gridx = 1;
highScorePanel.add(highScoreLabel, highScoreLabelGBC);
pack();
setVisible(true);
}
public class CreateMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (difficulty != 0) {
counter = 0;
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(false);
}
for (JButton b: button) {
b.setBackground(babyBlue);
b.setEnabled(false);
}
start.setEnabled(false);
arrayAuto = new int[difficulty];
arrayAuto[0] = (int)(Math.random() * 16);
for (int x = 1; x < difficulty; x++) {
arrayAuto[x] = (int)(Math.random() * 16);
while (arrayAuto[x] == arrayAuto[x - 1]) {
arrayAuto[x] = (int)(Math.random() * 16);
}
}
arrayUser = Arrays.copyOf(arrayAuto, arrayAuto.length);
button[arrayAuto[0]].setBackground(limeGreen);
timer.start();
} else {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(null, "Please select a Difficulty.", "ERROR", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
}
}
}
public class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
button[arrayAuto[0]].setBackground(babyBlue);
arrayAuto = Arrays.copyOfRange(arrayAuto, 1, arrayAuto.length);
if (arrayAuto.length == 0) {
timer.stop();
for (JButton b: button) {
b.setEnabled(true);
}
} else {
button[arrayAuto[0]].setBackground(limeGreen);
}
}
}
public class AttemptMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (Integer.parseInt(ae.getActionCommand()) == arrayUser[counter]) {
if (counter != 0) {
button[arrayUser[counter - 1]].setBackground(babyBlue);
}
button[arrayUser[counter]].setBackground(limeGreen);
counter++;
currentScore += difficulty;
currentScoreLabel.setText(" " + currentScore + " ");
} else {
if (currentScore > highScore) {
highScore = currentScore;
highScoreLabel.setText(" " + highScore + " ");
}
currentScore = 0;
currentScoreLabel.setText(" ");
for (int x = 0; x < difficulty; x++) {
button[arrayUser[x]].setBackground(brightRed);
}
start.setEnabled(true);
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
for (JButton b: button) {
b.setEnabled(false);
}
}
if (counter == arrayUser.length) {
start.setEnabled(true);
for (int x = 0; x < counter - 1; x++) {
button[arrayUser[x]].setBackground(limeGreen);
}
for (JButton b: button) {
b.setEnabled(false);
}
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
}
}
}
public class SelectDifficulty implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(0 + "")) {
difficulty = 3;
} else if (ae.getActionCommand().equals(2 + "")) {
difficulty = 7;
} else if (ae.getActionCommand().equals(3 + "")) {
difficulty = 9;
} else {
difficulty = 5;
}
}
}
public class ChangeColorsGUI implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (guiColorChanger.getSelectedItem() == guiColor[0]) {
guiColorChanger.setBackground(Color.WHITE);
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
buttonPanel.setBackground(Color.WHITE);
guiColorChangerPanel.setBackground(whiteBlue);
buttonPanel2.setBackground(Color.WHITE);
guiColorChanger.setForeground(Color.BLACK);
guiColorChangerLabel.setForeground(Color.BLACK);
difficultyPanel.setBackground(Color.WHITE);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.WHITE);
rb.setForeground(Color.BLACK);
}
difficultyLabel.setBackground(whiteBlue);
difficultyLabel.setForeground(Color.BLACK);
difficultyPanel2.setBackground(whiteBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scorePanel.setBackground(whiteBlue);
currentScoreLabel.setBackground(Color.WHITE);
currentScoreLabel.setForeground(Color.BLACK);
currentScoreLabel2.setForeground(Color.BLACK);
currentScorePanel.setBackground(whiteBlue);
currentScorePanel2.setBackground(whiteBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
highScoreLabel.setBackground(Color.WHITE);
highScoreLabel.setForeground(Color.BLACK);
highScoreLabel2.setForeground(Color.BLACK);
highScorePanel.setBackground(whiteBlue);
highScorePanel2.setBackground(whiteBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
guiColorChanger.setBackground(Color.BLACK);
settingsPanel.setBackground(blackBlue);
gamePanel.setBackground(Color.BLACK);
scorePanel.setBackground(blackBlue);
buttonPanel.setBackground(Color.BLACK);
guiColorChangerPanel.setBackground(blackBlue);
buttonPanel2.setBackground(Color.BLACK);
guiColorChanger.setForeground(Color.WHITE);
guiColorChangerLabel.setForeground(Color.WHITE);
difficultyPanel.setBackground(Color.BLACK);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.BLACK);
rb.setForeground(Color.WHITE);
}
difficultyLabel.setBackground(blackBlue);
difficultyLabel.setForeground(Color.WHITE);
difficultyPanel2.setBackground(blackBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.WHITE));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
scorePanel.setBackground(blackBlue);
currentScoreLabel.setBackground(Color.BLACK);
currentScoreLabel.setForeground(Color.WHITE);
currentScoreLabel2.setForeground(Color.WHITE);
currentScorePanel.setBackground(blackBlue);
currentScorePanel2.setBackground(blackBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
highScoreLabel.setBackground(Color.BLACK);
highScoreLabel.setForeground(Color.WHITE);
highScoreLabel2.setForeground(Color.WHITE);
highScorePanel.setBackground(blackBlue);
highScorePanel2.setBackground(blackBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
}
}
}
public static void main(String[] args) {
new MemoryGameView();
}
}
I really appreciate any help! (#camickr? :D)
Edit: I only need to do the files Model and View, no Controller needed.

Here is something to get you started. Define a a Model class that holds the information and logic the View needs.
In this simple demo I implemented a model that has only one attribute the View needs namely difficulty :
class Model{
private int difficulty = 0; //why not set a default value ?
Model(){
}
int getDifficulty() {
return difficulty;
}
void setDifficulty(int difficulty) {
this.difficulty = difficulty;
}
}
Now introduce a View class which is almost identical to MemoryGameView with one important difference: it has an instance of Model and uses it.
(Another difference is a design preference and not a must: unlike MemoryGameView it has a JFrame and it does not extend one.):
class View {
private JPanel gamePanel, settingsPanel, scorePanel;
private final JButton[] button = new JButton[16];
private JButton start;
private JPanel buttonPanel, buttonPanel2;
private JPanel difficultyPanel, difficultyPanel2;
private JLabel difficultyLabel;
private ButtonGroup difficultyButtonGroup;
private final JRadioButton[] difficultyButton = new JRadioButton[4];
private JComboBox guiColorChanger;
private final String[] guiColor = new String[2];
private JPanel guiColorChangerPanel;
private JLabel guiColorChangerLabel;
private JPanel currentScorePanel, currentScorePanel2, highScorePanel, highScorePanel2;
private JLabel currentScoreLabel, currentScoreLabel2, highScoreLabel, highScoreLabel2;
private int currentScore;
private int highScore = 0;
private int[] arrayAuto,arrayUser;
private int counter;
private Timer timer;
private final Color babyBlue = new Color(137, 156, 240);
private final Color brightRed = new Color(255, 69, 0);
private final Color limeGreen = new Color(50, 205, 50);
private final Color whiteBlue = new Color(240, 240, 255);
private final Color blackBlue = new Color(0, 0, 15);
private final Model model;
public View(Model model) {
this.model = model;
init();
}
public void init() {
JFrame frame = new JFrame("Memory Game - by Marc");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200, 500);
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(1, 3));
settingsPanel = new JPanel(new BorderLayout());
gamePanel = new JPanel(new GridBagLayout());
scorePanel = new JPanel(new BorderLayout());
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
frame.add(settingsPanel);
frame.add(gamePanel);
frame.add(scorePanel);
//GAME PANEL (CENTER) -----------------------------------------------------------------------------------------------------
//GAME GRID PANEL:
buttonPanel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int x = 0; x < 16; x++) {
button[x] = new JButton();
button[x].setBackground(babyBlue);
button[x].setEnabled(false);
button[x].addActionListener(new AttemptMemoryGame());
button[x].setActionCommand(x + "");
buttonPanel.add(button[x]);
}
buttonPanel2 = new JPanel();
buttonPanel2.setBackground(Color.WHITE);
buttonPanel2.setPreferredSize(new Dimension(320, 320));
buttonPanel.setPreferredSize(new Dimension(312, 312));
buttonPanel2.add(buttonPanel);
GridBagConstraints buttonGBC = new GridBagConstraints();
buttonGBC.gridy = 0;
buttonGBC.insets = new Insets(10, 10, 0, 10);
gamePanel.add(buttonPanel2, buttonGBC);
//START BUTTON:
start = new JButton("START");
start.setBackground(Color.ORANGE);
start.setPreferredSize(new Dimension(200, 40));
GridBagConstraints startGBC = new GridBagConstraints();
startGBC.gridy = 1;
startGBC.insets.top = 20;
startGBC.insets.bottom = 20;
gamePanel.add(start, startGBC);
start.addActionListener(new CreateMemoryGame());
timer = new Timer(750, new TimerListener());
//SETTINGS PANEL (LEFT) ----------------------------------------------------------------------------------------------
//GUI COLOR PANEL:
guiColor[0] = "Light";
guiColor[1] = "Dark";
guiColorChangerPanel = new JPanel(new GridBagLayout());
guiColorChangerPanel.setBackground(whiteBlue);
settingsPanel.add(guiColorChangerPanel, BorderLayout.NORTH);
guiColorChanger = new JComboBox(guiColor);
guiColorChanger.setBackground(Color.WHITE);
guiColorChanger.setPreferredSize(new Dimension(200, 30));
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints guiColorChangerGBC = new GridBagConstraints();
guiColorChangerGBC.gridy = 1;
guiColorChangerGBC.insets = new Insets(0, 20, 0, 50);
guiColorChangerGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChanger, guiColorChangerGBC);
guiColorChangerLabel = new JLabel("GUI Color Mode:");
GridBagConstraints guiColorChangerLabelGBC = new GridBagConstraints();
guiColorChangerLabelGBC.gridy = 0;
guiColorChangerLabelGBC.insets = new Insets(30, 20, 5, 0);
guiColorChangerLabelGBC.anchor = GridBagConstraints.WEST;
guiColorChangerPanel.add(guiColorChangerLabel, guiColorChangerLabelGBC);
guiColorChanger.addActionListener(new ChangeColorsGUI());
guiColorChanger.setFocusable(false);
//GAME DIFFICULTY PANEL:
difficultyPanel2 = new JPanel(new GridBagLayout());
difficultyPanel2.setBackground(whiteBlue);
settingsPanel.add(difficultyPanel2, BorderLayout.SOUTH);
difficultyLabel = new JLabel("Difficulty:");
GridBagConstraints difficultyLabelGBC = new GridBagConstraints();
difficultyLabelGBC.gridy = 0;
difficultyLabelGBC.insets = new Insets(30, 0, 5, 50);
difficultyLabelGBC.anchor = GridBagConstraints.WEST;
difficultyPanel2.add(difficultyLabel, difficultyLabelGBC);
difficultyPanel = new JPanel(new GridBagLayout());
difficultyPanel.setBackground(Color.WHITE);
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints difficultyPanelGBC = new GridBagConstraints();
difficultyPanelGBC.gridy = 1;
difficultyPanelGBC.insets = new Insets(0, 0, 75, 100);
difficultyPanel2.add(difficultyPanel, difficultyPanelGBC);
GridBagConstraints difficultyGBC = new GridBagConstraints();
difficultyGBC.insets = new Insets(5, 5, 5, 5);
difficultyGBC.anchor = GridBagConstraints.WEST;
difficultyButton[0] = new JRadioButton("Easy [3]");
difficultyButton[1] = new JRadioButton("Normal [5]");
difficultyButton[2] = new JRadioButton("Hard [7]");
difficultyButton[3] = new JRadioButton("Impossible [9]");
difficultyButtonGroup = new ButtonGroup();
for (int x = 0; x < 4; x++) {
difficultyButton[x].setBackground(Color.WHITE);
difficultyButton[x].setActionCommand(x + "");
difficultyGBC.gridy = x;
difficultyPanel.add(difficultyButton[x], difficultyGBC);
difficultyButtonGroup.add(difficultyButton[x]);
difficultyButton[x].addActionListener(new SelectDifficulty());
}
//SCORE PANEL (RIGHT) --------------------------------------------------------------------------------------------------------
//CURRENT SCORE:
currentScorePanel2 = new JPanel(new GridBagLayout());
currentScorePanel2.setBackground(whiteBlue);
scorePanel.add(currentScorePanel2, BorderLayout.NORTH);
currentScoreLabel2 = new JLabel("Score: ");
GridBagConstraints currentScoreLabelGBC = new GridBagConstraints();
currentScoreLabelGBC.gridx = 0;
currentScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
currentScoreLabelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScoreLabel2, currentScoreLabelGBC);
currentScorePanel = new JPanel(new GridBagLayout());
currentScorePanel.setBackground(Color.WHITE);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints currentScorePanelGBC = new GridBagConstraints();
currentScorePanelGBC.insets = new Insets(100, 0, 100, 100);
currentScorePanelGBC.anchor = GridBagConstraints.WEST;
currentScorePanel2.add(currentScorePanel, currentScorePanelGBC);
currentScoreLabel = new JLabel(" ");
currentScoreLabelGBC.gridx = 1;
currentScorePanel.add(currentScoreLabel, currentScoreLabelGBC);
//HIGHSCORE:
highScorePanel2 = new JPanel(new GridBagLayout());
highScorePanel2.setBackground(whiteBlue);
scorePanel.add(highScorePanel2, BorderLayout.SOUTH);
highScoreLabel2 = new JLabel("Highscore: ");
GridBagConstraints highScoreLabelGBC = new GridBagConstraints();
highScoreLabelGBC.gridx = 0;
highScoreLabelGBC.insets = new Insets(5, 5, 5, 5);
highScoreLabelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScoreLabel2, highScoreLabelGBC);
highScorePanel = new JPanel(new GridBagLayout());
highScorePanel.setBackground(Color.WHITE);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints highScorePanelGBC = new GridBagConstraints();
highScorePanelGBC.insets = new Insets(100, 0, 100, 100);
highScorePanelGBC.anchor = GridBagConstraints.WEST;
highScorePanel2.add(highScorePanel, highScorePanelGBC);
highScoreLabel = new JLabel(" ");
highScoreLabelGBC.gridx = 1;
highScorePanel.add(highScoreLabel, highScoreLabelGBC);
frame.pack();
frame.setVisible(true);
}
public class CreateMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (model.getDifficulty() != 0) {
counter = 0;
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(false);
}
for (JButton b: button) {
b.setBackground(babyBlue);
b.setEnabled(false);
}
start.setEnabled(false);
arrayAuto = new int[model.getDifficulty()];
arrayAuto[0] = (int)(Math.random() * 16);
for (int x = 1; x < model.getDifficulty(); x++) {
arrayAuto[x] = (int)(Math.random() * 16);
while (arrayAuto[x] == arrayAuto[x - 1]) {
arrayAuto[x] = (int)(Math.random() * 16);
}
}
arrayUser = Arrays.copyOf(arrayAuto, arrayAuto.length);
button[arrayAuto[0]].setBackground(limeGreen);
timer.start();
} else {
Object[] options = {"OK"};
JOptionPane.showOptionDialog(null, "Please select a Difficulty.", "ERROR", JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
}
}
}
public class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
button[arrayAuto[0]].setBackground(babyBlue);
arrayAuto = Arrays.copyOfRange(arrayAuto, 1, arrayAuto.length);
if (arrayAuto.length == 0) {
timer.stop();
for (JButton b: button) {
b.setEnabled(true);
}
} else {
button[arrayAuto[0]].setBackground(limeGreen);
}
}
}
public class AttemptMemoryGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (Integer.parseInt(ae.getActionCommand()) == arrayUser[counter]) {
if (counter != 0) {
button[arrayUser[counter - 1]].setBackground(babyBlue);
}
button[arrayUser[counter]].setBackground(limeGreen);
counter++;
currentScore += model.getDifficulty();
currentScoreLabel.setText(" " + currentScore + " ");
} else {
if (currentScore > highScore) {
highScore = currentScore;
highScoreLabel.setText(" " + highScore + " ");
}
currentScore = 0;
currentScoreLabel.setText(" ");
for (int x = 0; x < model.getDifficulty(); x++) {
button[arrayUser[x]].setBackground(brightRed);
}
start.setEnabled(true);
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
for (JButton b: button) {
b.setEnabled(false);
}
}
if (counter == arrayUser.length) {
start.setEnabled(true);
for (int x = 0; x < counter - 1; x++) {
button[arrayUser[x]].setBackground(limeGreen);
}
for (JButton b: button) {
b.setEnabled(false);
}
for (JRadioButton rb: difficultyButton) {
rb.setEnabled(true);
}
}
}
}
public class SelectDifficulty implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(0 + "")) {
model.setDifficulty(3);
} else if (ae.getActionCommand().equals(2 + "")) {
model.setDifficulty(7);
} else if (ae.getActionCommand().equals(3 + "")) {
model.setDifficulty(9);
} else {
model.setDifficulty(5);
}
}
}
public class ChangeColorsGUI implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (guiColorChanger.getSelectedItem() == guiColor[0]) {
guiColorChanger.setBackground(Color.WHITE);
settingsPanel.setBackground(whiteBlue);
gamePanel.setBackground(Color.WHITE);
scorePanel.setBackground(whiteBlue);
buttonPanel.setBackground(Color.WHITE);
guiColorChangerPanel.setBackground(whiteBlue);
buttonPanel2.setBackground(Color.WHITE);
guiColorChanger.setForeground(Color.BLACK);
guiColorChangerLabel.setForeground(Color.BLACK);
difficultyPanel.setBackground(Color.WHITE);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.WHITE);
rb.setForeground(Color.BLACK);
}
difficultyLabel.setBackground(whiteBlue);
difficultyLabel.setForeground(Color.BLACK);
difficultyPanel2.setBackground(whiteBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.BLACK));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scorePanel.setBackground(whiteBlue);
currentScoreLabel.setBackground(Color.WHITE);
currentScoreLabel.setForeground(Color.BLACK);
currentScoreLabel2.setForeground(Color.BLACK);
currentScorePanel.setBackground(whiteBlue);
currentScorePanel2.setBackground(whiteBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
highScoreLabel.setBackground(Color.WHITE);
highScoreLabel.setForeground(Color.BLACK);
highScoreLabel2.setForeground(Color.BLACK);
highScorePanel.setBackground(whiteBlue);
highScorePanel2.setBackground(whiteBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
guiColorChanger.setBackground(Color.BLACK);
settingsPanel.setBackground(blackBlue);
gamePanel.setBackground(Color.BLACK);
scorePanel.setBackground(blackBlue);
buttonPanel.setBackground(Color.BLACK);
guiColorChangerPanel.setBackground(blackBlue);
buttonPanel2.setBackground(Color.BLACK);
guiColorChanger.setForeground(Color.WHITE);
guiColorChangerLabel.setForeground(Color.WHITE);
difficultyPanel.setBackground(Color.BLACK);
for (JRadioButton rb: difficultyButton) {
rb.setBackground(Color.BLACK);
rb.setForeground(Color.WHITE);
}
difficultyLabel.setBackground(blackBlue);
difficultyLabel.setForeground(Color.WHITE);
difficultyPanel2.setBackground(blackBlue);
guiColorChanger.setBorder(BorderFactory.createLineBorder(Color.WHITE));
difficultyPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
scorePanel.setBackground(blackBlue);
currentScoreLabel.setBackground(Color.BLACK);
currentScoreLabel.setForeground(Color.WHITE);
currentScoreLabel2.setForeground(Color.WHITE);
currentScorePanel.setBackground(blackBlue);
currentScorePanel2.setBackground(blackBlue);
currentScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
highScoreLabel.setBackground(Color.BLACK);
highScoreLabel.setForeground(Color.WHITE);
highScoreLabel2.setForeground(Color.WHITE);
highScorePanel.setBackground(blackBlue);
highScorePanel2.setBackground(blackBlue);
highScorePanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
}
}
}
}
MemoryGameView becomes the controller, and it is as simple as:
public class MemoryGameView{
public MemoryGameView() {
Model model = new Model();
View view = new View(model);
}
public static void main(String[] args) {
new MemoryGameView();
}
}
Follow this link for a complete working prototype.
To continue: refactor more attributes (data and logic) from View to Model.
You may need to add listener so View can listen to changes in Model.
Side note: if indeed no Controller needed you can simply eliminate MemoryGameView and refactor its functionality to a main method:
public static void main(String[] args) {
Model model = new Model();
View view = new View(model);
}
but I wouldn't recommend it.

The following members might go into the model class:
difficulty
currentScore
highScore
arrayAuto
arrayUser
counter
Effectively the "pure" information.
The view should contain only ui code, i.e. Swing-Code. Since the game loop (timer) might be regarded as business code it would probably be a good idea to move it to the controller.
I did a quick google about swing and mvc: You might try to use existing frameworks like this for mvc.

Related

Dynamically replacing a panel of buttons

This is my first trial in java Swing. The issue am having is recreating the calendar panel every time the month changes. I would like to have the panelRightDown repopulated when addMonth is called (when > or < is clicked). I have tried calling revalidate, invalidate, repaint in addMonth but everything just goes haywire. The same methods ought to be implemented while calculating the year. Any help would be appreciated. More so, a better approach to this is highly welcome.
public class Gui extends JFrame {
private final int windowWidth = 700;
private final int windowHeight = 600;
private final Container container;
private final JPanel panelLeft = new JPanel();
private final JPanel panelRight = new JPanel();
private final GridBagConstraints gridBagConstraints = new GridBagConstraints();
private final int verticalSpacerSize = 8;
private final int horizontalSpacerSize = 15;
private Border lowerEtchedBorder =
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
// -----
protected boolean controlsOnTop;
protected boolean removeOnDaySelection;
protected Calendar currentDisplayDate;
protected JButton prevMonth;
protected JButton nextMonth;
protected JButton prevYear;
protected JButton nextYear;
protected JTextField textField;
protected List<ActionListener> popupListeners =
new ArrayList<ActionListener>();
protected Popup popup;
protected SimpleDateFormat dayName = new SimpleDateFormat("d");
protected SimpleDateFormat monthName = new SimpleDateFormat("MMMM");
protected String iconFile = "datepicker.gif";
protected String[] weekdayNames =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
JPanel datePanel = new JPanel();
JPanel panelRightDown = new JPanel();
JPanel controlsPanel;
// -----
// Constructor to setup the GUI components and event handlers
public Gui() {
//-----
currentDisplayDate = Calendar.getInstance();
controlsOnTop = true;
removeOnDaySelection = true;
//createPanel();
// Retrieve the content-pane of the top-level container JFrame
// All operations done on the content-pane
container = getContentPane();
container.setLayout(new BorderLayout());
//container.setMinimumSize(new Dimension(windowWidth, windowHeight));
createMenuBar();
createStatusBar();
JPanel fullPane = new JPanel();
fullPane.setLayout(new GridBagLayout());
// Spacer
container.add(Box.createVerticalStrut(
4), BorderLayout.NORTH);
container.add(fullPane, BorderLayout.CENTER);
fullPane.setMinimumSize(new Dimension(windowWidth, windowHeight));
// Position Left and Right panels
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.3;
gridBagConstraints.weighty = 1.0;
fullPane.add(panelLeft, gridBagConstraints);
gridBagConstraints.gridx = 1;
gridBagConstraints.weightx = 0;
fullPane.add(Box.createHorizontalStrut(
15), gridBagConstraints);
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 2;
gridBagConstraints.weightx = 0.9;
fullPane.add(panelRight, gridBagConstraints);
configurePanelLeft(panelLeft);
configurePanelRight(panelRight);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Prod - Reminder");
setSize(windowWidth, windowHeight);
setLocationRelativeTo(null);
setVisible(true);
addWindowListener(new Terminator());
}
public void setDate(String date) {
currentDisplayDate = Calendar.getInstance();
editDate(date);
}
public void setDate(Calendar date) {
currentDisplayDate = date;
//createPanel();
validate();
repaint();
}
public void setDate(int month, int day, int year) {
currentDisplayDate = Calendar.getInstance();
currentDisplayDate.set(expandYear(year), month - 1, day);
//createPanel();
validate();
repaint();
}
protected int expandYear(int year) {
if (year < 100) { // 2 digit year
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int current2DigitYear = currentYear % 100;
int currentCentury = currentYear / 100 * 100;
// set 2 digit year range +20 / -80 from current year
int high2DigitYear = (current2DigitYear + 20) % 100;
if (year <= high2DigitYear) {
year += currentCentury;
}
else {
year += (currentCentury - 100);
}
}
return year;
}
public void setControlsOnTop(boolean flag) {
controlsOnTop = flag;
//createPanel();
repaint();
}
public Calendar getCalendarDate() {
return currentDisplayDate;
}
public Date getDate() {
return currentDisplayDate.getTime();
}
public String getFormattedDate() {
return Integer.toString(getMonth()) + "/" +
Integer.toString(getDay()) + "/" +
Integer.toString(getYear());
}
public int getMonth() {
return currentDisplayDate.get(Calendar.MONTH) + 1;
}
public int getDay() {
return currentDisplayDate.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return currentDisplayDate.get(Calendar.YEAR);
}
protected JPanel createControls() {
JPanel c = new JPanel();
c.setBorder(BorderFactory.createRaisedBevelBorder());
c.setFocusable(true);
c.setLayout(new FlowLayout(FlowLayout.CENTER));
prevYear = new JButton("<<");
c.add(prevYear);
prevYear.setMargin(new Insets(0,0,0,0));
prevYear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addYear(-1);
}
});
prevMonth = new JButton("<");
c.add(prevMonth);
prevMonth.setMargin(new Insets(0,0,0,0));
prevMonth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMonth(-1);
}
});
textField = new JTextField(getFormattedDate(), 10);
c.add(textField);
textField.setEditable(true);
textField.setEnabled(true);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editDate(textField.getText());
}
});
nextMonth = new JButton(">");
c.add(nextMonth);
nextMonth.setMargin(new Insets(0,0,0,0));
nextMonth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMonth(+1);
}
});
nextYear = new JButton(">>");
c.add(nextYear);
nextYear.setMargin(new Insets(0,0,0,0));
nextYear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
addYear(+1);
}
});
return c;
}
protected JPanel configureDatePicker() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
datePanel.setFocusable(true);
datePanel.setLayout(gridbag);
String month = monthName.format(currentDisplayDate.getTime());
String year = Integer.toString(getYear());
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 7;
c.gridheight = 1;
JLabel title = new JLabel(month + " " + year);
datePanel.add(title, c);
Font font = title.getFont();
// Font titleFont = new Font(font.getName(), font.getStyle(),
// font.getSize() + 2);
Font weekFont = new Font(font.getName(), font.getStyle(),
font.getSize() - 2);
title.setFont(font);
c.gridy = 1;
c.weightx = 0.1;
c.weighty = 0.1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
for (c.gridx = 0; c.gridx < 7; c.gridx++) {
JLabel label = new JLabel(
weekdayNames[c.gridx], SwingConstants.CENTER);
datePanel.add(label, c);
label.setFont(weekFont);
}
Calendar draw = (Calendar) currentDisplayDate.clone();
draw.set(Calendar.DATE, 1);
draw.add(Calendar.DATE, -draw.get(Calendar.DAY_OF_WEEK) + 1);
int monthInt = currentDisplayDate.get(Calendar.MONTH);
// monthInt = 0;
// System.out.println("Current month: " + monthInt);
c.gridwidth = 1;
c.gridheight = 1;
int width = getFontMetrics(weekFont).stringWidth(" Wed ");
int width1 = getFontMetrics(weekFont).stringWidth("Wed");
int height = getFontMetrics(weekFont).getHeight() +
(width - width1);
for (c.gridy = 2; c.gridy < 8; c.gridy++) {
for (c.gridx = 0; c.gridx < 7; c.gridx++) {
JButton dayButton;
// System.out.print("Draw month: " + draw.get(Calendar.MONTH));
if (draw.get(Calendar.MONTH) == monthInt) {
String dayString = dayName.format(draw.getTime());
if (draw.get(Calendar.DAY_OF_MONTH) < 10) {
dayString = " " + dayString;
}
dayButton = new JButton(dayString);
} else {
dayButton = new JButton();
dayButton.setEnabled(false);
}
// System.out.println(", day: " + dayName.format(draw.getTime()));
datePanel.add(dayButton, c);
Color color = dayButton.getBackground();
if ((draw.get(Calendar.DAY_OF_MONTH) == getDay()) &&
(draw.get(Calendar.MONTH) == monthInt)) {
dayButton.setBackground(Color.yellow);
// dayButton.setFocusPainted(true);
// dayButton.setSelected(true);
} else
dayButton.setBackground(color);
dayButton.setFont(weekFont);
dayButton.setFocusable(true);
//dayButton.setPreferredSize(new Dimension(width, height));
//dayButton.setMargin(new Insets(0,0,0,0));
dayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeDay(e.getActionCommand());
}
});
//if (dateChange != null)
// dayButton.addActionListener(dateChange);
draw.add(Calendar.DATE, +1);
}
// if (draw.get(Calendar.MONTH) != monthInt) break;
}
return datePanel;
}
public void addMonth(int month) {
currentDisplayDate.add(Calendar.MONTH, month);
datePanel.invalidate();
controlsPanel.invalidate();
panelRightDown.validate();
datePanel = configureDatePicker();
controlsPanel = createControls();
panelRightDown.removeAll();
panelRightDown.add(controlsPanel);
panelRightDown.add(datePanel);
validate();
repaint();
}
public void addYear(int year) {
currentDisplayDate.add(Calendar.YEAR, year);
validate();
repaint();
}
public void editDate(String date) {
parseDate(date);
//createPanel();
validate();
repaint();
}
protected void parseDate(String date) {
String[] parts = date.split("/");
switch (parts.length) {
case 3:
currentDisplayDate.set(Calendar.MONTH,
Integer.valueOf(parts[0]) - 1);
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(parts[1]));
currentDisplayDate.set(Calendar.YEAR,
expandYear(Integer.valueOf(parts[2])));
break;
case 2:
currentDisplayDate = Calendar.getInstance();
currentDisplayDate.set(Calendar.MONTH,
Integer.valueOf(parts[0]) - 1);
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(parts[1]));
break;
default:
// invalid date
currentDisplayDate = Calendar.getInstance();
break;
}
}
public void changeDay(String day) {
currentDisplayDate.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(day.trim()));
textField.setText(getFormattedDate());
if (!removeOnDaySelection) {
//createPanel();
//validate();
repaint();
}
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit");
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener((ActionEvent event) -> {
System.exit(0);
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
}
private void createStatusBar() {
// create the status bar panel and shove it down the bottom of the frame
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
container.add(statusPanel, BorderLayout.SOUTH);
statusPanel.setPreferredSize(new Dimension(container.getWidth(), 20));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
JLabel statusLabel = new JLabel("status");
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
}
public void configurePanelLeft(JPanel panel) {
// Configure Left-side panels
// Top panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.3;
gridBagConstraints.weighty = 0.3;
JPanel panelLeftTop = new JPanel();
panelLeftTop.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.YELLOW));
panel.setLayout(new GridBagLayout());
panel.add(panelLeftTop, gridBagConstraints);
// Display Area
JTextArea displayItem = new JTextArea("Hello, left top!");
displayItem.setBorder(lowerEtchedBorder);
displayItem.setLineWrap(true);
displayItem.setBackground(panel.getBackground());
displayItem.setWrapStyleWord(true);
//displayItem.setEditable(false);
panelLeftTop.setLayout(new BorderLayout());
JScrollPane topScrollPane = new JScrollPane();
topScrollPane.getVerticalScrollBar().setUnitIncrement(3);
topScrollPane.setViewportView(displayItem);
topScrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelLeftTop.add(topScrollPane);
// Spacer
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0;
panel.add(Box.createVerticalStrut(
verticalSpacerSize), gridBagConstraints);
// Bottom panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.7;
JPanel panelLeftDown = new JPanel();
panelLeftDown.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
panelLeftDown.setLayout(new GridBagLayout());
for (int i = 0; i < 50; i++) {
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = i;
gridBagConstraints.weightx = 0.3;
//gridBagConstraints.weighty = 1.0;
String textValue = "Area: "+ i
+" This is a very long wrapped text, "
+ "which I expect to be an example of text in a label. "
+ "I really hope it works well."
+ "The Scroll Bar comes when your text goes beyond "
+ "the bounds of your view area. "
+ "Don't use Absolute Positioning, for such a small "
+ "talk at hand, always prefer Layout Managers, "
+ "do read the first para of the first link, "
+ "to know the advantage of using a Layout Manager.";
JTextArea textArea = new JTextArea(textValue);
textArea.setBorder(lowerEtchedBorder);
textArea.setLineWrap(true);
textArea.setBackground(panel.getBackground());
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
displayItem.setText(textValue);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
topScrollPane.getVerticalScrollBar().setValue(0);
}
});
}
#Override
public void mousePressed(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
panelLeftDown.add(textArea, gridBagConstraints);
}
JScrollPane scrollPane = new JScrollPane(panelLeftDown,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelLeftDown.setAutoscrolls(true);
scrollPane.setPreferredSize(new Dimension(300,800));
scrollPane.getVerticalScrollBar().setUnitIncrement(3);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollPane.getVerticalScrollBar().setValue(0);
}
});
panel.add(scrollPane, gridBagConstraints);
}
public void configurePanelRight(JPanel panel) {
// Configure right-side panels
// Top panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.1;
JPanel panelRightTop = new JPanel();
panelRightTop.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.YELLOW));
panelRightTop.add(new JLabel("Hello, right top!"));
panel.setLayout(new GridBagLayout());
panel.add(panelRightTop, gridBagConstraints);
// Spacer
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0;
panel.add(Box.createVerticalStrut(
verticalSpacerSize), gridBagConstraints);
// Bottom panel
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.9;
panelRightDown.setBorder(
BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
//panelRightDown.add(new JLabel("Hello, right down!"));
panel.add(panelRightDown, gridBagConstraints);
panel.add(panelRightDown, gridBagConstraints);
// Date Picker
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 0.1;
panelRightDown.setLayout(new BorderLayout());
datePanel = configureDatePicker();
controlsPanel = createControls();
panelRightDown.add(controlsPanel, BorderLayout.NORTH);
panelRightDown.add(datePanel, BorderLayout.CENTER);
}
private ListCellRenderer<? super String> getRenderer() {
return new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel listCellRendererComponent =
(JLabel) super.getListCellRendererComponent(
list, value, index, isSelected,cellHasFocus);
listCellRendererComponent.setBorder(
lowerEtchedBorder);
listCellRendererComponent.setEnabled(true);
return listCellRendererComponent;
}
};
}
public static void main(String[] args) {
// Run the GUI construction in the Event-Dispatching thread for thread-safety
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui(); // Let the constructor do the job
}
});
}
}

Selected variables doesn't change on pong game - Swing

I'm trying to make a pong game by using Swing. I have a menu screen where you can change your preferences such as music, game speed and you can choose multiplayer options etc. But when I made a choice, their values don't change. I have my mainmenu class and computer class.
For ex: I want to change the difficulty which means changing the AI's speed but I wasn't be able to do it. I am looking forward for an answer, maybe it's so simple but I can't see it.
This is my code:
public class MenuPanel
{
ScoreBoard sc = new ScoreBoard();
private JFrame mainFrame;
private JFrame optionsFrame;
private JPanel menuPanel;
private JPanel optionsPanel;
private JFrame gameEndFrame;
private JPanel gameEndPanel;
JCheckBox twoPlayer;
// creating the swing components and containers,
// there are two frames to swap between them,
// we tried to use cardLayout but it didn't work for us.
public MenuPanel() {
mainFrame = new JFrame("Welcome To Pong Game");
mainFrame.setSize(700,700);
mainFrame.setLayout(new CardLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuPanel = new JPanel(null);
menuPanel.setSize(700,700);
menuPanel.setVisible(true);
mainFrame.add(menuPanel);
optionsFrame = new JFrame("Settings");
optionsFrame.setSize(700, 700);
optionsFrame.setLayout(new CardLayout());
optionsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel optionsPanel = new JPanel(null) ;
optionsPanel.setSize(700,700);
optionsPanel.setVisible(true);
optionsFrame.add(optionsPanel);
// mainPanel components
ImageIcon ic1 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Actions-player-play-icon.png");
ImageIcon ic2 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Settings-L-icon.png");
ImageIcon ic3 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\cup-icon.png");
ImageIcon ic4 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\Button-Close-icon.png");
ImageIcon ic5 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\ice-2025937_960_720.jpg");
ImageIcon ic6 = new ImageIcon("C:\\Users\\Onur17\\Downloads\\tenis1.png");
JLabel mainLabel = new JLabel();
Font font = new Font("Papyrus", Font.BOLD,26);
mainLabel.setFont(font);
mainLabel.setForeground(Color.RED);
mainLabel.setText("PONG GAME");
JButton startButton = new JButton("Start Game");
JButton optionsButton = new JButton("Options");
JButton leaderButton = new JButton("Leaderboard");
JButton exitButton = new JButton("Exit");
JButton icb1 = new JButton(ic1);
JButton icb2 = new JButton(ic2);
JButton icb3 = new JButton(ic3);
JButton icb4 = new JButton(ic4);
JButton icb6 = new JButton(ic6);
// at first, we tried to keep our buttons and labels in panels
// but then we didn't add an image to label as the background
// so we created a JLabel to set its image as the background, we may remove it later.
JLabel mn = new JLabel(ic5);
mn.setBackground(Color.BLUE);
mn.setBounds(1, 1, 700, 700);
Font font3 = new Font("Calibri", Font.PLAIN, 20);
twoPlayer = new JCheckBox();
twoPlayer.setFont(font3);
twoPlayer.setForeground(Color.DARK_GRAY);
twoPlayer.setText(" MultiPlayer");
twoPlayer.setBounds(200, 350, 220, 40);
menuPanel.add(mn);
mn.add(mainLabel);
mn.add(startButton);
mn.add(optionsButton);
mn.add(leaderButton);
mn.add(exitButton);
mn.add(icb1);
mn.add(icb2);
mn.add(icb3);
mn.add(icb4);
mn.add(icb6);
mn.add(twoPlayer);
mainFrame.setVisible(true);
// the components added by their coordinates to make them look formal
mainLabel.setBounds(210, 100, 220, 40);
startButton.setBounds(200, 150, 220, 40);
optionsButton.setBounds(200, 200, 220, 40);
leaderButton.setBounds(200, 250, 220, 40);
exitButton.setBounds(200, 300, 220, 40);
icb1.setBounds(150, 150, 40, 40);
icb2.setBounds(150, 200, 40, 40);
icb3.setBounds(150, 250, 40, 40);
icb4.setBounds(150, 300, 40, 40);
icb6.setBounds(150,350,40,40);
startButton.setBorder(BorderFactory.createRaisedBevelBorder());
optionsButton.setBorder(BorderFactory.createRaisedBevelBorder());
leaderButton.setBorder(BorderFactory.createRaisedBevelBorder());
exitButton.setBorder(BorderFactory.createRaisedBevelBorder());
// optionsPanel components
JButton doneButton = new JButton("Done");
doneButton.setBounds(150,330,220,40);
doneButton.setBorder(BorderFactory.createRaisedBevelBorder());
Font font1 = new Font("Calibri", Font.PLAIN,24);
Font font2 = new Font("Calibri", Font.BOLD,19);
JLabel st = new JLabel();
st.setFont(font1);
st.setForeground(Color.DARK_GRAY);
st.setText("-OPTIONS-");
JLabel difficulty = new JLabel("Difficulty: ");
difficulty.setFont(font2);
difficulty.setForeground(Color.DARK_GRAY);
JLabel music = new JLabel("Sound: ");
music.setFont(font2);
music.setForeground(Color.DARK_GRAY);
JLabel gSpeed = new JLabel("Game Speed: ");
gSpeed.setFont(font2);
gSpeed.setForeground(Color.DARK_GRAY);
JLabel screen = new JLabel(ic5);
screen.setBackground(Color.BLUE);
screen.setBounds(1, 1, 700, 700);
JRadioButton rb1 = new JRadioButton("Easy");
JRadioButton rb2 = new JRadioButton("Normal");
JRadioButton rb3 = new JRadioButton("Hard");
JRadioButton rb4 = new JRadioButton("On");
JRadioButton rb5 = new JRadioButton("Off");
JRadioButton rb6 = new JRadioButton("x");
JRadioButton rb7 = new JRadioButton("2x");
JRadioButton rb8 = new JRadioButton("3x");
ButtonGroup bg1 = new ButtonGroup();
ButtonGroup bg2 = new ButtonGroup();
ButtonGroup bg3 = new ButtonGroup();
bg1.add(rb1);
bg1.add(rb2);
bg1.add(rb3);
bg2.add(rb4);
bg2.add(rb5);
bg3.add(rb6);
bg3.add(rb7);
bg3.add(rb8);
optionsPanel.add(screen);
screen.add(difficulty);
screen.add(st);
screen.add(gSpeed);
screen.add(rb1);
screen.add(rb2);
screen.add(rb3);
screen.add(rb4);
screen.add(rb5);
screen.add(rb6);
screen.add(rb7);
screen.add(rb8);
screen.add(music);
screen.add(doneButton);
st.setBounds(200,100,220,40);
difficulty.setBounds(100,150,90,40);
music.setBounds(100,200,90,40);
gSpeed.setBounds(100, 250, 120, 40);
rb1.setBounds(200,150,60,40);
rb2.setBounds(260,150,80,40);
rb3.setBounds(340, 150, 60, 40);
rb4.setBounds(200, 200, 50, 40);
rb5.setBounds(250,200,50,40);
rb6.setBounds(220, 250, 50, 40);
rb7.setBounds(270, 250, 50, 40);
rb8.setBounds(320, 250, 50, 40);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Pong pong = new Pong();
sound("Marimba-music");
mainFrame.dispose();
if(twoPlayer.isSelected()) {
pong.c.isTwoPlayer = true;
}
else {
pong.c.isTwoPlayer = false;
}
}
});
optionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.setVisible(false);
optionsFrame.setVisible(true);
}
});
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsFrame.dispose();
Pong pong = new Pong();
if(rb1.isSelected())
{
pong.c.setUp(-10);;
pong.c.setDown(10);
}
else if(rb2.isSelected())
{
pong.c.setUp(-11);
pong.c.setDown(11);
}
else if(rb3.isSelected())
{
pong.c.setUp(-30);
pong.c.setDown(30);
}
if(rb4.isSelected())
{
sound("Marimba-music");
}
else if(rb5.isSelected())
{
soundStop("Marimba-music");
}
if(rb6.isSelected())
{
GamePanel g = new GamePanel();
g.x = 50;
}
else if(rb7.isSelected())
{
GamePanel g = new GamePanel();
g.x = 75;
}
else if(rb8.isSelected())
{
GamePanel g = new GamePanel();
g.x = 100;
System.out.println(g.x);
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
mainFrame.dispose();
}
});
}
public void sound(String nm)
{
AudioStream BGM;
try {
InputStream test = new FileInputStream("./" +nm+".wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(IOException error) {
JOptionPane.showMessageDialog(null, error.getMessage());
}
}
public void soundStop(String nm)
{
AudioStream BGM;
try {
InputStream test = new FileInputStream("./" +nm+".wav");
BGM = new AudioStream(test);
AudioPlayer.player.stop(BGM);
}
catch(IOException error) {
JOptionPane.showMessageDialog(null, error.getMessage());
}
}
}
My Computer.class:
public class Computer
{
private GamePanel field;
private int y = Pong.WINDOW_HEIGHT / 2;
private int yCh = 0;
private int up = -10;
private int down = 10;
private int width = 20;
private int height = 90;
boolean isTwoPlayer = false;
public Computer() {
}
public void update(Ball b) {
if(y + height > Pong.WINDOW_HEIGHT)
{
y = Pong.WINDOW_HEIGHT - height;
}
else if(y < 0)
{
y = 0;
}
if(!isTwoPlayer) {
if(b.getY() < y+height && y >= 0)
{
yCh = up;
}
else if(b.getY() > y && y + height <= Pong.WINDOW_HEIGHT)
{
yCh = down;
}
y = y + yCh;
}
else {
y = y + yCh;
}
}
public void setYPosition(int speed) {
yCh = speed;
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRoundRect(450, y, width, height, 10, 10);
}
public int getX() {
return 450;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getUp() {
return up;
}
public int getDown() {
return down;
}
public void setUp(int up) {
this.up = up;
}
public void setDown(int down) {
this.down = down;
}
I don't know how your whole program is structured. But in this piece of code:
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionsFrame.dispose();
Pong pong = new Pong();
You create a new instance of Pong class and set the values of the new created instance.
This instance is not used anywhere else. You may need to use a instance of Pong that is already in use, or make other classes use the new created instance.

using a varible to decide array length for several classes in one class Java

I have made 3 classes for each level (easy 4*4, medium 6*4, hard 6*6) in a memory game. They consist of the same code, however they have different numbers of the array length and other variables. I want to make the code more efficient by combining the three classes together into only one, do you have any suggestions? If it helps I have pasted the three different classes below :)
Arrays and variables from the 3 different classes:
JButton[] button = new JButton[16];
JButton[] button = new JButton[24];
JButton[] button = new JButton[36];
int[] StoreCards = new int[16];
int[] StoreCards = new int[24];
int[] StoreCards = new int[36];
static int[] card = new int[9];
static int[] card = new int[13];
static int[] card = new int[19];
Easy Level:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class EasyWindow extends JFrame implements ActionListener, MouseListener {
JLabel Score = new JLabel("Score: - ");
JLabel Welcome = new JLabel("Welcome " + StartWindow.user + "!");
ImageIcon Back = new ImageIcon("mback.png");
ImageIcon musicicon = new ImageIcon("musicicon.png");
ImageIcon themeicon = new ImageIcon("themeicon.png");
ImageIcon difficultyicon = new ImageIcon("difficulty.png");
ImageIcon pointsicon = new ImageIcon("pointsicon.png");
ImageIcon studentsicon = new ImageIcon("studentsicon.png");
JButton AnOtherLevel = new JButton(
"Click here if you want to change level.");
JButton Quit = new JButton("Quit Game!");
JButton[] button = new JButton[16];
JMenuBar menuBar = new JMenuBar();
JMenu Settings = new JMenu("Settings");
JMenu Theme = new JMenu("Theme");
JMenu Rules = new JMenu("Rules");
JMenu Creators = new JMenu("Creators");
JMenuItem Music = new JMenuItem("Music", musicicon);
JMenuItem Celebrities = new JMenuItem("Celebrities", themeicon);
JMenuItem Cities = new JMenuItem("Cities", themeicon);
JMenuItem Memes = new JMenuItem("Memes", themeicon);
JMenuItem Difficulty = new JMenuItem("Difficulty", difficultyicon);
JMenuItem Points = new JMenuItem("Points", pointsicon);
JMenuItem Ava = new JMenuItem("Ava Baghchesara", studentsicon);
JMenuItem Michelle = new JMenuItem("Michelle Bill", studentsicon);
int[] StoreCards = new int[16];
static int[] cardChecker = new int[2];
static int[] card = new int[9];
int[] Button = new int[2];
static int flipped = 0;
static int score = 0;
String imageType = ".png";
String back = ".png";
JPanel Top = new JPanel(new GridLayout(1, 1, 5, 15));
JPanel Center = new JPanel(new GridLayout(4, 4, 5, 5));
JPanel Bottom = new JPanel(new GridLayout(1, 2, 0, 0));
JPanel Right = new JPanel(new GridLayout(2, 2, 0, 0));
JPanel Left = new JPanel(new GridLayout(1, 1, 0, 0));
static Container contentArea;
public EasyWindow() {
super("User: " + StartWindow.user + " || Easy Level");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLayout(new BorderLayout());
setVisible(true);
AnOtherLevel.addActionListener(this);
Quit.addActionListener(this);
AnOtherLevel.addMouseListener(this);
Quit.addMouseListener(this);
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
add(Top, BorderLayout.NORTH);
add(Left, BorderLayout.WEST);
add(Center, BorderLayout.CENTER);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
Welcome.setFont(new Font("Serif", Font.PLAIN, 30));
Welcome.setHorizontalAlignment(SwingConstants.CENTER);
Welcome.setVerticalAlignment(SwingConstants.CENTER);
Top.add(Welcome);
Top.setBackground(Color.white);
Center.setBackground(Color.white);
Right.setBackground(Color.white);
Right.add(Score);
Bottom.add(AnOtherLevel);
Bottom.add(Quit);
Bottom.setBackground(Color.white);
for (int n = 0; n <= button.length - 1; n++) {
button[n] = new JButton();
Center.add(button[n]);
button[n].addActionListener(this);
button[n].setBackground(Color.white);
}
contentArea = getContentPane();
contentArea.add("North", Top);
contentArea.add("Center", Center);
contentArea.add("South", Bottom);
menuBar.add(Settings);
menuBar.add(Rules);
menuBar.add(Creators);
setJMenuBar(menuBar);
Music.addActionListener(this);
Theme.addActionListener(this);
Celebrities.addActionListener(this);
Cities.addActionListener(this);
Memes.addActionListener(this);
Difficulty.addActionListener(this);
Points.addActionListener(this);
Ava.addActionListener(this);
Michelle.addActionListener(this);
Settings.add(Music);
Settings.add(Theme);
Theme.add(Celebrities);
Theme.add(Cities);
Theme.add(Memes);
Rules.add(Difficulty);
Rules.add(Points);
Creators.add(Ava);
Creators.add(Michelle);
Game();
flipped = 3;
Reset();
setContentPane(contentArea);
contentArea.setBackground(Color.white);
}
public void Game() {
int number = 0;
int x = 0;
ImageIcon image[] = new ImageIcon[15];
while (x < 16) {
number = (int) RandomNumbers.GetRandomNumber(8);
image[number] = new ImageIcon(number + imageType);
if (card[number] < 2) {
card[number]++;
StoreCards[x] = number;
System.out.println(number + " Number" + "card nr " + x);
x++;
}
}
}
public void Reset() {
if (flipped > 2) {
flipped = 0;
for (int n = 0; n <= button.length - 1; n++) {
button[n].setIcon(Back);
}
}
}
public void Check(int number) {
if (cardChecker[0] == cardChecker[1]) {
score = score + 2;
Score.setText("Score: " + score);
DisableButtons();
} else {
System.out.println("jj");
}
if (score == 16) {
setVisible(false);
new EndWindow1();
}
}
public void Card1and2(int number, int button) {
if (flipped == 0) {
cardChecker[0] = number;
Button[0] = button;
}
if (flipped == 1) {
cardChecker[1] = number;
Button[1] = button;
if (StoreCards[cardChecker[0]] == StoreCards[cardChecker[1]]) {
if (Button[0] != Button[1])
Check(number);
}
}
}
public void DisableButtons() {
for (int n = 0; n <= button.length; n++) {
if (Button[0] == n || Button[1] == n) {
button[n].setVisible(false);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == AnOtherLevel) {
setVisible(false);
new AnOtherWindow();
}
if (event.getSource() == Quit) {
System.exit(0);
}
for (int n = 0; n <= button.length - 1; n++) {
if (event.getSource() == button[n]) {
int number = StoreCards[n];
button[n].setIcon(new ImageIcon(number + imageType));
Card1and2(number, n);
flipped++;
Reset();
}
}
if (event.getSource() == Celebrities) {
Back = new ImageIcon("ceback.png");
imageType = "c.png";
}
if (event.getSource() == Cities) {
Back = new ImageIcon("ciback.png");
imageType = ".jpg";
}
if (event.getSource() == Memes) {
Back = new ImageIcon("mback.png");
imageType = ".png";
}
}
public void mouseEntered(MouseEvent event) {
if (event.getSource() == AnOtherLevel) {
AnOtherLevel.setBackground(Color.lightGray);
AnOtherLevel.setForeground(Color.BLACK);
}
if (event.getSource() == Quit) {
Quit.setBackground(Color.lightGray);
Quit.setForeground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class EasyLevelWindow {
public static void main(String[] args) {
EasyWindow win = new EasyWindow();
}
Medium Level:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class MediumWindow extends JFrame implements ActionListener, MouseListener {
JLabel Score = new JLabel("Score: - ");
JLabel Welcome = new JLabel("Welcome " + StartWindow.user + "!");
ImageIcon Back = new ImageIcon("mback.png");
ImageIcon musicicon = new ImageIcon("musicicon.png");
ImageIcon themeicon = new ImageIcon("themeicon.png");
ImageIcon difficultyicon = new ImageIcon("difficulty.png");
ImageIcon pointsicon = new ImageIcon("pointsicon.png");
ImageIcon studentsicon = new ImageIcon("studentsicon.png");
JButton AnOtherLevel = new JButton(
"Click here if you want to change level.");
JButton Quit = new JButton("Quit Game!");
JButton[] button = new JButton[24];
JMenuBar menuBar = new JMenuBar();
JMenu Settings = new JMenu("Settings");
JMenu Theme = new JMenu("Theme");
JMenu Rules = new JMenu("Rules");
JMenu Creators = new JMenu("Creators");
JMenuItem Music = new JMenuItem("Music", musicicon);
JMenuItem Celebrities = new JMenuItem("Celebrities", themeicon);
JMenuItem Cities = new JMenuItem("Cities", themeicon);
JMenuItem Memes = new JMenuItem("Memes", themeicon);
JMenuItem Difficulty = new JMenuItem("Difficulty", difficultyicon);
JMenuItem Points = new JMenuItem("Points", pointsicon);
JMenuItem Ava = new JMenuItem("Ava Baghchesara", studentsicon);
JMenuItem Michelle = new JMenuItem("Michelle Bill", studentsicon);
int[] StoreCards = new int[24];
static int[] cardChecker = new int[2];
static int[] card = new int[13];
int[] Button = new int[2];
static int flipped = 0;
static int score = 0;
String imageType = ".png";
String back = ".png";
JPanel Top = new JPanel(new GridLayout(2, 1, 5, 15));
JPanel Center = new JPanel(new GridLayout(6, 4, 5, 5));
JPanel Bottom = new JPanel(new GridLayout(1, 1, 0, 0));
JPanel Right = new JPanel(new GridLayout(2, 2, 0, 0));
JPanel Left = new JPanel(new GridLayout(1, 1, 0, 0));
static Container contentArea;
public MediumWindow() {
super("User: " + StartWindow.user + " || Medium Level");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLayout(new BorderLayout());
setVisible(true);
AnOtherLevel.addActionListener(this);
Quit.addActionListener(this);
AnOtherLevel.addMouseListener(this);
Quit.addMouseListener(this);
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
add(Top, BorderLayout.NORTH);
add(Left, BorderLayout.WEST);
add(Center, BorderLayout.CENTER);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
Welcome.setFont(new Font("Serif", Font.PLAIN, 30));
Welcome.setHorizontalAlignment(SwingConstants.CENTER);
Welcome.setVerticalAlignment(SwingConstants.CENTER);
Top.add(Welcome);
Top.setBackground(Color.white);
Center.setBackground(Color.white);
Right.setBackground(Color.white);
Right.add(Score);
Bottom.add(AnOtherLevel);
Bottom.add(Quit);
Bottom.setBackground(Color.white);
for (int n = 0; n <= button.length - 1; n++) {
button[n] = new JButton();
Center.add(button[n]);
button[n].addActionListener(this);
button[n].setBackground(Color.white);
}
contentArea = getContentPane();
contentArea.add("North", Top);
contentArea.add("Center", Center);
contentArea.add("South", Bottom);
menuBar.add(Settings);
menuBar.add(Rules);
menuBar.add(Creators);
setJMenuBar(menuBar);
Music.addActionListener(this);
Theme.addActionListener(this);
Celebrities.addActionListener(this);
Cities.addActionListener(this);
Memes.addActionListener(this);
Difficulty.addActionListener(this);
Points.addActionListener(this);
Ava.addActionListener(this);
Michelle.addActionListener(this);
Settings.add(Music);
Settings.add(Theme);
Theme.add(Celebrities);
Theme.add(Cities);
Theme.add(Memes);
Rules.add(Difficulty);
Rules.add(Points);
Creators.add(Ava);
Creators.add(Michelle);
Game();
flipped = 3;
Reset();
setContentPane(contentArea);
contentArea.setBackground(Color.white);
}
public void Game() {
int number = 0;
int x = 0;
ImageIcon image[] = new ImageIcon[23];
while (x < 24) {
number = (int) RandomNumbers.GetRandomNumber(12);
image[number] = new ImageIcon(number + imageType);
if (card[number] < 2) {
card[number]++;
StoreCards[x] = number;
System.out.println(number + " Number" + "card nr " + x);
x++;
}
}
}
public void Reset() {
if (flipped > 2) {
flipped = 0;
for (int n = 0; n <= button.length - 1; n++) {
button[n].setIcon(Back);
}
}
}
public void Check(int number) {
if (cardChecker[0] == cardChecker[1]) {
score = score + 2;
Score.setText("Score: " + score);
DisableButtons();
} else {
System.out.println("jj");
}
if (score == 24) {
setVisible(false);
new EndWindow1();
}
}
public void Card1and2(int number, int button) {
if (flipped == 0) {
cardChecker[0] = number;
Button[0] = button;
}
if (flipped == 1) {
cardChecker[1] = number;
Button[1] = button;
if (StoreCards[cardChecker[0]] == StoreCards[cardChecker[1]]) {
if (Button[0] != Button[1])
Check(number);
}
}
}
public void DisableButtons() {
for (int n = 0; n <= button.length; n++) {
if (Button[0] == n || Button[1] == n) {
button[n].setVisible(false);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == AnOtherLevel) {
setVisible(false);
new AnOtherWindow();
}
if (event.getSource() == Quit) {
System.exit(0);
}
for (int n = 0; n <= button.length - 1; n++) {
if (event.getSource() == button[n]) {
int number = StoreCards[n];
button[n].setIcon(new ImageIcon(number + imageType));
Card1and2(number, n);
flipped++;
Reset();
}
}
if (event.getSource() == Celebrities) {
Back = new ImageIcon("ceback.png");
imageType = "c.png";
}
if (event.getSource() == Cities) {
Back = new ImageIcon("ciback.png");
imageType = ".jpg";
}
if (event.getSource() == Memes) {
Back = new ImageIcon("mback.png");
imageType = ".png";
}
}
public void mouseEntered(MouseEvent event) {
if (event.getSource() == AnOtherLevel) {
AnOtherLevel.setBackground(Color.lightGray);
AnOtherLevel.setForeground(Color.BLACK);
}
if (event.getSource() == Quit) {
Quit.setBackground(Color.lightGray);
Quit.setForeground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class MediumLevelWindow {
public static void main(String[] args) {
MediumWindow win = new MediumWindow();
}
}
Hard Level:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class HardWindow extends JFrame implements ActionListener, MouseListener {
JLabel Score = new JLabel("Score: - ");
JLabel Welcome = new JLabel("Welcome " + StartWindow.user + "!");
ImageIcon Back = new ImageIcon("mback.png");
ImageIcon musicicon = new ImageIcon("musicicon.png");
ImageIcon themeicon = new ImageIcon("themeicon.png");
ImageIcon difficultyicon = new ImageIcon("difficulty.png");
ImageIcon pointsicon = new ImageIcon("pointsicon.png");
ImageIcon studentsicon = new ImageIcon("studentsicon.png");
JButton AnOtherLevel = new JButton(
"Click here if you want to change level.");
JButton Quit = new JButton("Quit Game!");
JButton[] button = new JButton[36];
JMenuBar menuBar = new JMenuBar();
JMenu Settings = new JMenu("Settings");
JMenu Theme = new JMenu("Theme");
JMenu Rules = new JMenu("Rules");
JMenu Creators = new JMenu("Creators");
JMenuItem Music = new JMenuItem("Music", musicicon);
JMenuItem Celebrities = new JMenuItem("Celebrities", themeicon);
JMenuItem Cities = new JMenuItem("Cities", themeicon);
JMenuItem Memes = new JMenuItem("Memes", themeicon);
JMenuItem Difficulty = new JMenuItem("Difficulty", difficultyicon);
JMenuItem Points = new JMenuItem("Points", pointsicon);
JMenuItem Ava = new JMenuItem("Ava Baghchesara", studentsicon);
JMenuItem Michelle = new JMenuItem("Michelle Bill", studentsicon);
int[] StoreCards = new int[36];
static int[] cardChecker = new int[2];
static int[] card = new int[19];
int[] Button = new int[2];
static int flipped = 0;
static int score = 0;
String imageType = ".png";
String back = ".png";
JPanel Top = new JPanel(new GridLayout(2, 1, 5, 15));
JPanel Center = new JPanel(new GridLayout(6, 6, 5, 5));
JPanel Bottom = new JPanel(new GridLayout(1, 1, 0, 0));
JPanel Right = new JPanel(new GridLayout(2, 2, 0, 0));
JPanel Left = new JPanel(new GridLayout(1, 1, 0, 0));
static Container contentArea;
public HardWindow() {
super("User: " + StartWindow.user + " || Hard Level");
setSize(780, 730);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLayout(new BorderLayout());
setVisible(true);
AnOtherLevel.addActionListener(this);
Quit.addActionListener(this);
AnOtherLevel.addMouseListener(this);
Quit.addMouseListener(this);
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
add(Top, BorderLayout.NORTH);
add(Left, BorderLayout.WEST);
add(Center, BorderLayout.CENTER);
add(Right, BorderLayout.EAST);
add(Bottom, BorderLayout.SOUTH);
Welcome.setFont(new Font("Serif", Font.PLAIN, 30));
Welcome.setHorizontalAlignment(SwingConstants.CENTER);
Welcome.setVerticalAlignment(SwingConstants.CENTER);
Top.add(Welcome);
Top.setBackground(Color.white);
Center.setBackground(Color.white);
Right.setBackground(Color.white);
Right.add(Score);
Bottom.add(AnOtherLevel);
Bottom.add(Quit);
Bottom.setBackground(Color.white);
for (int n = 0; n <= button.length - 1; n++) {
button[n] = new JButton();
Center.add(button[n]);
button[n].addActionListener(this);
button[n].setBackground(Color.white);
}
contentArea = getContentPane();
contentArea.add("North", Top);
contentArea.add("Center", Center);
contentArea.add("South", Bottom);
menuBar.add(Settings);
menuBar.add(Rules);
menuBar.add(Creators);
setJMenuBar(menuBar);
Music.addActionListener(this);
Theme.addActionListener(this);
Celebrities.addActionListener(this);
Cities.addActionListener(this);
Memes.addActionListener(this);
Difficulty.addActionListener(this);
Points.addActionListener(this);
Ava.addActionListener(this);
Michelle.addActionListener(this);
Settings.add(Music);
Settings.add(Theme);
Theme.add(Celebrities);
Theme.add(Cities);
Theme.add(Memes);
Rules.add(Difficulty);
Rules.add(Points);
Creators.add(Ava);
Creators.add(Michelle);
Game();
flipped = 3;
Reset();
setContentPane(contentArea);
contentArea.setBackground(Color.white);
}
public void Game() {
int number = 0;
int x = 0;
ImageIcon image[] = new ImageIcon[35];
while (x < 36) {
number = (int) RandomNumbers.GetRandomNumber(18);
image[number] = new ImageIcon(number + imageType);
if (card[number] < 2) {
card[number]++;
StoreCards[x] = number;
System.out.println(number + " Number" + "card nr " + x);
x++;
}
}
}
public void Reset() {
if (flipped > 2) {
flipped = 0;
for (int n = 0; n <= button.length - 1; n++) {
button[n].setIcon(Back);
}
}
}
public void Check(int number) {
if (cardChecker[0] == cardChecker[1]) {
score = score + 2;
Score.setText("Score: " + score);
DisableButtons();
} else {
System.out.println("jj");
}
if (score == 36) {
setVisible(false);
new EndWindow1();
}
}
public void Card1and2(int number, int button) {
if (flipped == 0) {
cardChecker[0] = number;
Button[0] = button;
}
if (flipped == 1) {
cardChecker[1] = number;
Button[1] = button;
if (StoreCards[cardChecker[0]] == StoreCards[cardChecker[1]]) {
if (Button[0] != Button[1])
Check(number);
}
}
}
public void DisableButtons() {
for (int n = 0; n <= button.length; n++) {
if (Button[0] == n || Button[1] == n) {
button[n].setVisible(false);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == AnOtherLevel) {
setVisible(false);
new AnOtherWindow();
}
if (event.getSource() == Quit) {
System.exit(0);
}
for (int n = 0; n <= button.length - 1; n++) {
if (event.getSource() == button[n]) {
int number = StoreCards[n];
button[n].setIcon(new ImageIcon(number + imageType));
Card1and2(number, n);
flipped++;
Reset();
}
}
if (event.getSource() == Celebrities) {
Back = new ImageIcon("ceback.png");
imageType = "c.png";
}
if (event.getSource() == Cities) {
Back = new ImageIcon("ciback.png");
imageType = ".jpg";
}
if (event.getSource() == Memes) {
Back = new ImageIcon("mback.png");
imageType = ".png";
}
}
public void mouseEntered(MouseEvent event) {
if (event.getSource() == AnOtherLevel) {
AnOtherLevel.setBackground(Color.lightGray);
AnOtherLevel.setForeground(Color.BLACK);
}
if (event.getSource() == Quit) {
Quit.setBackground(Color.lightGray);
Quit.setForeground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
AnOtherLevel.setBackground(Color.white);
AnOtherLevel.setForeground(Color.BLACK);
Quit.setBackground(Color.white);
Quit.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public class HardLevelWindow {
public static void main(String[] args) {
HardWindow win = new HardWindow();
}
}
You can create a Parent class e.g.: BaseGame which is abstract. Like that:
public abstract class BaseGame {
private abstract int[] getStoreCards();
private abstract JButton[] getButtons();
private abstract int[] getCards();
... your other code goes here
}
And then you can create your child classes where you implement these methods, e.g:
public class EasyGame {
#Override
private int[] getStoreCards() {
return new int[16];
}
#Override
private int[] getCards() {
return new int[9];
}
#Override
private JButton[] getButtons() {
return new JButton[16];
}
}
So everywhere in your code where you usually initalize your arrays, use those methods instead.
int[] Button = new int[2];
becomes
getButtons();
You probably want to use an ArrayList, like so:
ArrayList<JButton> buttons = new ArrayList<>();
//...
for (int n = 0; n < boardSize; n++) {
JButton button = new JButton();
buttons.add(button); // add to the end of the expandable list
Center.add(button);
button.addActionListener(this);
button.setBackground(Color.white);
}
where boardSize is a parameter to your constructor specifying the size.

2 Player Checkers Game (Java)

In my Springbreak holiday I started to write Checkers Game. I have created my CheckersBoard but I couldn't write MouseListener part. Can you help me with this part? I'm not pretty sure how to implement this part? Is MouseListener correct? Or should I choose another Listener? I have googled but couldn't any clue.
Thank you so much.
public class CheckersGUI {
private final JPanel gui = new JPanel(new BorderLayout(3, 3));
private JButton[][] Squares = new JButton[8][8];
private JPanel Board;
private final JLabel message = new JLabel(
"Ready to play!");
private static final String COLS = "ABCDEFGH";
private ImageIcon brown = new ImageIcon("brown.jpg");
private ImageIcon red = new ImageIcon("red.png");
CheckersGUI() {
create();
//create ButtonHandler
/* ButtonHandler handler = new ButtonHandler();
for (int i=0; i<Squares.length; i++){
for (int j=0; i<Squares[0].length; i++){
Squares[i][j].addMouseListener(handler);
}
}
}
private class ButtonHandler implements MouseListener{
public void MouseClicked ( MouseEvent event){
}*/
}
public final void create() {
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
gui.add(tools, BorderLayout.PAGE_START);
Action newGameAction = new AbstractAction("New") {
#Override
public void actionPerformed(ActionEvent e) {
setupNewGame();
}
};
tools.add(newGameAction);
// TODO - add functionality!
tools.addSeparator();
tools.add(message);
gui.add(new JLabel(""), BorderLayout.LINE_START);
Board = new JPanel(new GridLayout(0, 9)) ;
Board.setBorder(new CompoundBorder(
new EmptyBorder(8,8,8,8),
new LineBorder(Color.BLACK)
));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(Board);
gui.add(boardConstrain);
// create the chess board squares
Insets buttonMargin = new Insets(0, 0, 0, 0);
for (int ii = 0; ii < Squares.length; ii++) {
for (int jj = 0; jj < Squares[ii].length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
ImageIcon icon = new ImageIcon(
new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.BLACK);
}
Squares[jj][ii] = b;
}
}
/*
* fill the chess board
*/
Board.add(new JLabel(""));
// fill the top row
for (int ii = 0; ii < 8; ii++) {
Board.add(
new JLabel(COLS.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 0; ii < 8; ii++) {
for (int jj = 0; jj < 8; jj++) {
switch (jj) {
case 0:
Board.add(new JLabel("" + (9-(ii + 1)),
SwingConstants.CENTER));
default:
Board.add(Squares[jj][ii]);
}
}
}
}
public final JComponent getGui() {
return gui;
}
/**
* Initializes the icons of the initial chess board piece places
*/
private final void setupNewGame() {
message.setText("Make your move!");
for (int ii = 0; ii < 8; ii++) {
Squares[ii][1].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][2].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][5].setIcon(brown);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][6].setIcon(brown);
}
}
public static void main(String[] args) {
CheckersGUI cg = new CheckersGUI();
JFrame f = new JFrame("Checkers");
f.add(cg.getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
f.setResizable(false);
f.setVisible(true);
}
}
You can add an ActionListener to each button. If the button is pressed (actually, when it is released) the actionPerformed method will be called.
Add the following to your code, to make each square red after it has been clicked:
public static class ButtonHandler implements ActionListener {
private JButton b;
public ButtonHandler(JButton b) {
this.b = b;
}
#Override
public void actionPerformed(ActionEvent e) {
b.setBackground(Color.red);
}
}
This is the handler. Notice that each handler instance will be associated with a button.
Now, create and add a new ButtonHandler to each button after it has been created:
JButton b = new JButton();
...
b.addActionListener(new ButtonHandler(b));
You can change the implementation of actionPerformed.
Example: Add a method getCurrentPlayer() to actionPerformed, then, if the current player is player one, change the color to blue, else, change the color to red.
I trust this will help you to achieve what you need.

Array of JLabels in Jpanel not showing up

So im tearing my hair out at this, I cannot seem to figure out why these JLabels are not drawing to the window. I keep looking at another project Ive done in the past that also used JLabels inside a JPanel and everything seems right. Does anyone see where I am messing this up?
package lab19_20;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class Lab19_20 extends JFrame implements ActionListener, MouseListener
{
JLabel[] lblBoard = new JLabel[16];
int[] nums = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8};
int firstChoice = -1;
int tries = 0;
JLabel lblFirst;
JButton btnGame = new JButton("New Game");
JLabel lblTries = new JLabel("0");
JPanel pnlControls = new JPanel();
JPanel pnlBoard = new JPanel();
Font lblBoardFont = new Font("Helvetica", Font.BOLD, 30);
Container content = this.getContentPane();
public Lab19_20()
{
setTitle("The Concentration Game");
setVisible(true);
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createLabels();
content.add(pnlBoard, BorderLayout.NORTH);
pnlControls.add(btnGame);
pnlControls.add(lblTries);
content.add(pnlControls, BorderLayout.SOUTH);
btnGame.addActionListener(this);
}
void createLabels()
{
pnlBoard.setLayout(new GridLayout(4, 4, 5, 5));
for(int i = 0; i < lblBoard.length; i++)
{
lblBoard[i] = new JLabel("", JLabel.CENTER);
lblBoard[i].setVisible(true);
lblBoard[i].setOpaque(true);
lblBoard[i].setBackground(Color.BLUE);
lblBoard[i].setForeground(Color.BLACK);
lblBoard[i].setFont(lblBoardFont);
lblBoard[i].addMouseListener(this);
lblBoard[i].setName("" + i);
pnlBoard.add(lblBoard[i]);
}
}
void shuffle()
{
int num1, num2, tmp = 0;
Random r = new Random();
for (int i = 0; i < 500; i++)
{
num1 = r.nextInt(nums.length);
num2 = r.nextInt(nums.length);
tmp = nums[num1];
nums[num1] = nums[num2];
nums[num2] = tmp;
}
}
#Override
public void actionPerformed(ActionEvent ae)
{
shuffle();
firstChoice = -1;
for (int i = 0; i < lblBoard.length; i++)
lblBoard[i].setText("");
tries = 0;
lblTries.setText("" + tries);
}
#Override
public void mouseClicked(MouseEvent me)
{
JLabel l = (JLabel) me.getSource();
int theNumber = Integer.parseInt(l.getName());
if (firstChoice == -1)
{
l.setText("" + nums[theNumber]);
lblFirst = l;
firstChoice = theNumber;
}
else if (nums[theNumber] != nums[firstChoice])
{
l.setText("" + nums[theNumber]);
pnlBoard.paintImmediately(0,0, pnlBoard.getWidth(), pnlBoard.getHeight());
try
{
Thread.sleep(250);
}
catch(InterruptedException blah){}
lblFirst.setText("");
l.setText("");
lblFirst = null;
firstChoice = -1;
tries++;
}
else
{
l.setText("" + nums[theNumber]);
firstChoice = -1;
tries++;
}
lblTries.setText("" + tries);
}
public static void main(String[] args)
{
Lab19_20 console = new Lab19_20();
}
#Override public void mousePressed(MouseEvent me) {}
#Override public void mouseReleased(MouseEvent me) {}
#Override public void mouseEntered(MouseEvent me) {}
#Override public void mouseExited(MouseEvent me) {}
}
Two quick things...
Call setVisible(true); last, after you have established the basic UI.
Use lblBoard[i].setText("" + i); instead of (or as well as) lblBoard[i].setName("" + i);

Categories

Resources