Eljay Eljay - 1 year ago 86
Java Question

Reading a value from Textfield

I want to read a value from textfied in Java but I am not able to read it
Here is my code

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");
Container content = frm.getContentPane();
JTextField text = new JTextField();
JButton button1, button2;
button1 = new JButton("PROGRAMMER");
button2 = new JButton("USER");
button1.addActionListener(new ButtonHandler());
button2.addActionListener(new ButtonHandler());

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

I tried the following methods

1.In the Class Textfield i used this method under button2.addactionlistener.It gave an error

Cannot refer to a non-final variable text inside an inner class defined in a different method

button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

2.In the class ButtonHandler

it says that text cannot be resolved

What Method should i use to read the textfield and in which class should in read it

Answer Source

1) if you rename (possible conflict with with AWT API with name TextField) and remove JDialog, because it is never used

public class TextField extends JDialog { TextField(){


public class MyTextField { public MyTextField(){

2) and change the main method

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


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

            private final JTabbedPane jtp = new JTabbedPane();

            public void run() {
                MyTextField textField = new MyTextField();

3) remove all chars >

4) add DefaultCloseOparation for JFrame, otherwise your program will stay in the memory until your PC is restarted or switched off

5) remove all un_Swing methods and use a LayoutManager

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download