由于某种原因,getText不能在JTextField上工作

时间:2014-08-28 02:58:47

标签: java swing jtextfield gettext

这是我的代码 它要求我将changeName设置为静态变量。这没有意义,因为我试图捕获用户输入。

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

我特别对这部分代码存在问题

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

它要求我将changeName设置为静态变量。这没有意义,因为我试图捕获用户输入。

1 个答案:

答案 0 :(得分:1)

你的内部类被声明为static ...

static class setNameAction ...

如果您希望能够引用外部类的实例字段,请从类声明中删除static引用...

否则,您需要将OptionsJTextField的实例传递给setNameAction课程。

您可能希望阅读Code Conventions for the Java TM Programming Language,这样可以让人们更轻松地阅读您的代码并让您阅读其他代码