calling a function from textfield java gui - java

my question relates to java gui with netBeans
i'm trying to call a function from a TextField "Block"
but some how my gui freezing's when I do the following:
by the way if it's matters the other function called "startconnection();"
are private to... (p.s->Forgive me for my english...)
private void userTextActionPerformed(java.awt.event.ActionEvent evt) {
String str = evt.getActionCommand();
if(connected)
sendMessage(str);
else{
if((str.length() > 10) &&
(str.subSequence(0, 9).equals("<connect>")) &&
(str.charAt(9)== '<' )&&
(str.charAt(str.length()-1) == '>')&&
(!connected))
{
clientName = str.substring(10, str.length()-1);
userText.setText("");
startConnection();//sweet spot!! this is where i'm stack...
}else{
chatArea.append("Invalid input if you want to connect\nplease type '<connect><Your Name>'\n");
}
}
}

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

JOptionPane cancel button and getting input

I'm trying to get the user to input there name if it is left blank it will ask again, if they fill it out it sets a JLabel or hit cancel to get out.
My last if statement is wrong it does not like nameEnt.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
if (nameEnt == nameOption.CANCEL_OPTION) {
System.exit(0);
}
}
The JOptionPane.CANCEL_OPTION is a static int field, and you can't compare String with int with ==.
Good practice
In your case you want to use ok and cancel button JOptionPane.showConfirmDialog and JOptionPane.showInputDialog() in one shot and this is not possible, i suggest to use this instead :
JTextField nameF = new JTextField(20);//create TextField
JPanel myPanel = new JPanel();//cerate JPanel
myPanel.add(new JLabel("Name"));
myPanel.add(nameF);//add your JTextField to your panel
int result;
do {
result = JOptionPane.showConfirmDialog(null, myPanel,
"Title of Panel", JOptionPane.OK_CANCEL_OPTION);//add your panel to JOptionPane
if (result == JOptionPane.OK_OPTION) {//if the user press OK then
if (nameF.getText().isEmpty()) {//check if the input is empty
//if this condition is true JOption stays until name is entered or canceled
} else if (!nameF.getText().matches("[a-zA-Z]+")) {//check if the input match with your regex
//name match exactly
//name.setText(nameF.getText());
}
}
} while (result != JOptionPane.CANCEL_OPTION);//If the user hit cancel then exit
As per the JOptionPane API, if the user cancels the dialog, null is returned.
And so the correct solution is to to not to use equals, but rather to check the return value for null and to do this first, before checking its length.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
}
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
// if (nameEnt == nameOption.CANCEL_OPTION) {
// System.exit(0);
// }
}
But why are you creating a JOptionPane this way? Better to use the static method of creation.
// don't use null as the first parameter if the GUI is already showing
String nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
}
Or maybe something like this, if you're trying to loop to get input:
public Player() {
setSize(600, 400); // This is not good to do. Ask for details and I'll tell.
name = new JLabel();// Don't forget to add this to the GUI!
String nameEnt = "";
while (nameEnt.trim().isEmpty()) {
// if the GUI is already showing, pass a component from it as the first param here, not null
nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
} else if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
} else {
// set it to "" so that we keep looping
nameEnt = "";
}
}
}

Why JOptionPane cannot stop flow of execution, in my application?

String nmEmp = fName.getText();
if(nmEmp.trim().isEmpty() || nmEmp.trim().equals("")){
JOptionPane.showMessageDialog(null, "Empty Name", "Name Confirmation", JOptionPane.YES_OPTION);
}
Why JOptionPane cannot stop flow of execution, in my application ? And java keep running to executing code below JOptionPane, if JOptionPane execution in true condition. And what reason, this happen?. Please help, Thank you
From Java documentation JOptionPane : https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Direct Use:
To create and use an JOptionPane directly, the standard pattern is
roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;

Why StringIndexOutOfBoundsException with subSequence?

I have a problem with Java and Android Studio; the following code was to be a backspace button:
else if(view == btnBackspace){
int expressionLength = expression.length() - 2;
String expressionNew = newExpression.subSequence(0, expressionLength); // new expression is the t
editText.setText(expressionNew); // prints out text
}
I'm trying do a backspace button, I don't know if this is the better way of make this. So, subSequence method return's me that is a char sequence then I put a .toString() :
String expressionNew = newExpression.subSequence(0, expressionLength).toString();
But it doesn't work! The app compiles but when I press my backspace button the app stops and terminal points out the following exception:
FATAL EXCEPTION: main
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-2
at java.lang.String.startEndAndLength(String.java:583)
at java.lang.String.substring(String.java:1464) [...]
Thanks!
Check the String your want to call first.
if(!newExpression.isEmpty() && newExpression.length() > expressionLength) {
String expressionNew = newExpression.subSequence(0, expressionLength).toString();
}
Check the length before applying the string operator. Try this:
int expressionLength = expression.length() - 2;
if(expressionLength>0)
{
String expressionNew = newExpression.subSequence(0, expressionLength).toString(); // new expression is the t
editText.setText(expressionNew); // prints out text
else {
editText.setText("Empty expression string");
}
It is just if you want to know
I was reseting the var expression and the correct code for this is:
else if(view == btnBackspace){
int expressionLength = expression.length() - 1;
if(!expression.isEmpty() && expression.length() > expressionLength) {
String expressionNew = expression.subSequence(0, expressionLength).toString();
editText.setText(expressionNew);
}
else {
editText.setText("Empty expression string");
}
}

how to use textfied and button to get results from an if else statement

how to use if else statement using textfield as an input then use a button to show results, I have tried using the code the bellow ,but it does not allow me to use " if else " condition for second condition , below is my code;
int x = Integer.parseInt(jTextField1.getText());
if (x>=120&x<200)
{JOptionPane.showMessageDialog(null, "select drum : PPJ upwards")};
if else (x>=230&x<=300);
{JOptionPane.showMessageDialog(null,"select drum :RRf Upwards");}
else
{JOptionPane.showMessageDialog(null,"incorrect entry");}
}
}
The correct way to write if else condition is as below
if (condition1 && condition2) {
} else if (condition3 && condition4) {
} else {
}
And if my assumtions are correct below s how your code should be written as following;
int x = Integer.parseInt(jTextField1.getText().toString()); // getText needs to be converted to String before parsing it to int.
if (x>=120 && x<200) { //in the if condition you need two && not one &
JOptionPane.showMessageDialog(null, "select drum : PPJ upwards");//semicolon should be here
}//putting semicolon here is wrong
else if (x>=230 && x<=300)//putting semicolon here is also wrong
{
JOptionPane.showMessageDialog(null,"select drum :RRf Upwards");
}
else {
JOptionPane.showMessageDialog(null,"incorrect entry");
}

Categories

Resources