1

Trying to get the stop button to give a running total of the numbers when user clicks on start. The stop button will not give me a total or hold the numbers that start gives when you click on it.

What am I doing wrong here?

package com.egroegnosbig.dicerollergui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Fishing {
    public static void main(String[] args) {
        //create Jframe
        JFrame Frame = new JFrame("Fishing Game");

        JPanel panel = new JPanel(new BorderLayout());
        panel.setPreferredSize(new Dimension(600,600));

        //two panels in main panel
        JPanel panelup = new JPanel();
        JPanel paneldown = new JPanel();
        panelup.setBackground(Color.white);

        //title image with word overlay
        ImageIcon pole1 = new ImageIcon("fishingpole.png");
        JLabel title = new JLabel(pole1);
        title.setBounds(150, 0,325,175);
        title.setText("Go Fishing?");
        title.setFont(new Font("Ravie", Font.BOLD, 30));
        title.setForeground(Color.green);
        title.setHorizontalTextPosition(JLabel.CENTER);
        title.setVerticalTextPosition(JLabel.CENTER);
        title.setOpaque(false);
        panelup.add(title);

        panelup.setPreferredSize(new Dimension(600,375));
        panelup.setLayout(null);

        JLabel points = new JLabel("<html>Look what you caught!<br>(click start to keep going)</html> " );
        points.setForeground(Color.blue);
        points.setFont(new Font(null, Font.BOLD, 20));
        points.setBounds(10,150, 450, 100);
        panelup.add(points);

        JTextField caught = new JTextField(20);
        caught.setSize(10,10);
        caught.setFont(new Font("Times New Roman", Font.BOLD, 15));
        caught.setForeground(Color.RED);
        caught.setBounds(10,230,350,30);
        panelup.add(caught);

        JTextField total = new JTextField(20);
        total.setSize(10,10);
        total.setFont(new Font("Times New Roman", Font.BOLD, 15));
        total.setForeground(Color.RED);
        total.setBounds(325,315,150,30);
        panelup.add(total);

        ** This is the stop button**
        JLabel End = new JLabel("<html>All Done?! Press Stop and Let's<br>see how well you did!<html>" );
        End.setForeground(Color.blue);
        End.setFont(new Font(null, Font.BOLD, 20));
        End.setBounds(10, 310, 325, 50);
        panelup.add(End);

        JTextField single = new JTextField(20);
        single.setSize(10,10);
        single.setFont(new Font("Times New Roman", Font.BOLD, 15));
        single.setForeground(Color.RED);
        single.setBounds(10,275,100,30);
        panelup.add(single);

        //Label for asking user to continue
        ImageIcon bobber = new ImageIcon("bobber2.jpg");
        JButton start = new JButton(bobber);
        start.setBorderPainted(false);
        start.setBounds(350, 170,100,100);
        start.setText("Start!");
        start.setFont(new Font("Serif", Font.BOLD, 20));
        start.setForeground(Color.black);
        start.setHorizontalTextPosition(JLabel.CENTER);
        start.setVerticalTextPosition(JLabel.CENTER);
        start.setOpaque(false);
        panelup.add(start);

        ImageIcon bobber2 = new ImageIcon("bobber2.jpg");
        JButton stop= new JButton(bobber2);
        stop.setBorderPainted(false);
        stop.setBounds(450, 170,100,100);
        stop.setText("Stop!");
        stop.setFont(new Font("Serif", Font.BOLD, 25));
        stop.setForeground(Color.black);
        stop.setHorizontalTextPosition(JLabel.CENTER);
        stop.setVerticalTextPosition(JLabel.CENTER);
        stop.setOpaque(false);
        panelup.add(stop);

        start.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    double input = 0;
                    int count = 0 ;
                    int points2 = 0;
                    int die;
                    die = (int)(Math.random()*6) + 1;

                    if (die == 1)
                    {
                        caught.setText("Winner winner fish fry dinner! Catfish ");
                        points2 =  10;
                    }
                    if (die == 2)
                    {
                        caught.setText("Nemo! Go straight to Jail. ");
                        points2 = 15;
                    }
                    if (die == 3)
                    {
                        caught.setText("Stinky shoe boohoo! ");
                        points2 = 5;
                    }
                    if (die == 4)
                    {
                        caught.setText("Whale of a fish, BIG TUNA ");
                        points2 = 30;
                    }
                    if (die == 5)
                    {
                        caught.setText("Yumm Yumm Bass Pro");
                        points2 = 25;
                    }
                    if (die == 6)
                    {
                        caught.setText("Is that a toilet bowl seat!? ");
                        points2 = 10;
                    }

                    count += points2;

                    single.setText(points2 + "");
                    {
                    }
                }
            }
        );

        stop.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    int total2 = 0;
                    int totalpoints =0;

                    totalpoints += total2;

                    total2 = Integer.parseInt(single.getText());
                    totalpoints += total2;
                    total.setText(""+ totalpoints);
                }
            }
        );

        //paneldown image
        ImageIcon water = new ImageIcon("water.jpg");
        JLabel pic = new JLabel(water);    
        paneldown.add(pic, BorderLayout.SOUTH);

        //panel positioning
        panel.add(panelup, BorderLayout.NORTH);
        panel.add(paneldown, BorderLayout.SOUTH);

        //set frame with panel
        Frame.add(panel);
        Frame.pack();
        Frame.setLocationRelativeTo(null);
        Frame.setSize(600,600);
        Frame.setVisible(true);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
  • Because you are not saving the result. Some member variables will be required to save the total. – MikeCAT May 05 '16 at 02:49
  • My 3rd language is English so sorry if this does not make the sense, but i think that is why i put in the stop actionListener to a total and set to zero inorder to have a running total. I want them to be added and then display it when you click stop button. – Erick FromDlions May 05 '16 at 02:53
  • Your code formatting including indentations and blank lines are all over the place making your code hard to follow. Please look up and try to follow Java code formatting rules. By following these rules, others will more easily be able to read and understand your code, and then be able to help you. If you are using most IDE's they can help you format your code correctly for you. – Hovercraft Full Of Eels May 05 '16 at 02:57
  • 1
    "0 + 0 = 0" Your variables are local to the ActionListener and always 0 – MadProgrammer May 05 '16 at 02:58
  • @MadProgrammer thank you for your help friend i will try this, – Erick FromDlions May 05 '16 at 03:12
  • @HovercraftFullOfEels i will go back a redo sorry about the bad ethics, will get better for future! – Erick FromDlions May 05 '16 at 03:12

2 Answers2

0

Every time that you click the stop button you are recreating the totalpoints variable and setting it to zero. Move this variable outside of the action listener and you won't have this problem.

CVarg
  • 69
  • 10
0

This is a problem of variable scope. By simply moving the variables to a place with more visible scope, they can be accessed by more methods (simply put)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Fishing {

public static void main(String[] args) {
    // This is where the variables got moved to
    final int[] total2 = {
            0
    };
    final int[] totalpoints = {
            0
    };

    //create Jframe
    JFrame Frame = new JFrame("Fishing Game");
    Frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    JPanel panel = new JPanel(new BorderLayout());
    panel.setPreferredSize(new Dimension(600, 600));

    //two panels in main panel
    JPanel panelup = new JPanel();
    JPanel paneldown = new JPanel();
    panelup.setBackground(Color.white);

    //title image with word overlay
    ImageIcon pole1 = new ImageIcon("fishingpole.png");
    JLabel title = new JLabel(pole1);
    title.setBounds(150, 0, 325, 175);
    title.setText("Go Fishing?");
    title.setFont(new Font("Ravie", Font.BOLD, 30));
    title.setForeground(Color.green);
    title.setHorizontalTextPosition(JLabel.CENTER);
    title.setVerticalTextPosition(JLabel.CENTER);
    title.setOpaque(false);
    panelup.add(title);

    panelup.setPreferredSize(new Dimension(600, 375));
    panelup.setLayout(null);


    JLabel points = new JLabel("<html>Look what you caught!<br>(click start to keep going)</html> ");
    points.setForeground(Color.blue);
    points.setFont(new Font(null, Font.BOLD, 20));
    points.setBounds(10, 150, 450, 100);
    panelup.add(points);

    JTextField caught = new JTextField(20);
    caught.setSize(10, 10);
    caught.setFont(new Font("Times New Roman", Font.BOLD, 15));
    caught.setForeground(Color.RED);
    caught.setBounds(10, 230, 350, 30);
    panelup.add(caught);

    JTextField total = new JTextField(20);
    total.setSize(10, 10);
    total.setFont(new Font("Times New Roman", Font.BOLD, 15));
    total.setForeground(Color.RED);
    total.setBounds(325, 315, 150, 30);
    panelup.add(total);

    // STOP BUTTON
    JLabel End = new JLabel("<html>All Done?! Press Stop and Let's<br>see how well you did!<html>");
    End.setForeground(Color.blue);
    End.setFont(new Font(null, Font.BOLD, 20));
    End.setBounds(10, 310, 325, 50);
    panelup.add(End);

    JTextField single = new JTextField(20);
    single.setSize(10, 10);
    single.setFont(new Font("Times New Roman", Font.BOLD, 15));
    single.setForeground(Color.RED);
    single.setBounds(10, 275, 100, 30);
    panelup.add(single);


    //Label for asking user to continue
    ImageIcon bobber = new ImageIcon("bobber2.jpg");
    JButton start = new JButton(bobber);
    start.setBorderPainted(false);
    start.setBounds(350, 170, 100, 100);
    start.setText("Start!");
    start.setFont(new Font("Serif", Font.BOLD, 20));
    start.setForeground(Color.black);
    start.setHorizontalTextPosition(JLabel.CENTER);
    start.setVerticalTextPosition(JLabel.CENTER);
    start.setOpaque(false);
    panelup.add(start);

    ImageIcon bobber2 = new ImageIcon("bobber2.jpg");
    JButton stop = new JButton(bobber2);
    stop.setBorderPainted(false);
    stop.setBounds(450, 170, 100, 100);
    stop.setText("Stop!");
    stop.setFont(new Font("Serif", Font.BOLD, 25));
    stop.setForeground(Color.black);
    stop.setHorizontalTextPosition(JLabel.CENTER);
    stop.setVerticalTextPosition(JLabel.CENTER);
    stop.setOpaque(false);
    panelup.add(stop);


    start.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            double input = 0;
            int count = 0;
            int points2 = 0;
            int die;
            die = (int) (Math.random() * 6) + 1;

            if (die == 1) {
                caught.setText("Winner winner fish fry dinner! Catfish ");
                points2 = 10;

            }
            if (die == 2) {
                caught.setText("Nemo! Go straight to Jail. ");
                points2 = 15;
            }

            if (die == 3) {
                caught.setText("Stinky shoe boohoo! ");
                points2 = 5;
            }
            if (die == 4) {
                caught.setText("Whale of a fish, BIG TUNA ");
                points2 = 30;

            }
            if (die == 5) {
                caught.setText("Yumm Yumm Bass Pro");
                points2 = 25;
            }
            if (die == 6) {
                caught.setText("Is that a toilet bowl seat!? ");
                points2 = 10;
            }

            count += points2;

            single.setText(points2 + "");
            totalpoints[0] += points2;
        }
    });

    stop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                total2[0] = Integer.parseInt(single.getText());
            } catch (NumberFormatException ee) {
                // If there is a blank input from single.getText();, then make total2 zero to avoid larger errors
                total2[0] = 0; // Another way to handle the exception
            }
            total.setText("" + totalpoints[0]);
        }

    });


    //paneldown image
    ImageIcon water = new ImageIcon("water.jpg");
    JLabel pic = new JLabel(water);
    paneldown.add(pic, BorderLayout.SOUTH);

    //panel positioning
    panel.add(panelup, BorderLayout.NORTH);
    panel.add(paneldown, BorderLayout.SOUTH);


    //set frame with panel
    Frame.add(panel);
    Frame.pack();
    Frame.setLocationRelativeTo(null);
    Frame.setSize(600, 600);
    Frame.setVisible(true);
}
}

The reason why I turned the variables into an array is because the variables are being accessed from an inner class they need to be declared final or effectively final. Read more on this post (here)

By the way, (IMHO) your initial code was formatted horrifically. If you're going to post a large chunk of code please be mindful that somebody other than you has to read it, because even my IDE's auto formatter couldn't fix this.

EDIT: Updated code to include extra statements to add functionality. EDIT 2: Updated code to handle the exceptions in a better way

Community
  • 1
  • 1
BitShuffler
  • 103
  • 1
  • 8
  • ok this made the stop button work but when you click on the stop button it now just adds what is in start, i need it for the user to click start as many times as they want and the when stop is clicked it gives total, this method does give a total but does not hold previous numbers given – Erick FromDlions May 05 '16 at 03:11
  • I fixed the code. Not sure what you're asking but I think this is along the lines of what you're saying – BitShuffler May 05 '16 at 03:18
  • yes this code is almost there i see what you have done, and thank you for your patience and understanding! but i do not want the total when pressing start to show how much the user has accumulated in the all done box, until you press stop. The program now adds correctly so thank you for that but when you press stop it adds the points to the total again. This is the problem i have not been able to fix – Erick FromDlions May 05 '16 at 03:36
  • i am forever in you debt my friend i have take more advil then a human should consume because of this program, everyone in class said to stop trying to make original program, but i knew someone could help thank you once again and God Bless you man! – Erick FromDlions May 05 '16 at 03:45
  • Good luck with your code, if my answer works for you be sure to mark it as correct :) – BitShuffler May 05 '16 at 03:45
  • in the portion of the stop button , why did you use a try and what does the catch variable do ? i have never seen this catch used. – Erick FromDlions May 05 '16 at 04:12
  • the "try catch" is a statement, used to handle exceptions. Because you are parsing strings into integers it is good practice to provide exception handling to avoid error messages if the strings cannot be correctly parsed (in this case they handle a numberformatexception). See this for a more general explanation [try catch finally](https://en.wikipedia.org/wiki/Exception_handling_syntax#Java). If you tried hitting stop in your original code it will result in a numberformatexception. – BitShuffler May 05 '16 at 12:29
  • If you tried hitting stop before hitting start that is. See the updated code for better error handling – BitShuffler May 05 '16 at 12:39