EDIT: Having Trouble with Static Variables - java

I am writing a program that is supposed to take the input from two text fields, length and width. It is then supposed to calculate the cost based on the area and type of flooring selected. However, all of the static variables are not being used or updated by my program when I run it. Even when I click my Clear button, all of the fields will clear except ones that are declared static. Could someone please let me know what I'm doing wrong? If I try to remove the static, other classes aren't able to access it.
EDIT: I was able to remove the static declarations so that nothing in this class (Cost) is static. However, I have another class (OrderSummary) that needs to access the getFloorArea(), etc. methods from Cost. It also accesses methods getFirstName(), getLastName, etc. from another class (CustomerInfo). I did some reading and found out that I need to instantiate these classes so that OrderSummary can invoke these methods, I'm just confused as to where to instantiate these classes. In my Main? Or the class that I create the GUI in? I just need all of my information entered in the GUI to displayed in OrderSummary but I can't seem to figure out how to implement it.
I know I'm bad at this but I'm really trying to learn.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import helpers.*;
public class Cost extends JPanel {
static JRadioButton carpet;
static JRadioButton wood;
JButton btnClear;
JButton btnSubmit;
static JTextField enterLength;
static JTextField enterWidth;
JButton btnArea;
JButton btnCost;
JTextField txtArea;
JTextField txtCost;
JLabel length;
JLabel width;
static double woodCost = 20.00;
static double carpetCost = 10.00;
static double floorCost = 0.00;
static double floorLength = 0.00;
static double floorWidth = 0.00;
static double floorArea = 0.00;
static double totalCost = 0.00;
public Cost() {
createPanel();
}
private void createPanel() {
super.setLayout(new GridBagLayout());
GridBagConstraints bag = new GridBagConstraints();
bag.fill = GridBagConstraints.BOTH;
bag.anchor = GridBagConstraints.FIRST_LINE_START;
bag.insets = new Insets(5,5,5,5);
ButtonGroup bg = new ButtonGroup();
bag.gridx = 0;
bag.gridy = 0;
carpet = new JRadioButton("Carpet");
this.add(carpet, bag);
bg.add(carpet);
bag.gridx = 1;
bag.gridy = 0;
wood = new JRadioButton("Wood");
this.add(wood, bag);
bg.add(wood);
bag.gridx = 1;
bag.gridy = 1;
enterLength = new JTextField("0");
this.add(enterLength, bag);
bag.gridx = 0;
bag.gridy = 1;
length = new JLabel("Length");
length.setFont(new Font("Arial", Font.BOLD, 12));
length.setBackground(Color.BLUE);
this.add(length, bag);
bag.gridx = 3;
bag.gridy = 1;
btnArea = new JButton("Area");
btnArea.addActionListener(new AreaHandler());
this.add(btnArea, bag);
bag.gridx = 4;
bag.gridy = 1;
txtArea = new JTextField();
txtArea.setColumns(10);
this.add(txtArea, bag);
bag.gridx = 1;
bag.gridy = 2;
enterWidth = new JTextField("0");
this.add(enterWidth, bag);
bag.gridx = 0;
bag.gridy = 2;
width = new JLabel("Width");
this.add(width, bag);
bag.gridx = 3;
bag.gridy = 2;
btnCost = new JButton("Cost");
btnCost.addActionListener(new CostHandler());
this.add(btnCost, bag);
bag.gridx = 4;
bag.gridy = 2;
txtCost = new JTextField();
this.add(txtCost, bag);
bag.gridx = 4;
bag.gridy = 4;
btnSubmit = new JButton("Submit Order");
btnSubmit.addActionListener(new SubmitHandler());
this.add(btnSubmit, bag);
bag.gridx = 4;
bag.gridy = 5;
btnClear = new JButton("Clear");
btnClear.addActionListener(new ClearHandler());
this.add(btnClear, bag);
}
public static double getFlooringCost() {
if (carpet.isSelected())
floorCost = carpetCost;
if (wood.isSelected())
floorCost = woodCost;
return floorCost;
}
public static double getFloorArea() {
floorLength = Double.parseDouble(enterLength.getText());
floorWidth = Double.parseDouble(enterWidth.getText());
floorArea = floorLength * floorWidth;
return floorArea;
}
public static double getTotalCost() {
totalCost = floorCost * floorArea;
return totalCost;
}
public void setFloorArea(double floorArea) {
if (floorArea >= 0) {
Cost.floorArea = floorArea;
}
else {
JOptionPane.showMessageDialog(null, "Length or Width must be greater than 0.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setTotalCost(double totalCost) {
Cost.totalCost = totalCost;
}
private class AreaHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
txtArea.setText(String.valueOf(getFloorArea()));
}
}
private class CostHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
txtCost.setText(OutputHelpers.formattedCurrency(getTotalCost()));
}
}
private class ClearHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
enterLength.setText("");
enterWidth.setText("");
txtArea.setText("");
txtCost.setText("");
}
}
private class SubmitHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
setFloorArea(getFloorArea());
setTotalCost(getTotalCost());
enterLength.setText("");
enterWidth.setText("");
txtArea.setText("");
txtCost.setText("");
}
}
//class OrderSummary
import javax.swing.*;
import java.awt.*;
import helpers.*;
public class OrderSummary extends JPanel {
JTextArea orderSummary;
public OrderSummary() {
createPanel();
}
private void createPanel() {
super.setLayout(new GridBagLayout());
GridBagConstraints bag = new GridBagConstraints();
bag.fill = GridBagConstraints.BOTH;
bag.anchor = GridBagConstraints.FIRST_LINE_START;
bag.insets = new Insets(5,5,5,5);
bag.gridx = 0;
bag.gridy = 0;
orderSummary = new JTextArea(5, 20);
orderSummary.setFont(new Font("Arial", Font.BOLD, 12));
orderSummary.setBackground(Color.WHITE);
this.add(orderSummary, bag);
//this is where I need to get data from classes Cost and CustomerInfo
orderSummary.setText("Customer Name: " + aCustomerInfo.getFirstName() + " " + aCustomerInfo.getLastName() +
"\nAddress: " + aCustomerInfo.getStreet() + "\n" + aCustomerInfo.getCity() + "\n" + aCustomerInfo.getState() + "\n" + aCustomerInfo.getZip() +
"\n\nTotal Area: " + aCost.getFloorArea() + " square feet" +
"\nCost: " + OutputHelpers.formattedCurrency(aCost.getTotalCost()));
}
}

Related

Transform my Java Swing program to an MVC program?

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.

How does a class call methods after instantiating another class?

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);
}
}

adjust JTextField with JComboBox

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);
}
});
}
}

Retrieving values from fields

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]);
}

NullPointerException in "AWT-EventQueue-0" java.lang

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.

Categories

Resources