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.
I am very new to this community. I have tried to get up to speed on all rules before posting this question (as well as researching solutions). I apologize if I offended or broke any rules through ignorance. Please also excuse my awful code, I am still learning. Thank you for understanding!
EDIT: I have added additional information and tried different approaches to this issue I'm having. I have reworked part of the code below.
I am building a simple football game with a game field panel and control panel. The game field displays all of the player and tackles on the GUI. The control panel sets the difficulty of the game, starts the timer, and the type of quarterback. I ran into a road block where I have all of my code to compile correctly, but when calling set methods on the GameField class to update the score, it updates the variable but not the actual score through my JTextArea Score keeper.
I have instantiated the ControlPanel within the GameField class. I've also tested with a System.out.println() and it shows that it is indeed updating the variable. Is updating JTextArea allowed between classes?
GameField.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GameField extends JPanel implements KeyListener {
ControlPanel cp = new ControlPanel();
// Game pieces
private JButton playerIcon = new JButton("RB");
private JButton tackleIcon1 = new JButton("LB");
private JButton tackleIcon2 = new JButton("LB");
private JButton fieldGoal = new JButton("FG");
// Player and Tackle locations
private int playerPositionX = 100;
private int playerPositionY = 500;
private int tackle1PositionX = 1200;
private int tackle1PositionY = 400;
private int tackle2PositionX = 1200;
private int tackle2PositionY = 600;
// Player variable speeds
private int playerSpeed = 20;
public GameField() {
setLayout(null);
setBackground(Color.green);
add(playerIcon);
playerIcon.setBounds(new Rectangle(getPlayerPositionX(), getPlayerPositionY(), 80, 30));
add(tackleIcon1);
tackleIcon1.setBounds(new Rectangle(getTackle1PositionX(), getTackle1PositionY(), 100, 50));
add(tackleIcon2);
tackleIcon2.setBounds(new Rectangle(getTackle2PositionX(), getTackle2PositionY(), 100, 50));
add(fieldGoal);
fieldGoal.setBounds(new Rectangle(1600, 100, 100, 800));
playerIsTackled();
setFocusable(true);
addKeyListener(this);
}
public void playerIsTackled() {
Rectangle playerRect = playerIcon.getBounds();
Rectangle tackle1Rect = tackleIcon1.getBounds();
Rectangle tackle2Rect = tackleIcon2.getBounds();
if (playerRect.intersects(tackle1Rect) || playerRect.intersects(tackle2Rect)) {
setPlayerPositionX(100);
setPlayerPositionY(500);
setTackle1PositionX(1200);
setTackle1PositionY(400);
setTackle2PositionX(1200);
setTackle2PositionY(600);
playerIcon.setBounds(getPlayerPositionX(), getPlayerPositionY(), 80, 30);
tackleIcon1.setBounds(getTackle1PositionX(), getTackle1PositionY(), 100, 50);
tackleIcon2.setBounds(getTackle2PositionX(), getTackle2PositionY(), 100, 50);
cp.setCurrentTackles(cp.getCurrentTackles() + 1);
System.out.println(cp.getCurrentTackles());
}
}
public void playerScored() {
Rectangle playerRect = playerIcon.getBounds();
Rectangle fieldGoalRect = fieldGoal.getBounds();
if (playerRect.intersects(fieldGoalRect)) {
setPlayerPositionX(100);
setPlayerPositionY(500);
setTackle1PositionX(1200);
setTackle1PositionY(400);
setTackle2PositionX(1200);
setTackle2PositionY(600);
playerIcon.setBounds(getPlayerPositionX(), getPlayerPositionY(), 80, 30);
tackleIcon1.setBounds(getTackle1PositionX(), getTackle1PositionY(), 100, 50);
tackleIcon2.setBounds(getTackle2PositionX(), getTackle2PositionY(), 100, 50);
cp.setCurrentScore(cp.getCurrentScore() + 1);
System.out.println(cp.getCurrentScore());
}
}
public void moveToPlayer() {
if (getTackle1PositionX() > getPlayerPositionX()) {
setTackle1PositionX(getTackle1PositionX() - 1);
} else {
setTackle1PositionX(getTackle1PositionX() + 1);
}
if (getTackle1PositionY() > getPlayerPositionY()) {
setTackle1PositionY(getTackle1PositionY() - 1);
} else {
setTackle1PositionY(getTackle1PositionY() + 1);
}
getTackleIcon1().setBounds(getTackle1PositionX(), getTackle1PositionY(), 100, 50);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
requestFocusInWindow();
playerIsTackled();
playerScored();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
if (k == e.VK_LEFT && getPlayerPositionX() > 0) {
setPlayerPositionX(getPlayerPositionX() - getPlayerSpeed());
}
if (k == e.VK_RIGHT && getPlayerPositionX() < 1703) {
setPlayerPositionX(getPlayerPositionX() + getPlayerSpeed());
}
if (k == e.VK_UP && getPlayerPositionY() > 0) {
setPlayerPositionY(getPlayerPositionY() - getPlayerSpeed());
}
if (k == e.VK_DOWN && getPlayerPositionY() < 1089) {
setPlayerPositionY(getPlayerPositionY() + getPlayerSpeed());
}
getPlayerIcon().setBounds(getPlayerPositionX(), getPlayerPositionY(), 80, 30);
}
Below is the ControlPanel.java. In the actionPerformed method, you can see I added a getScore().setText() method for updating the score. It correctly updates the score there if I replace the getCurrentScore() method with any integer.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Hashtable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ControlPanel extends JPanel implements ActionListener, ChangeListener {
private JButton start;
private JButton stop;
private JSlider speed;
private JComboBox playerList;
private Timer tim;
private int delay = 1000;
private int i = 0;
private int currentScore = 0;
private int currentTackles = 0;
private JTextArea timer = new JTextArea("Timer: " + 0, 1, 6);
private JTextArea score = new JTextArea("Field Goals: " + currentScore + " Tackles: " + currentTackles, 1, 16);
private String[] playerStyle = {"Slow Runner", "Running Back", "All Star"};
public ControlPanel() {
super();
setBackground(Color.darkGray);
// Game controls
start = new JButton("Start");
stop = new JButton("Stop");
speed = new JSlider(JSlider.HORIZONTAL, 0, 2, 1);
playerList = new JComboBox(getPlayerStyle());
// Slider label
Hashtable labelTable = new Hashtable();
labelTable.put(new Integer(0), new JLabel("Slow"));
labelTable.put(new Integer(1), new JLabel("Normal"));
labelTable.put(new Integer(2), new JLabel("Fast"));
speed.setLabelTable(labelTable);
speed.setPaintLabels(true);
// Combo box dropdown
playerList.setSelectedIndex(1);
// Timer
tim = new Timer(getDelay(), this);
// Add methods
add(start);
add(stop);
add(timer);
add(speed);
add(score);
add(playerList);
// Event listeners
start.addActionListener(this);
stop.addActionListener(this);
speed.addChangeListener(this);
playerList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String playerChoice = (String) cb.getSelectedItem();
playerList.setSelectedItem(playerChoice);
}
});
// Set focus to false on all game controls
start.setFocusable(false);
stop.setFocusable(false);
speed.setFocusable(false);
playerList.setFocusable(false);
}
#Override
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if (obj == getTim()) {
setI(getI() + 1);
getTimer().setText("Timer: " + getI());
getScore().setText("Field Goals: " + getCurrentScore() + " Tackles: " + getCurrentTackles());
}
if (obj == getStop()) {
getTim().stop();
}
if (obj == getStart()) {
getTim().start();
}
}
#Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
int currentSpeed = (int) source.getValue();
if (currentSpeed == 0) {
int delaySpeed = getTim().getDelay();
delaySpeed = (int) 2000;
getTim().setDelay(delaySpeed);
}
if (currentSpeed == 1) {
int delaySpeed = getTim().getDelay();
delaySpeed = (int) 1000;
getTim().setDelay(delaySpeed);
}
if (currentSpeed == 2) {
int delaySpeed = getTim().getDelay();
delaySpeed = (int) 500;
getTim().setDelay(delaySpeed);
}
}
MyJPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJPanel extends JPanel {
public MyJPanel() {
super();
setBackground(Color.gray);
setLayout(new BorderLayout());
ControlPanel gm = new ControlPanel();
GameField gf = new GameField();
add(gm, "North");
add(gf, "Center");
}
}
Thanks to #D.B. I have gotten my code to run as intended. Because I only intend to have two JPanels (Control Panel and Game Panel), I added the panels to pass as arguments to each other. After this, the code started working as intended. Thank you for pushing me into the right step! It was such a simple mistake. Special thanks to #DaveyDaveDave for motivating me to push harder!
Changes I made to my main JPanel object:
public class MyJPanel extends JPanel {
ControlPanel gm = new ControlPanel();
GameField gf = new GameField();
public MyJPanel() {
super();
setBackground(Color.gray);
setLayout(new BorderLayout());
add(gm, "North");
add(gf, "Center");
gf.setCp(gm);
gm.setGf(gf);
}
}
Please some one can told me why I don't have the JTextField in the same line with my JComboBox ?
I need to have like that:
myJComboBox1 JTextField1
JTextField2
myJComboBox2 JTextField1
JTextField2
following this example
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
public DisplayPanel(){
super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000,500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents(){
box = new JComboBox[3];
field1 = new JTextField[4];
field2 = new JTextField[5];
}
private void initComponents(){
setLayout(new GridLayout(0, 2));
for(int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] =new JComboBox<>(new String[] { "field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener(box[i]));
}
}
private Component createPanelWithTextFields(JPanel panel) {
//need to keep the same layout as JComboBox
panel.setLayout(new GridLayout(0, 1));
for(int x=0; x<4; x++){
field1[x] = new JTextField("field1 Name " + (x+1));
field1[x].setVisible(false);
panel.add(field1[x]);
}
for(int x=0; x<5; x++){
field2[x] = new JTextField("field2 Name " + (x+1));
field2[x].setVisible(false);
panel.add(field2[x]);
}
return panel;
}
class CustomActionListener implements ActionListener {
JComboBox b;
public CustomActionListener(JComboBox u) {
super();
this.b = u;
}
public void actionPerformed(ActionEvent e) {
int numChosen = b.getSelectedIndex() + 1;
switch (numChosen){
case 1:
for(int x=0; x<4; x++)
field1[x].setVisible(true);
break;
case 2:
for(int x=0; x<5; x++)
field2[x].setVisible(true);
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new DisplayPanel().setVisible(true);
}
});
}
you are assigning new textfield to textfield array.but it contain only 4 textfields.but you call assigning more than 4 times.so what happening is last rextfield references get reassigning and you can't use them again.at the end of the the loop your field array contain reference to textfields of last panel.and that's why your see textfields on last panel even you select from combobox1.
how to fix ?
change this
field1 = new JTextField[4];
to this
field1 = new JTextField[4 * 3];
and then you don't need to reassign jtextfields .you have 3 panels and you have 4 textfields for each panel.
same for field2
here is an example .
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
Color col[] = {Color.red, Color.GREEN, Color.blue};
int i = 0;
int counter = 0;
private int boxcount;
int field1counter = 0;
int field2counter = 0;
public DisplayPanel() {
//super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000, 500);
//setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents() {
boxcount = 3;
box = new JComboBox[1 * boxcount];
field1 = new JTextField[4 * boxcount];
field2 = new JTextField[5 * boxcount];
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] = new JComboBox<>(new String[]{"field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener());
}
}
private Component createPanelWithTextFields(JPanel panelc) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBackground(col[i]);
System.out.println("......................");
for (int x = 0; x < 4; x++) {
System.out.println("iterating .." + (field1counter) + " counter " + counter);
field1[field1counter] = new JTextField("field1 Name " + (x + 1));
field1[field1counter].setVisible(false);
panel.add(field1[field1counter]);
field1counter++;
}
for (int x = 0; x < 5; x++) {
field2[field2counter] = new JTextField("field2 Name " + (x + 1));
field2[field2counter].setVisible(false);
panel.add(field2[field2counter]);
field2counter++;
}
i++;
counter++;
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox) e.getSource();
int comboidenty = 0;
for (int k = 0; k < box.length; k++) {
if (box[k] == b) {
break;
}
comboidenty++;
}
System.out.println(((JPanel) (b.getParent())).getBackground());
int numChosen = b.getSelectedIndex() + 1;
System.out.println("hi " + comboidenty);
switch (numChosen) {
case 1:
for (int x = 0; x < 4; x++) {
System.out.println("field1 " + (comboidenty * 4 + x));
field1[comboidenty * 4 + x].setVisible(true);
}
break;
case 2:
for (int x = 0; x < 5; x++) {
System.out.println("field2 " + (comboidenty * 5 + x));
field2[comboidenty * 5 + x].setVisible(true);
}
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DisplayPanel().setVisible(true);
}
});
}
}
I cannot seem to retrieve the values from each of the fields created. I currently in my actionPerformed() method have f set to 1, but I would like to retrieve the values from all the created fields. It may be the case that not all fields are used.
Please see code below
package classes;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Classes extends JFrame implements ActionListener {
private JTextField ivol, fvol;
private JLabel ilabel, flabel;
private JButton button;
private final JTextField vol1HH[] = new JTextField[10];
private final JLabel vollabel[] = new JLabel[10];
private int f;
public static void main(String[] args) {
Classes RV = new Classes();
RV.setSize(1000, 1200);
RV.createGUI();
RV.setVisible(true);
double sum = add((double) 10, (double) 20.1, (double) 30.1, (double) 40.1);
System.out.println(sum);
}
public static int add(Double... numbers) {
int result = 0;
for (Double number : numbers) {
result += number;
}
return result;
}
public void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(null);
ivol = new JTextField(20);
ivol.setBounds(150, 50, 100, 20);
fvol = new JTextField(20);
fvol.setBounds(150, 1000, 100, 20);
ilabel = new JLabel("Initial Order Volume");
ilabel.setBounds(10, 50, 150, 20);
flabel = new JLabel("Final Order Volume");
flabel.setBounds(10, 1000, 150, 20);
button = new JButton("Remaning Volume");
button.setBounds(10, 1050, 150, 20);
button.addActionListener(this);
window.add(ivol);
window.add(fvol);
window.add(ilabel);
window.add(flabel);
window.add(button);
for (int y = 100; y < 1000; y += 50) {
for (int f = 0; f < 10; f++) {
vol1HH[f] = new JTextField(10);
vol1HH[f].setName("volHH" + f);
vollabel[f] = new JLabel("HH34");
vol1HH[f].setBounds(150, y, 100, 20);
vollabel[f].setBounds(80, y, 100, 20);
window.add(vol1HH[f]);
window.add(vollabel[f]);
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
//double vol;
f = 1;
double vol = Double.parseDouble(vol1HH[f].getText());
//if(e.getSource() == button) {
fvol.setText(Double.toString(vol));
}
}
If you want to retrieve all records from textfields and store it some where. You need to have a variable for storing.
public class Classes extends JFrame implements ActionListener {
//Your other variable declarations
String [] fieldRecords = new String[10]; //Declare array for storing textfields' data
}
Now, simply create a method to transfer all input be it empty of filled into the fieldRecords[].
public void retrieve(){
for(int x=0; x<vol1HH.length; x++)
fieldRecords[x] = vol1HH[x].getText();
}
When ever you need to retrieve your records, simply call retrieve(). For example when you press the button - hence you can place it in the actionPerformed().
public void actionPerformed(ActionEvent e) {
//Your other actions..
retrieve(); //Send all textfield data into fieldRecord[]
}
With the data saved into the array. You can print it or set it back onto the textfields any time you need.
Example:
public void display(){
for(int x=0; x<fieldRecords.length; x++)
System.out.println(fieldRecords[x]);
}
public void load(){
for(int x=0; x<vol1HH.length; x++)
vol1HH.setText(fieldRecords[x]);
}
Hey all I am making a flight booking system and having this error when I click a seat for booking "AWT-EventQueue-0" java.lang.NullPointerException I think there is a mistake with my 2D Object initialization...
PS: is there a way I can get rid of the final in front of Seats[][] seats = new Seats[4][5];
Here is my Seats Class:
public class Seats {
private int row_number;
private boolean booked;
private Passenger myPassenger;
private String seat_name;
private String type;
private int column_number;
private long booking_nr;
public Seats(){
myPassenger = new Passenger();
booked = false;
}
public boolean isBooked() {
return booked;
}
public void setBooked(boolean booked) {
this.booked = booked;
}
}
and below is my GUI:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Book_GUI extends JFrame {
//private EconomyClass eco;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Book_GUI frame = new Book_GUI();
frame.setTitle("Economy Class");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
int left = 3;
int middle = 3;
int right = 4;
String[] singleRowAll = new String [left+middle+right];
for(int i = 1;i<singleRowAll.length;i++){singleRowAll[i] = "";}
singleRowAll[0] = "Window";
singleRowAll[left-1] = "Aisle";
singleRowAll[left] = "Aisle";
singleRowAll[left+middle-1] = "Aisle";
singleRowAll[left+middle] = "Aisle";
singleRowAll[left+middle+right-1] = "Window";
//eco = new EconomyClass(4,5,3,3,4);
final Seats[][] seats = new Seats[4][10];
for ( int i = 0; i < 4; i++) {
char c= 'A';
for ( int j = 0; j < 10; j++) {
final int x = i;
final int z = j;
final JButton btnBookFlight = new JButton(" " + (i+1) + c++ + " " + singleRowAll[j] );
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(seats[x][z].isBooked()){btnBookFlight.setBackground(Color.GREEN);}
seats[x][z].setBooked(true);
//JButton button = (JButton)arg0.getSource();
//button.setBackground(Color.RED);
// btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
}
});
contentPane.add(btnBookFlight);
}
}
contentPane.setLayout(new GridLayout(4, 10));
pack();
}
}
Thank you for reading and for your time!
You are not initializing the Seats[][] array. Try replacing the Constructor of Book_GUI.java with:
public Seats[][] seats = new Seats[4][10];
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
int left = 3;
int middle = 3;
int right = 4;
String[] singleRowAll = new String[left + middle + right];
for (int i = 1; i < singleRowAll.length; i++) {
singleRowAll[i] = "";
}
singleRowAll[0] = "Window";
singleRowAll[left - 1] = "Aisle";
singleRowAll[left] = "Aisle";
singleRowAll[left + middle - 1] = "Aisle";
singleRowAll[left + middle] = "Aisle";
singleRowAll[left + middle + right - 1] = "Window";
// eco = new EconomyClass(4,5,3,3,4);
//Delete this line:
//final Seats[][] seats = new Seats[4][5];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 5; j++) {
seats[i][j] = new Seats();
}
}
for (int i = 0; i < 4; i++) {
char c = 'A';
for (int j = 0; j < 10; j++) {
final int x = i;
final int z = j;
final JButton btnBookFlight = new JButton(" " + (i + 1) + c++
+ " " + singleRowAll[j]);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (seats[x][z].isBooked()) {
btnBookFlight.setBackground(Color.GREEN);
}
seats[x][z].setBooked(true);
// JButton button = (JButton)arg0.getSource();
// button.setBackground(Color.RED);
// btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
}
});
contentPane.add(btnBookFlight);
}
}
contentPane.setLayout(new GridLayout(4, 10));
pack();
}
This should help :)
You are creating a new seat array, using new Seats[4][5], but that simply makes an empty array of references. you need to actually create a new seat that goes in each place in the array.