public void actionPerformed(ActionEvent e) {
s = tf1[0].getText();
}
I want to save the text input i get from tf1[0].getText(); to String s and call s in my main , or in another class, but I get null back instead. Is there a way to call s in another class?
this is the rest of the code:
public class GUI {
static String s;
public static void gui(){
{
try{
String File_Name="C:/Users/Ray/Desktop/test.txt";
ReadFile rf=new ReadFile(File_Name);
JFrame f1=new JFrame("Maintest");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
final String[] aryLines=rf.OpenFile();
final JTextField tf1[];
tf1=new JTextField[22];
JButton []b1=new JButton[6];
String bNames="OK";
final JTextField tf2[]=new JTextField[aryLines.length];
f1.setSize(200,450);
JLabel l1[]=new JLabel[20];
for ( int i=0; i < aryLines.length; i++ )
{
b1[i]=new JButton(bNames);
l1[i]=new JLabel("Enter Serial# for "+ aryLines[i]);
p1.add(l1[i]);p1.add(tf1[i] = new JTextField());p1.add(b1[i]);
}
p1.setLayout(new BoxLayout(p1,BoxLayout.PAGE_AXIS));
f1.add(p1,BorderLayout.WEST);
b1[0].addActionListener(new ActionListener(){
private String s2;
public void actionPerformed(ActionEvent e)
{
s=tf1[0].getText();
System.out.print(s);
}
});
f1.show();
}
catch(Exception e)
{
System.out.print(e);
}
}
}
}
There are a couple solutions to this. You can make "s" a class based variable that can be retrieved from the object instance like this:
public String getS(){
return this.s;
}
And here:
public void actionPerformed(ActionEvent e) {
this.s = tf1[0].getText();
}
Then in your other class needing s, you should instantiate the Class containing s and call:
String s2 = instantiatedObject.getS();
If you feel getting a little risky, you can make "s" a static variable and you can just call it anywhere you instantiate the class containing "s":
String s2 = instantiatedObject.s;
Related
this is my first question on this website.
I have this problem, in this class I have two buttons with two different functions, one to exit and another to put the first and last name in a text field.
I can't get the second ActionEvent to work, please help me, thanks.
import javax.swing.*;
import java.awt.event.*;
public class Prueba1 extends JFrame implements ActionListener{
private JLabel nombre, apellidos,respondo;
private JTextField textfield, textfield1;
private JButton boton,botonoff;
public Prueba1() {
setLayout(null);
nombre = new JLabel("Nombre:");
nombre.setBounds(10, 10, 300, 30);
add(nombre);
apellidos = new JLabel("Apellidos");
apellidos.setBounds(10, 40, 300, 30);
add(apellidos);
textfield = new JTextField();
textfield.setBounds(100,10,150,20);
add(textfield);
textfield1 = new JTextField();
textfield1.setBounds(100,40,150,20);
add(textfield1);
boton = new JButton("¿Que saldrá?");
boton.setBounds(10,80,120,30);
boton.addActionListener(this);
add(boton);
botonoff = new JButton("Salir");
botonoff.setBounds(10,120,120,30);
botonoff.addActionListener(this);
add(botonoff);
respondo = new JLabel("UwU");
respondo.setBounds(160,80,300,30);
add(respondo);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
}
}
public void actionPerformed1(ActionEvent e) {
if(e.getSource() == botonoff) {
System.exit(0);
}
}
public static void main(String args[]) {
Prueba1 clase = new Prueba1();
clase.setVisible(true);
clase.setBounds(0, 0, 500, 500);
clase.setResizable(true);
clase.setLocationRelativeTo(null);
}
}
Remove public void actionPerformed1(ActionEvent e) method and add the body of that method in the else branch in the body of public void actionPerformed(ActionEvent e).
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
} else if (e.getSource() == botonoff) {
System.exit(0);
}
}
When you provide an ActionListener object to a buttons button.addActionListener(listener)
You have several ways to accomplish this.
button.addActionListener(this);
Is only one way. This way says the the class implements ActionListener.
In effect it implements the
public void actionPerformed(ActionEvent e)
method.
Your
public void actionPerformed1(ActionEvent e)
can't be used by the button at all.
Fortunately there are many other ways to describe the code that should be executed when an action event is produced.
An inner class, static or not. Other class/object.
A lambda expression.
You can find how to express a lambda here.
So I have to take a string input from GUI using Textfield and make it show up in a pdf document, when I use ActionListener :
b1[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0)
{
s=tf1[0].getText();
}
});
When I run the gui and type in the tf1 and press b1, it should save it in s right? But it isn't doing that, however if I just hardcode s="string" it shows up in the pdf. Any ideas?
Forgot to mention I am using iText so the only problem i am having is that the String s is not getting saved from the TextField
Also the code for the actionlistener class if you want it:
public class GUI {
public static String s;
public static void gui(){
{
try{
String File_Name="C:/Users/Ray/Desktop/test.txt";
ReadFile rf=new ReadFile(File_Name);
JFrame f1=new JFrame("Maintest");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
final String[] aryLines=rf.OpenFile();
final JTextField tf1[]=new JTextField[22];
JButton []b1=new JButton[6];
String bNames="OK";
final JTextField tf2[]=new JTextField[aryLines.length];
f1.setSize(200,450);
JLabel l1[]=new JLabel[20];
for ( int i=0; i < aryLines.length; i++ )
{
b1[i]=new JButton(bNames);
l1[i]=new JLabel("Enter Serial# for "+ aryLines[i]);
p1.add(l1[i]);p1.add(tf1[i] = new JTextField());p1.add(b1[i]);
}
p1.setLayout(new BoxLayout(p1,BoxLayout.PAGE_AXIS));
f1.add(p1,BorderLayout.WEST);
b1[0].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0)
{
s=""+tf1[0].getText();
System.out.println(s);
}
});
f1.show();
}
catch(Exception e)
{
System.out.print(e);
}
}
}
}
Sorry that I can't answer in more detail, but you could check if the tf1[0].getText() works. Just put a System.out.println("Text: "tf1[0].getText()); into your ActionListener. I'm pretty sure it will be null or "Text: ". For further help you'll have to provide more code.
Please take a look at this link
public Server(){
start.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try{
port = Integer.parseInt(portInput.getText());
}
catch(NumberFormatException e){
text.append("");
}
}
});
}
Having the actionlistener inside the constructor, I can't use the append method becacuse it tells me to add a Server cast to text.append("");
When I do this it tells me I "Cannot cast from JTextArea to Server"
When I move the action listener outside of the constructor it gives me an error and basically forces me to put the action listener inside the constructor. So what I want is to be able to have the action listener outside the constructor so I can call the append method inside the actionlistener.
At this point I'm not sure what to do. I'm sure its something minor, but I just can't figure it out. Any help please?
I'm going to first present working code based for the addActionListener in constructor case, I took the liberty of introducing missing fields.
public class ServerGUI {
private final JButton startServer = new JButton("Start server");
int port;
private JTextField portInput = new JTextField();
private JTextArea eventsLog = new JTextArea();
public ServerGUI(){
startServer.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try{
port = Integer.parseInt(portInput.getText());
}
catch(NumberFormatException nfe){
appendEventsLog("");
}
}
});
}
private void appendEventsLog(String msg) {
String text = eventsLog.getText();
eventsLog.setText(text + "\n" + msg);
}
}
The problem here was that appendEventsLog is not a member of JTextArea but a member of ServerGUI.
For the second case assigning ActionListener to JButton outside the constructor you have to use static code block or what I prefer initialise method
public class ServerGUI {
private final JButton startServer = new JButton("Start server");
int port;
private JTextField portInput = new JTextField();
private JTextArea eventsLog = new JTextArea();
public ServerGUI(){
initalise();
}
private void initalise() {
startServer.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try{
port = Integer.parseInt(portInput.getText());
}
catch(NumberFormatException nfe){
appendEventsLog("");
}
}
});
}
private void appendEventsLog(String msg) {
String text = eventsLog.getText();
eventsLog.setText(text + "\n" + msg);
}
}
You are actually not handing over any string at
eventsLog.appendEventsLog("");
I´m not shure if it has to do with your problem or if you just forgot to type it.
I was wondering how to retrieve the string textOperandValue,from this code :
final JTextField textOperand = new JTextField();
textOperand.setBounds(200,100,75,25);
//textOperand action Listener
textOperand.addActionListener( new ActionListener () {
public void actionPerformed(ActionEvent e) {
String textOperandValue = textOperand.getText();
}
});
So I can take it, and then parse it into a double to be used later in the program. I tried setting it equal to a another string
String Input = " "; but it said I had to initialize the string to a final String Input = " "; which I learned is something like a constant in C++.
Any variables you declare within an ActionListener won't be visible to the rest of your code. Either you need to set a variable (from within the listener) that has wider scope:
public class Listen
{
String usefulResult = null;
public Listen()
{
final JTextField textOperand = new JTextField();
textOperand.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Listen.this.usefulResult = textOperand.getText();
}
});
}
}
Here we use the "OuterClass.this" trick to access the surrounding scope without needing a final variable.
or you need to perform all the necessary work from within the listener itself (i.e. you don't "retrieve" the value, you just use the value):
public void doSomethingUseful(String usefulValue) { /* add code here */ }
textOperand.addActionListener( new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
doSomethingUseful(textOperand.getText());
}
});
Or you could use this second technique to call a setter method that changes the value of a variable, avoiding the problems of accessing final variables within event listeners:
public class Listen
{
String usefulResult = null;
public void setUseful(String usefulValue){
usefulResult = usefulValue;
}
public Listen()
{
final JTextField textOperand = new JTextField();
textOperand.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setUseful(textOperand.getText());
}
});
}
}
It depends what you want to do with the value from the TextField.
You can't access the members of anonymous classes. In this case it's even a local variable in a method, those are never accessible.
Either, you'll have to set the value of a member of the outer class, but beware of synchronization trouble.
class MyClass {
final JTextField textOperand = new JTextField();
public String textOperandValue;
public MyClass() {
textOperand.setBounds(200,100,75,25);
//textOperand action Listener
textOperand.addActionListener( new ActionListener () {
public void actionPerformed(ActionEvent e) {
textOperandValue = textOperand.getText();
}
});
}
public someOtherMethod() {
// textOperandValue available here
if (textOperandValue != null)
//is set
}
}
Or, you'll have to call a method somewhere else that can store the value.
class MyClass {
final JTextField textOperand = new JTextField();
public MyClass() {
textOperand.setBounds(200,100,75,25);
//textOperand action Listener
textOperand.addActionListener( new ActionListener () {
public void actionPerformed(ActionEvent e) {
someOtherMethod(textOperand.getText());
}
});
}
public someOtherMethod(String value) {
System.out.println(value);
}
}
Or, you create a (named) class that is an ActionListener and that can store the value in a retrievable form.
class MyClass {
final JTextField textOperand = new JTextField();
public String textOperandValue;
private class MyActionListener implements ActionListener {
String value;
public void actionPerformed(ActionEvent e) {
value =textOperand.getText();
}
}
MyActionListener l = new MyActionListener();
public MyClass() {
textOperand.setBounds(200,100,75,25);
//textOperand action Listener
textOperand.addActionListener(l);
}
public someOtherMethod() {
if (l.value != null)
//is set
}
}
Or, you just do what you need to do in the action method:
class MyClass {
final JTextField textOperand = new JTextField();
public MyClass() {
textOperand.setBounds(200,100,75,25);
//textOperand action Listener
textOperand.addActionListener( new ActionListener () {
public void actionPerformed(ActionEvent e) {
System.out.println(textOperand.getText());
}
});
}
}
it can work if textOperandValue is global(if it defined in class globally) variable.
not inside ActionListener, not inside method where you wrote this code.
I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects