TextField waiting for a user input - java

I got a JTextfield a GetText method, and an array to store the numbers logged on the Jtextfield.
JTextField tf1 = new JTextField();
frame.add(tf1);
String tfone = tf1.getText();
int one = Integer.parseInt(tfone);
int[][] array = new int[4][5];
array[0][0] = one;
array[0][1] = otherValues...
The problem here is, that code execute all, so no wait for a user input into the JtextField. How can i make the jtextfield wait, until an user log in something. To latter on execute the Integer.Parseint ?
I can no change JtextField by another method cuz I'm working with GUI (Graphic User Environment.)

You may try adding Button and then perform it's ActionListener and then enter the input and pressing the button will load the code of doing the stuff you want.

You can use a DocumentListener:
JTextField tf1 = new JTextField();
tf1.getDocument().addDocumentListener(DocumentListener()
{
#Override
public void changedUpdate(DocumentEvent e)
{
}
#Override
public void insertUpdate(DocumentEvent e)
{
// parse here
}
#Override
public void removeUpdate(DocumentEvent e)
{
// parse here
}
});

Instead of JTextField, you can use JOptionPane to get the user input. It will display a modal form and wait until the user validates.
String tfone = JOptionPane.showInputDialog("Please enter a number");
// Now test the user input
if (tfone != null) {
int one = Integer.parseInt(tfone);
}
Here is the documentation User input with JOptionPane

Here is the code:
JTextField tf1 = new JTextField();
frame.add(tf1);
JButton b = new JButton();
b.setText("Solve");
b.setBounds(30, 140, 110, 30);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
String tfone = tf1.getText();
int one = Integer.parseInt(tfone);
int[][] array = new int[4][5];
array[0][0] = one;
array[0][1] = otherValues...
//Here you can complete the rest of functions
});
frame.add(b);
Once the user press the button the code will end its execution.

Related

How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

This is part of a project for school, and I'm stuck and need someone to bounce ideas off of. I have a game where there is an option to sign up or sign in for a machine-local game so a record can be kept of the person's scores. The game is run from a base GUI JFrame, and I want to make buttons to bring up secondary windows for the person to sign in or sign up, before closing out of them. I need to pass the validated username back to the initial GUI/game class so I can store it for the following game so the game score can be added under that user. I just need to pass the username back and I'm not sure how to go about it. This is the main GUI code up to where I'm having my issue:
public class MathFactsGUI extends JFrame
{
// instance variables
private JTextField problemJTextField, answerJTextField;
private JLabel equalJLabel;
private JButton additionJButton, multiplicationJButton;
private JButton signupJButton, signinJButton;
private JButton submitJButton;
private JLabel scoreJLabel,resultJLabel;
//private JButton reviewButton;
private String username;
private Userbase userbase;
private JLabel introJLabel;
Quiz quiz;
/**
* Constructor for objects of class MathFactsGUI
*/
public MathFactsGUI()
{
super("Math Facts Quiz");
userbase = Userbase.getUserbase();
username = "guest";
/* code here has been removed to be abbreviated */
// Action listener for buttons
additionJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('+');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
multiplicationJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('x');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
signinJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JDialo
}
});
signupJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
gui.setVisible(true);
}
});
}
This is the JFrame I wrote for the sign-up button:
public class MathFactsSignUpGUI extends JDialog {
private JTextField usernameJTextField, userPassJTextField, userFirstNameJTextField;
private JLabel usernameJLabel, userPassJLabel, userFirstNameJLabel;
private JButton submitJButton;
private String username;
private String userPass;
private String userFirstName;
public MathFactsSignUpGUI(){
usernameJLabel = new JLabel("Username:");
usernameJTextField = new JTextField();
userPassJLabel = new JLabel("Password:");
userPassJTextField = new JTextField();
userFirstNameJLabel = new JLabel("Player First Name:");
userFirstNameJTextField = new JTextField();
Box usernameBox = Box.createHorizontalBox();
usernameBox.add(usernameJLabel);
usernameBox.add(usernameJTextField);
Box userPassBox = Box.createHorizontalBox();
userPassBox.add(userPassJLabel);
userPassBox.add(userPassJTextField);
Box userFirstBox = Box.createHorizontalBox();
userFirstBox.add(userFirstNameJLabel);
userFirstBox.add(userFirstNameJTextField);
submitJButton = new JButton("Submit");
submitJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
username = usernameJTextField.getText();
userPass = userPassJTextField.getText();
userFirstName = userFirstNameJTextField.getText();
if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
JOptionPane.showMessageDialog(null, "All fields must have values.");
} else if (Userbase.getUserbase().userExist(username)==true){
JOptionPane.showMessageDialog(null, "Username is taken, please choose another.");
} else {
Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
MathFactsGUI.setUsername(username);
}
}
});
JPanel mfSignUp = new JPanel()
mfSignUp.setLayout(new GridLayout(0,1));
mfSignUp.add(usernameBox);
mfSignUp.add(userPassBox);
mfSignUp.add(userFirstBox);
mfSignUp.add(submitJButton);
}
public String signIn(){
return username;
}
public boolean checkValid(String a){
if (a == null || a.length() == 0){
return false;
} else {
return true;
}
}
}```
I was thinking of implementing a WindowListener action for when the sign-up/sign-in frames close, but I'm not sure that will work. I was also looking into JDialog, but I'm not sure if it has the layout/text verification properties I need.
Use a JOptionPane. It will simplify your layout without the need for creating a separate JFrame and easily pass values back to wherever it was called from. You can then make it check for valid username when you click OK.
Try this site. It gives a good rundown with example images
First you need to understand that this is an object, so you can create some global variables which will contains this information(username,password,Nickname), i recommend to pull info from MathFactsSignUpGUI by using ScheduledExecutorService. It will pull info from this sign up gui in every 100ms, than it will destroy itself, here is an example:
MathFactsSignUpGUI su = new MathFactsSignUpGUI ();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
public void run(){
if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty() ){
if(su.isLogin){ //if player is loggining
//do something here
}else{//if user is registered
//do something here
}
System.out.println("Check complete");
service.shutdown();//to destroy this service after recieving the data
}
}
}, 100, TimeUnit.MICROSECONDS);

two textfield update each other

I try to convert data but without clicking on a button,
When I enter the data in the 1st textfield nothing happens
JTextField textC = new JTextField() ;
JTextField textF = new JTextField() ;
labelC.setText("Celsius");
labelF.setText("Fahrenheit");
ActionListener textFieldCListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = textC.getText();
try {
float valC = new Float(value);
float valF = valC * 1.8f + 32;
textF.setText(Float.toString(valF));
} catch (Exception exp) {
textF.setText("");
textC.setText("");
}
}};
You should add ActionListener to your JTextField object.
textC.addActionListener(textFieldCListener);
See this: What addActionListener does?
Try:
textC.addActionListener(textFieldCListener);

Java : Any way to save a string input into pdf

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

if statements,lables and combo boxes

Ok my code has to pick route combo box (check) display in label(check) have a return and single ticket combobox(check) need it to display text(check) my problem is it only prints text related to one of my statments hope someone can tell me how to fix my if statments. The lable changes on a button .It reads code by lable.So far it only prints 15 and wont print 20 unless i had another label but this wouldnt make sense for the program
package learning;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList.*;
import java.util.Arrays.*;
import java.util.List.*;
#SuppressWarnings("unused")
public class test {
String[] items = {"Tipperary_to_cork","Cork_to_Dublin","Limerick_to_Tipperary","Dublin_to_Cork"};
JComboBox c = new JComboBox(items);
JButton b = new JButton("From");
JLabel l = new JLabel();
String[] items2 = {"window","aisle"};
JComboBox m = new JComboBox(items2);
JButton n = new JButton("Seat");
JLabel o = new JLabel();
String[] items3 = {"Single","return"};
JComboBox x = new JComboBox(items3);
JButton y= new JButton("Ticket");
JLabel z = new JLabel("choose Ticket");
String[] items4 = {"1","2","3","4","5","6","7","8","9","10"};
JComboBox<?> xx = new JComboBox(items4);
JButton yy = new JButton("seat");
JLabel zz = new JLabel("Choose a seat");
JLabel hh = new JLabel("cost");
JButton ccc = new JButton("comfirm");
JLabel hhh = new JLabel("");{
}
public test(){
frame();
}
public void frame(){
JFrame wolf = new JFrame();//frame
wolf.setVisible(true);
wolf.setSize(350,350);
wolf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = new JPanel();
p.add(hh);
p.add(c);//
p.add(b);//
p.add(l);//lable1
p.add(m);//
p.add(n);//
p.add(o);//lable 2
p.add(x);//
p.add(y);//
p.add(z);//lable 2
p.add(xx);//
p.add(yy);//
p.add(zz);//lable 2
p.add(ccc);
p.add(hhh);
wolf.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
l.setText(s);
}
});
n.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = m.getSelectedItem().toString();
o.setText(s);
}
});
y.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = x.getSelectedItem().toString();
z.setText(s);
}
});
yy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = xx.getSelectedItem().toString();
zz.setText(s);
}
});
}
{
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("single"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("15"); //***
}});
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("return"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("20"); //****
}
});
}}}
public static void main(String[]args){
new test();
}
}
You want to check "if some condition" when you click the button. So, start with one simple if statement inside one of the actionPerformed methods. You shouldn't add an action listener inside an if statement, you should always perform an action, and determine the event inside that action.
For example
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
if (s.equals("Tipperary to cork")) {
// TODO: do something
}
}
});
Original answer
These line just happen to work because you have if(false==false)
if(l.equals("Tipperary to cork")==(z.equals("single"))) { ... }
if(l.equals("Tipperary to cork")==(z.equals("return"))) { ... }
The reason they evaluate to false is because you are comparing a JLabel.equals(String). You should use l.getText().equals("text here"), but...
The problem is that you have those if statements inside the constructor for your class, meaning that they are the first thing that is evaluated in your code. You should move the corrected if statements into the ActionListeners for the respective buttons.
Additional note: You seem to want "Tipperary to cork" AND "single". In that case, use && in place of ==. Alternatively, you could do this (psuedocode intentional)
if "Tipperary to cork" {
if "single" { ... }
else if "return" { ... }
}
In reality, though, you should compare c.getSelectedItem().toString() instead of the text of the label, but that's your decision.

Update a JTextArea dynamically depending on users JTextField values

I have two JTextField which take numbers from users, like this:
nbMuscle = new JTextField();
nbMuscle.setText("2");
and this:
nbFuyard = new JTextField();
nbFuyard.setText("1");
my JTextArea() takes make an addition of both JTextField's values, like this:
nbPersonnages = new JTextArea();
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));
It works like a charm but I have one problem, if the user edit one of the JTextFields, the JTextArea value don't change. I have found on internet some notions like jTextArea.appened(String str) but it doesn't work.
Any idea of what I could do?
You have to add a DocumentListener to the underlying Document of the TextFields to listen to changes made while the program runs.
The easiest way to do this is proboably an anonymous class.
Here is the Code:
nbMuscle = new JTextField();
nbMuscle.setText("2");
nbFuyard = new JTextField();
nbFuyard.setText("1");
nbPersonnages = new JTextArea();
DocumentListener dl = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
textChanged();
}
#Override
public void insertUpdate(DocumentEvent e) {
textChanged();
}
#Override
public void changedUpdate(DocumentEvent e) {
// This method is not called when the text of the Document changed, but if attributes of the Document changed.
}
private void textChanged() {
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));
}
};
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));
nbMuscle.getDocument().addDocumentListener(dl);
nbFuyard.getDocument().addDocumentListener(dl);

Categories