gpt4 book ai didi

java - 从文本域中读取值

转载 作者:行者123 更新时间:2023-11-29 06:04:24 25 4
gpt4 key购买 nike

我想从 Java 中的 textfied 中读取一个值,但我无法读取它这是我的代码

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

public class TextField extends JDialog {
TextField() {
JFrame frm = new JFrame("SAMPLE PROGRAM");
frm.setBounds(150,150,420,400);
frm.setLayout(null);
Container content = frm.getContentPane();
content.setBackground(Color.cyan);
JTextField text = new JTextField();
text.setBounds(70,25,100,30);
JButton button1, button2;
button1 = new JButton("PROGRAMMER");
button2 = new JButton("USER");
button1.setBounds(270,25,120,50);
button2.setBounds(270,90,120,50);
button1.addActionListener(new ButtonHandler());
button2.addActionListener(new ButtonHandler());
frm.add(button1);
frm.add(button2);
frm.add(text);
frm.setVisible(true);
frm.setResizable(false);
}

public static void main(String[] args) {
new TextField();
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = new String();
str = e.getActionCommand();
System.out.println(" " + str);
}
}
}

我尝试了以下方法

1.在 Class Textfield 中,我在 button2.addactionlistener 下使用了这个方法。它给出了一个错误

不能在不同方法中定义的内部类中引用非最终变量文本

button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(text.getText().equals("joe"))

2.在ButtonHandler类中

它说文本无法解析

我应该使用什么方法来读取文本字段以及应该在哪个类中读取它

最佳答案

1) 如果您重命名(可能与名称为 TextField 的 AWT API 发生冲突)并删除 JDialog,因为它从未被使用过

public class TextField extends JDialog { TextField(){

public class MyTextField { public MyTextField(){

2) 并更改主要方法

public static void main(String[] args) {
new TextField();
}

    public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

private final JTabbedPane jtp = new JTabbedPane();

@Override
public void run() {
MyTextField textField = new MyTextField();
}
});
}

3) 删除所有字符 >

4) 为JFrame添加DefaultCloseOparation,否则你的程序将一直停留在内存中,直到你的电脑重启或关机

5) 删除所有un_ Swing methods并使用 LayoutManager

关于java - 从文本域中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9044501/

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