gpt4 book ai didi

java - 由于某种原因,getText 无法在 JTextField 上工作

转载 作者:行者123 更新时间:2023-12-01 12:36:29 25 4
gpt4 key购买 nike

这是我的代码它要求我将changeName 设置为静态变量。这没有意义,因为我正在 try catch 用户输入。

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 设置为静态变量。这没有意义,因为我正在 try catch 用户输入。

最佳答案

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

static class setNameAction ...

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

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

您可能想通读Code Conventions for the Java TM Programming Language ,这将使人们更容易阅读您的代码,也让您更轻松地阅读其他人

关于java - 由于某种原因,getText 无法在 JTextField 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25540020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com