简体   繁体   中英

ActionListener & a method can't “see” JTextFields

A little background on the code. I'm a student currently on summer vacation and I wanted to play around with my programming skills. I wrote a simple GUI program that calculates nutritional needs for weightlifters. The program worked fully.

I then expanded my code to create a Tabbed Pane. The third tab of the program is the code from my original nutrition program. Now the code doesn't work. Specifically the nested class for the ActionListener and a method I wrote to calculate the nutritional values can't resolve the JTextField code entries from the constructor. I can remove the ActionListener and the actionTakenMethod and the rest of the code works (It's not pretty, but it works).

I appreciate any help I can get with this issue. I would keep in mind two things. First, the code I used from my original program worked, so this issue didn't crop up until I added the code to the tabbed pane. Second, I'm still an undergraduate student so my code is perhaps not the prettiest! Thanks!

Also, my program is not finished so the first two tabs have nothing in them.

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

public class GatesFiveByFive extends JFrame{

    public GatesFiveByFive(){

        //Title of window
        setTitle("Gates 5x5");

        //Size of window
        setSize(500,500);

        //Set Default Close Operation
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set Panel Visible
        setVisible(true);

        //JTabbedPane object declaration
        JTabbedPane jtp=new JTabbedPane();

        //creates the content pane
        getContentPane().add(jtp);

        //First Tab
        JPanel tab1=new JPanel();

        //Second Tab
        JPanel tab2=new JPanel();

        //Third Tab
        JPanel tab3=new JPanel();

        //Add Tab 1 to Content Pane
        jtp.addTab("     5x5     ",tab1);

        //Add Tab 2 to Content Pane
        jtp.addTab("     HST     ",tab2);

        //Add Tab 3 to Content Pane
        jtp.addTab(" Nutrition ",tab3);

        /**Adds content to the First Tab pane*/

        /**Adds content to the Second Tab pane*/

        /**Adds content to Third Tab pane*/

        JButton calculate;//display calculate button

        JLabel weight;
        JLabel weight1;
        JLabel totalCalories;
        JLabel protein;
        JLabel fats;
        JLabel carbs;

        JTextField weightField;
        JTextField totalCaloriesField;
        JTextField proteinField;
        JTextField fatsField;
        JTextField carbsField;

        //Create five labels
        weight=new JLabel("Enter your weight:");
        weight1=new JLabel("");
        totalCalories=new JLabel("Total Calories");
        protein=new JLabel("Protein");
        fats=new JLabel("Fats");
        carbs=new JLabel("Carbs");

        //Create five text fields
        weightField=new JTextField(20);
        totalCaloriesField=new JTextField(20);
        proteinField=new JTextField(20);
        fatsField=new JTextField(20);
        carbsField=new JTextField(20);

        //Create "calculate" button
        calculate=new JButton("Calculate");

        //Register "calculate" button
        calculate.addActionListener(new CalculateButtonListener());

        //Populate Tab 3
        tab3.setLayout(new GridLayout(6,2));
        tab3.add(weight);
        tab3.add(weight1);
        tab3.add(weightField);
        tab3.add(calculate);
        tab3.add(totalCalories);
        tab3.add(totalCaloriesField);
        tab3.add(protein);
        tab3.add(proteinField);
        tab3.add(fats);
        tab3.add(fatsField);
        tab3.add(carbs);
        tab3.add(carbsField);


    }//end constructor GatesFiveByFive

    /**Private inner class for event handler CalculateButtonListener*/
    private class CalculateButtonListener implements ActionListener{

        public void actionPerformed(ActionEvent e){

            actionTakenMethod(weightField.getText());     


        }//end actionPerformed method

    }//end CalculateButtonListener inner class

    /**method for calculating tab 3 stats*/      
    public void actionTakenMethod(String currentWeight){

        /**Convert String input to double for processing*/
        double x=Double.parseDouble(currentWeight);

        /**Calculations for finding macronutrient stats*/
        double cal=14.183*x+500; //total calories
        double pro=0.886*x; //protein
        double fat=0.39397*x; //fats
        double carb=1.7733175*x; //carbs

        /**Convert results of calculations back to string for display*/
        String calCal=Double.toString(cal);
        String proPro=Double.toString(pro);
        String fatFat=Double.toString(fat);
        String carbCarb=Double.toString(carb);

        /**Display results of calculation*/
        totalCaloriesField.setText(calCal);
        proteinField.setText(proPro);
        fatsField.setText(fatFat);
        carbsField.setText(carbCarb);

    }//end actionTakenMethod

    public static void main(String[]args){

        GatesFiveByFive gates=new GatesFiveByFive();

    }//end main

}// end GatesFiveByFive.java

Those variables are local to the constructor. Declare your JLabel s and JTextField s outside your constructor. That is, make them private instance fields of the GatesFiveByFive class. Your ActionListener is an inner class, so it will still have access to those fields of the outer class.

You've created variables that are local to the constructor. You should make them instance variables so they are accessible by any methods in the class.

public class GatesFiveByFive extends JFrame{
    JButton calculate;//display calculate button

    JLabel weight;
    JLabel weight1;
    JLabel totalCalories;
    JLabel protein;
    JLabel fats;
    JLabel carbs;

    JTextField weightField;
    JTextField totalCaloriesField;
    JTextField proteinField;
    JTextField fatsField;
    JTextField carbsField;
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM