Calling String from another method - Java - java

I am trying to use this String called "username" from another method, but I can't seem to figure out what to do.
I have this bit of code right here, which assigns a text field's entry to a variable, but I can't seem to use this variable in another method
//Configuring content pane
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(129, 36, 120, 20);
UsernameFrame.getContentPane().add(formattedTextField);
UsernameFrame.setVisible(true);
//Assigning text field entry to variable
String username = formattedTextField.getText();
Now, I am trying to use this variable in the method pasted below, but I don't know what I am missing..
public void actionPerformed(ActionEvent e){
if(username.length() < 5){
}
//Execute when the button is pressed
System.out.println("The button has been pressed");
}
This is probably something really simple I am missing, thanks for your help guys.
(full code)
http://pastebin.com/RMszazd4

Declare username right after your class declaration like this:
public class App {
private String username;
public static void main(String[] args) {
...
}
...
}

If these are two separate methods you will need to reassign the username variable again or you can create a global variable outside of your methods.

You might want to pass in the string variable "username"as a parameter to another method since it would not recognize the scope of your string in another method unless its declared global.

You don't appear to have a way of reading the JFormattedTextField. If I understand what you're trying to do correctly, you could declare formattedTextField as an instance variable, and then declare username inside the listener:
public class Frame {
JFrame UsernameFrame = new JFrame("Welcome");
private JFormattedTextField formattedTextField;
....
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = formattedTextField.getText();
if (username.length() < 5) {
}
// Execute when the button is pressed
System.out.println("The button has been pressed");
}
});
Now you have a reference to the text of the JFormattedTextField to do what you will with each time the button is pressed.

Related

Java ActionCommand

Is there a method to get the button associated with a particular command string?
For instance if I define a button with:
button.setActionCommand("unique_toggle");
Having that string "unique_toggle", is it possible to retrieve that button from another class? I am beginner at Java, excuse if this question may seem obvious to you.
Yes, you can access to your button and its associated button's command. If you need to a button's command, that possibly means that you should consider redesining your programm because this approach is not advisable and very dirty way to do what you want to achieve.
When it comes to answer to your question,
Lets say Foo1 is your GUI class.
class Foo1{
JButton button;
public Foo1(Foo2 otherClass)
{
button = new JButton();
otherClass.setButtonAddress(button);
}
..... other methods
}
Foo2 is the class, in where you want to access button's command text.
class Foo2{
JButton buttonFromOtherClass;
//This is the method, in where you need command string of the button
private void getCommandsString()
{
Foo1 foo1 = new Foo1(this);
//After the initialization of Foo1, you can get every information of the button
String actionCommand = buttonFromOtherClass.getActionCommand();
}
public void setButtonAddress(JButton button)
{
buttonFromOtherClass = button;
}
}

Java - Linking a JTextField variable with another class variable

What I want to achieve is very simple.
I have 2 classes. "SpeedingTicket" & "SpeedingTicket GUI".
Inside my GUI I have 1 textbox name txtSpeedLimit & a button.
Inside my SpeedingTicket class I have a variable "int speedingTicket".
Inside my SpeedingTicket class I also have a get & set method for "speedingTicket".
I know how to get and set text using JTextFields, but I want to be able to:
receive input from the "txtSpeedLimit", and store that value into the "txtSpeedLimit" instance variable in the "SpeedTicket" class. I can then check for validation etc when I come to adding the vehicle speed.
Maybe this isn't the most efficient way of dealing with this program. Maybe I should scrap the instance variables in SpeedingTicket, and deal with it all in the GUI.
Any advice would be hugely appreciated.
Basically what I'm trying to do is this:
class confirmHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String val = txtSpeedLimit.getText();
int realNum = speed.getSpeedLimit() = txtSpeedLimit; < but obviously that doesn't work, but I want the textbox link to the variable.
EDIT: If we take away the GUI, all I want my program to do is the following:
Speed Limit: 50 < enterd via textfield
Speed: 60 < entered via textfield
if the speed is blah blah (ive already coded this).. then output a result to one of my labels.
I achieved this without making a GUI and making it only console based, but instead of the user typing it via the console, I want it to be typed via textfields.
THe values that are entered into the textfields should be stored in the two variables (speed and speedlimit) that are in the SpeedingTicket class.
You can update a value in:
public class SpeedingTicket {
int speedingTicket;
public SpeedingTicket() {
speedingTicket = 500;
}
public int getSpeedingTicket() {
return speedingTicket;
}
}
by:
public class SpeedingTicketGUI extends JPanel{
SpeedingTicket st;
SpeedingTicketGUI() {
st = new SpeedingTicket();
setLayout(new FlowLayout(FlowLayout.LEFT));
JTextField txtField = new JTextField(10);
txtField.setText(""+st.getSpeedingTicket());
add(txtField);
JButton btn = new JButton("Update");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setSpeedingTicket(txtField.getText());
}
});
add(btn);
}
private void setSpeedingTicket(String text) {
try {
int speedTicket = Integer.parseInt(text);
st.setSpeedingTicket(speedTicket);
System.out.println("Speeding ticket set to " +st.getSpeedingTicket());
} catch (NumberFormatException ex) {
System.out.println("Invalid value " +text);
ex.printStackTrace();
}
}
public static void main(String[] args){
JFrame frame = new JFrame("Speeding Ticket");
frame.setSize(400,100);
frame.add(new SpeedingTicketGUI());
frame.setVisible(true);
}
}
You don't need to store values in JText or any GUI componenets...
Use global static variables. For example:
public static int speed_limit;
You can access this variable from ANY method,class, etc.
There are multiple ways to do it.
You can detect textfield changes by using a DocumentListener or if you want (not recommended) by a KeyListener.
The Listener could be implemented directly by your gui class or by your other class. If you want more abstraction you could implement the DocumentListener by your gui class and create a method
public void addSpeedChangeListener(SpeedChangeListener scl) {
this.speedChangeListeners.add(scl);
}
Your SpeedChangeListener could be very simple:
public interface SpeedChangeListener {
public void speedChanged(int value);
}
Then your second class implements the SpeedChangeListener and calls addSpeedChangeListener(this) on your gui class. Inside the gui class, your document listener calls speedChanged(val) for every listener registered.
EDIT
You can also use the Button and call the speedChanged on every listener inside the actionPerformed method of the ActionListener.
I think it would be easier to use a JOptionDialog which pop ups when the button is clicked. That way you can easily get input and also validate the input straight away.

How to store text field value in to a variable for further use of it in java swing?

initialized a variable "input" and i want store the text in to it. so that i can perform search operation using that variable. by the below code it is not taking the variable input. thanks inadvance. please anyone help me
String input;
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
input = jt.getText(); // problem occurs here
jl.setText(input);
}
});
NOTE: if you want to use the object anywhere of your program please declare it at the top of your program. Like that
import java.awt.EventQueue;
public class MyExample {
private JFrame frame;
String input;
You shouldn't declare type of 'input' at out of an anonymous class. In this way, you have an error like 'The final local variable input cannot be assigned, since it is defined in an enclosing type'. In order to avoid this error, please make sure that you write the code in this way,
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = jt.getText();
jl.setText(input);
}
});
So you can put the input into JLabel.

FocusListener on JTextField not working

I've created an application that uses FocusListener to make sure a text fieid's value is always positive. When the user inputs negative value and then click the "tab" key to move focus away from the text field, the value will be multiplied by -1 so that the resulted value is positive. However, when I ran the application, the text field didn't change. I am not sure what I did wrong, and will appreciate any help.
Here is my code:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class AlwaysPositive extends JFrame implements FocusListener {
JTextField posField = new JTextField("30",5);
public AlwaysPositive() {
super("AlwaysPositive");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JTextField posField = new JTextField("30",5);
JButton ok= new JButton("ok");
posField.addFocusListener(this);
pane.add(posField);
pane.add(ok);
add(pane);
setVisible(true);
}
public void focusLost(FocusEvent event) {
try {
float pos = Float.parseFloat(posField.getText());
if (pos < 0)
pos = pos*-1;
posField.setText("" + pos);
} catch (NumberFormatException nfe) {
posField.setText("0");
}
}
public void focusGained(FocusEvent event) {
}
public static void main(String[] arguments) {
AlwaysPositive ap = new AlwaysPositive();
}
}
The main problem is you are shadowing your variables
You declare
JTextField posField = new JTextField("30",5);
As an instance variable, but in your constructor, you redeclare it again...
public AlwaysPositive() {
//...
JTextField posField = new JTextField("30",5);
posField.addFocusListener(this);
//...
}
Add attach the focus listener to it, but in the focusLost method, you are referring to the instance variable, which isn't the one that is actually on the screen
Start by changing the declaration within the constructor
public AlwaysPositive() {
//...
posField = new JTextField("30",5);
posField.addFocusListener(this);
//...
}
However, there are better solutions to use then FocusListener.
For example, you could use an InputVerifier that will allow you to verify the value of the field and make decisions about whether focus should be moved or not.
Take a look at How to Use the Focus Subsystem and Validating Input in particular
You could also use a DocumentFilter to restrict what the user can actually enter, filtering the input as the user types it. Take a look at Text Component Features and Implementing a Document Filter in particular.
You can also take a look at these examples for more ideas
When you create object of same name inside a method, the listener is set to the method object and not to the Class object.

How to access a variable defined in a Listener from the main class?

I have a problem with a variable in MyFrame class. I want to have in MyFrame class the value of a variable that is defined in a combobox listener.
This is my situation: I have a combobox with some friends' name. I have put a listener to the combobox which has to return the surname of the selected friend.
I want to insert the value of surname in a command in MyFrame class, but there are some problems: once setted surname as final (because it has to be used in the Listener), I have an error that say:
The final local variable surname cannot be assigned, since it is defined in an enclosing type.
What is (or are) the matter(s)? Here I post my code:
public class MyFrame extends {
public static void main (String[] args)
{
//other
String [] names = {"john","al","jack"};
final String surname=null;
JLabel nameLbl = new JLabel("surname: " + surname);
JComboBox box = new JComboBox(names);
JPanel centralPnl = new JPanel();
centralPnl.add(nameLbl);
centralPnl.add(box);
box.addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
{
// Here operations from database
//that return friends' surname under the variable name of "result"
surname = result;
}
}
});
}
}
You are trying to reassign a final variable, and thats the problem.
Also your final variable needs to be initialised in the first place.
Beyond the issues with the code already pointed out, I guess the question is do you need to store surname or are you just using it to update the label?
If you need to store the data, move your surname variable to the class level.
If you are simply updating the label, then do something like
nameLbl.setText("surname: " + result);
There are two things first one is that final variable must be initialized when it is declared and that final variable cannot be reassigned a value.
Unfortunately you are doing both of the mistakes.
Another problem is that you should post a Valid code; it will make others finding problems easily.

Categories