简体   繁体   中英

How do I get the text from a textfield when a button is pressed?

I'm a new entry in the programming world, so my skills are really poor. Anyway, I have to write a program for a school project, so I figured out one that seemd easy. Basically, I have just a Frame, a Button, a Panel (that I will use later) and two textfields. I need that when I write something in the first textfield and I press the button, the text will be scanned and put in a variable (that have to be processed later). The fact is that I dont't think I'm doing something right (just like I said, I'm just a beginner), and I can't figure out how to get what I want. Here's the code:

import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.*;
import java.io.*;
import java.util.Timer.*;
import java.util.TimerTask.*;
import java.util.Scanner.*;
import java.lang.*;
import javax.sound.sampled.*; 

public class ExamProgram {

public TextField scrivi;
public TextField vuraid;
public Button b;
public String s;


 static class int timer4action(){return 0;}

 static class chiusura implements WindowListener { 
 public void windowClosing (WindowEvent ev) {System.exit(0);} 
 public void windowClosed (WindowEvent ev) {} 
 public void windowOpened (WindowEvent ev) {} 
 public void windowActivated (WindowEvent ev) {} 
 public void windowDeactivated (WindowEvent ev) {} 
 public void windowIconified (WindowEvent ev) {} 
 public void windowDeiconified (WindowEvent ev) {} 
}  //Window events

public ExamProgram(){ //Constructor
    //Frame inizialization
    Frame f = new Frame ("Artificial wife");
    f.setLayout(null);
    f.setBackground(Color.white);
    Image icona = Toolkit.getDefaultToolkit().getImage("src\\img\\Kurisu_profile.png");
    f.setIconImage(icona);
    f.setSize(800,600);
    f.setVisible(true);
    f.setResizable(false);
    f.addWindowListener(new chiusura());
    //Menù initialization.
    MenuBar mb = new MenuBar();
    Menu m1 = new Menu("File");
    Menu m2 = new Menu("Opzioni");
    Menu m3 = new Menu("Aiuto");
    MenuItem mi1 = new MenuItem("Nuovo");
    MenuItem mi2 = new MenuItem("Carica");
    MenuItem mi3 = new MenuItem("Chiudi");
    MenuItem mi4 = new MenuItem("Cambia lingua");
    MenuItem mi5 = new MenuItem("FAQ");
    MenuItem mi6 = new MenuItem("Manuale Elettronico");
    m1.add(mi1); m1.add(mi2); m1.add(mi3);
    m2.add(mi4);
    m3.add(mi5);m3.add(mi6); 
    mb.add(m1); mb.add(m2); mb.add(m3);
    f.setMenuBar(mb);
    //Panel initialization
    Panel waifu = new Panel();
    waifu.setBackground(Color.PINK);
    waifu.setBounds(25, 50, 750, 450);
    waifu.setVisible(true);
    f.add(waifu);
    //Textfield n°1 initialization
    scrivi = new TextField();
    scrivi.setVisible(true);
    scrivi.setBackground(Color.pink);
    scrivi.setBounds(200,530, 400, 30);
    f.add(scrivi);

    //Button initialization
    b = new Button("Send");
    b.setBackground(Color.PINK);
    b.setBounds(650, 530, 50, 30);
    f.add(b);

    //Event and Textfield n°2 initialization
    vuraid = new TextField();
    vuraid.setVisible(true);
    vuraid.setEditable(false);
    vuraid.setBackground(Color.green);
    vuraid.setBounds(200,570, 400, 30);
    f.add(vuraid);
    b.addActionListener(new send());

}

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

And the action I want to get from the event:

import java.lang.*;
import java.awt.*;
import java.awt.event.*;

public class send implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {
       String textDialogue = new String();
       textDialogue = scrivi.getText();
       vuraid.setText(textDialogue);
    }
}

Hope that I expressed myself properly so that you could get what I'm trying to ask. I tried to remove every italian text for letting the code be more understandable. Thank you very much for your attention.

Your send class needs a reference to the object which contains the information (ie the text field)

The "simplest" solution would be to pass a reference of the text field to the send class via it's constructor

b.addActionListener(new send(vuraid));

You will, obviously need to update the send class to support this

public class send implements ActionListener {
    private TextField vuraid

    public send(TextField vuraid) {
        this.vuraid = vuraid;
    }
    //...

This is a relatively common concept. See Passing Information to a Method or a Constructor for more details

Word of warning. You are using mostly AWT based components. AWT was superseded by Swing more then 18 years ago, you might want to consider updating

I would also encourage you to get an understand of the how the layout management API works, as it will solve many common issues you will encounter between different computers.

Start by having a look at Laying Out Components Within a Container for more details

You will also generally find that moving

f.setSize(800,600);
f.setVisible(true);
f.setResizable(false);

to the end of your main method and call them in the following order

f.setResizable(false);
f.setSize(800,600);
f.setVisible(true);

This is resolve issues with components not been visible when the UI is first displayed. There are also considerations you need to take into account when using setResizable , as it can change the size of the window borders and change the available window size

I would firstly suggest to format the code in you example as it's way off. Other than that, please describe the problem you're experiencing. I ran your example and it seems to be working fine.

I input some text of the first textfield, hit send and the text was shown on the second textfield. What is the problem exactly then?

Other than that, I would suggest several changes in the code. First of all instead of creating a new class that implements the ActionListener , you could very well use an Anonymous class to obtain the same functionality. Instead of b.addActionListener(new send()); you could very do:

b.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //your logic goes here...
        }
    });

Even better you could do the same thing in a one-liner with a lambda expression:

b.addActionListener(e -> {
        // logic goes here
    });

In both cases you bypass the new need to create a new class. Speaking of this, I suggest you check the naming conventions regarding class naming. The class name called send that implements the ActionListener should start with an upper-case letter as should all classes.

In all cases, avoid doing this String something = new String(); . This will effectively create a new String object that is uneeded and may result in unexpected stuff happening (check here for more Java Strings: "String s = new String("silly");" ).

In all cases though, please reformat the code and explain the exact error you're having.

Action listener should be added to Button as you want the text from Textfield on Button click like this:

b = new Button("Send");
b.setBackground(Color.PINK);
b.setBounds(650, 530, 50, 30);
b.addActionListener(this);
f.add(b);

Also remove the line b.addActionListener(new send()); from your code(wrong syntax)

And for fetching the text from Textfield1 and displaying it in Textfield2 on button click:

public void actionPerformed(ActionEvent e)
{
String textDialogue = scrivi.getText();
vuraid.setText(textDialogue);
}
}

All the best!

Basically whenever you press a button you want this class inside your already made class...

So lets say in your class called ExamProgram , you would do this:

public class ExamProgram {
    //Additional information here...

    public ExamProgram() {
        //Additional information here...

        theHandler handler=new theHandler();
        someTextField.addActionListener(handler);
    }

    public class theHandler implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == someTextField) {
                //Button Pressed Actions Go here...
            }
        }
    }
}

The theHandler Action Listener class is what you would be using to test if that button is pushed, and what should happen when that button is pushed...

Now if you don't (or can't) so that, than you have to do this...

In this part, your Component must be either a static or final ...

final JTextField someTextField=new JTextField("Example");

someTextField.addActionLister(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //Button Pressed Actions Go here...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM