Search code examples
javaswingjtextfieldgettext

getText wont work on a JTextField for some reason


Here is my code Its asking to me set changeName to a static variable. This wouldnt make sense because I'm trying to capture user input.

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;

import CourseProject.General.exitApp;

public class Options extends JPanel{

    private JLabel changeLabel;
    private JTextField changeName;
    private JButton setName;
    private JButton exitButton;

    public Options(){
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.NORTH;
        setBackground(Color.WHITE);
        super.setLayout(gridbag);
        c.insets = new Insets(10, 10, 10, 10);

        changeLabel = new JLabel("Change Company Name:");
        changeName = new JTextField(10);
        setName = new JButton("Set New Name");
        exitButton = new JButton("Exit");       

        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        add(changeLabel, c);        

        c.gridx = 0;
        c.gridy = 1;    
        add(changeName, c);     

        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        add(setName, c);
        setName.addActionListener(new setNameAction());


        c.gridx = 1;
        c.gridy = 2;    
        add(exitButton, c);
        exitButton.addActionListener(new exitApp());
        exitButton.setSize(40,40);

    }
    static class setNameAction implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String str = "";
            str = changeName.getText();
        }
    }

    static class exitApp implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
}

I'm specifically having a problem with this part of the code

static class setNameAction implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String str = "";
        str = changeName.getText();
    }
}

Its asking to me set changeName to a static variable. This wouldnt make sense because I'm trying to capture user input.


Solution

  • You inner class is declared static...

    static class setNameAction ...
    

    Remove the static reference from the class declaration if you want to be able to reference the instance fields of the outer class...

    Otherwise you will be required to pass an instance of Options or JTextField to the setNameAction class.

    You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others