I am working on a turtle graphics project and I'm attempting to retrieve a user input from a jtextfield (commField) which should be like: ' forward 100 ' I've attempted to do a string split and intparse however when the program is run, even when a correct command is entered it will go to the message error dialogue. After a few hours of turning the cogs in my brain I'm struggling to figure out why and so am asking for any help. If more of my code is needed for an answer that is fine, perhaps I'm focusing on the wrong thing.
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
}
});
Below is the full code block for those who want it:
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(commField.getText().contains("penup")) {
graphicsPanel.penUp();
}
else if(commField.getText().contains("pendown")) {
graphicsPanel.penDown();
}
else if(commField.getText().contains("turnright")) {
graphicsPanel.turnRight();
}
else if(commField.getText().contains("turnleft")) {
graphicsPanel.turnLeft();
}
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
System.out.println(commField);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("black")) {
graphicsPanel.black(Color.black);
}
else if(commField.getText().contains("green")) {
graphicsPanel.green(Color.green);
}
else if(commField.getText().contains("red")) {
graphicsPanel.red(Color.red);
}
else if(commField.getText().contains("reset")) {
graphicsPanel.clear();
}
else {
JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
}
commField.setText("");
graphicsPanel.repaint();
}
});
Line of interest:
String cForward = commField.toString();
JTextField.toString() does not return the content of the JTextField.
I checked my java 8 sources and found the following:
public String toString() {
return getClass().getName() + '[' + paramString() + ']';
}
However, the toString() method is intended to be a debugging utility. Unless its behavior is explicitly documented it is not recommended to rely on it programmatically.
For retrieving its text content, JTextField provides a separate method: JTextComponent#getText(). The line should therefore be changed to:
String cForward = commField.getText();
Related
I have a program to update vehicle inventory. I call the updateVehicle()...it should loop through the arrayList of vehicles to look for a match based on what the user input. In the if statement, if a match is found, update the vehicle in the arrayList with what the user input, call the displayCurrentVehicleEntry() and display the updated details to console. The code works and will update the vehicle.
However, if there is more than one vehicle in the arrayList, it will update it correctly, but not display the details of the updated vehicle (it displays the info for the last element in the arrayList).
In the displayCurrentVehicleEntry() it will grab the last element and display the details, which works correctly for the addVehicle().
I'm not sure how to get that to work for the updateVehicle().
public void updateVehicle(String makeCurrent, String modelCurrent, String colorCurrent, int yearCurrent, int mileageCurrent,
String makeUpdated, String modelUpdated, String colorUpdated, int yearUpdated, int mileageUpdated) {
try {
boolean found = false;
for (int i = 0; i < listOfVehicles.size(); i++) {
AutoInv vehicle = listOfVehicles.get(i);
if (vehicle.getMake().equalsIgnoreCase(makeCurrent)
&& vehicle.getModel().equalsIgnoreCase(modelCurrent)
&& vehicle.getColor().equalsIgnoreCase(colorCurrent)
&& vehicle.getYear() == yearCurrent
&& vehicle.getMileage() == mileageCurrent) {
vehicle.setMake(makeUpdated);
vehicle.setModel(modelUpdated);
vehicle.setColor(colorUpdated);
vehicle.setYear(yearUpdated);
vehicle.setMileage(mileageUpdated);
System.out.println("\nVehicle updated successfully!\n");
displayCurrentVehicleEntry(); //FIXME not working rethink
found = true;
}
}
if (!found) {
System.out.println("\nVehicle not found in inventory!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Failure");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void displayCurrentVehicleEntry() {
try {
AutoInv vehicle = listOfVehicles.get(listOfVehicles.size() - 1);
System.out.println("Make: " + vehicle.getMake().toUpperCase());
System.out.println("Model: " + vehicle.getModel().toUpperCase());
System.out.println("Color: " + vehicle.getColor().toUpperCase());
System.out.println("Year: " + vehicle.getYear());
System.out.println("Mileage: " + vehicle.getMileage());
System.out.println("");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Failure");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void addVehicle(AutoInv vehicle) throws Exception{
try {
if (listOfVehicles.add(vehicle)) {
System.out.println("\nFollowing vehicle added successfully:\n");
displayCurrentVehicleEntry();
}
else {
throw new Exception("\nFailed to add vehicle.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
// e.printStackTrace();
}
}
Modify the displayCurrentVehicleEntry() method, add a parameter to displayCurrentVehicleEntry() like this displayCurrentVehicleEntry(int index), and change AutoInv vehicle = listOfVehicles.get(listOfVehicles.size() - 1); to AutoInv vehicle = listOfVehicles.get(index);
in addVehicle, you can use displayCurrentVehicleEntry(listOfVehicles.size() - 1); and in updateVehicle you can use displayCurrentVehicleEntry(i); to select the vehicle you want to print
I think the user.contains is not reading every line and is only checking the first line. I had this working right earlier(I am testing the duplicate user portion of my code), but now my program is skipping :
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
I am not sure what I did, or how I managed to break my own program. Now its skipping all the way to:
else { if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
}
Where did I go wrong?
private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
String un = UserName.getText().trim();
String pw = Password.getText().trim();
HashSet hs= new HashSet();
HashSet users = new HashSet();
boolean goahead=true;
try {
Scanner Scan = new Scanner(new File("Login.txt"));
while (Scan.hasNextLine()) {
String authenticator = Scan.nextLine().trim();
String[] autparts=authenticator.split(" ");
String user = autparts[0].trim();
if (goahead){
if (users.contains(user)) {
if (user.equals(un)) {
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
} else {
hs.add(authenticator);
users.add(user);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (goahead) {
if (createAccount.isSelected() & (hs.contains(new String(un+" "+pw)))){
JOptionPane.showMessageDialog(null,"User Already Exsist! No Need to create a new account. ");
dispose();
} else {
if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
} else {
if (createAccount.isSelected()){
try {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Login.txt", true)));
output.println(un+" "+pw);
output.close();
} catch (IOException ex) {
System.out.printf("error %s/n", ex );
}
JOptionPane.showMessageDialog(null,"Welcome!"+" " + un+" "+"Please Relogin Now");
dispose();
}else {
JOptionPane.showMessageDialog(null, "user doesn't exist or password incorrect. ");
dispose();
}
}
}
}
the following is my output and whats in the txt file. :
I have formatted your code now:
String un = UserName.getText().trim();
if (goahead){
if (users.contains(user))
{
if (user.equals(un))
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
}
else
{
hs.add(authenticator);
users.add(user);
}
}
Now when the flag goahead is set to false dont we need to reset it to true somewhere? If HashSet contains user then why do you need to again compare name of user? You should have defined equals for the user itself. Nope?
You seem to chasing your tail, doing two things at one, reading the file/populating the Set AND checking for duplicates. Instead, do one at a time...
Something like...
// You could pre-load these and cache the result instead
// of reading it each time, but that's up to you
Map<String, String> credentials = new HashMap<>(25);
try (Scanner scan = new Scanner(new File("Login.txt"))) {
while (scan.hasNextLine()) {
String value = scan.nextLine();
String[] parts = value.split(" ");
credentials.put(parts[0], parts[1]);
}
} catch (IOException exp) {
exp.printStackTrace();
}
// Make your required checks here
if (credentials.containsKey(un)) {
if (credentials.get(un).equals(pw)) {
// Validated
} else {
// Wrong password
}
} else {
// New user...?
}
I'm having some trouble getting my code to compile.
This is a method that uses the class Value to save text to a file
public void saveEventsToFile() throws Exception {
String tmp = getEventsAsString();
value = Value.makeString(tmp);
Value.saveFile(value, "\\events" + "\\" + "YEAR" + "\\" + months[MONTH] + "\\" + DAY);
}
and this is part of a constructor of another object. I've got an actionlistener on a button (OK) and when that button is pressed, I want to call the saveEventsToFile method.
OK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int h, m;
h = (Integer) hourSpinner.getValue();
m = (Integer) minuteSpinner.getValue();
parentPanel.createNewEvent(parentPanel.selectedBox, parentWindow, textPane.getText(), h, m);
parentPanel.selectedBox.saveEventsToFile();
dispose();
}
});
If I add throws Exception on actionPerformed my code does not compile, and without it I get "Unhandled exception" error on the arentPanel.selectedBox.saveEventsToFile(); line
How could I get this to compile? I've not had much experience with exceptions.
As donfuxx said:
OK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int h, m;
h = (Integer) hourSpinner.getValue();
m = (Integer) minuteSpinner.getValue();
parentPanel.createNewEvent(parentPanel.selectedBox, parentWindow, textPane.getText(), h, m);
try {
parentPanel.selectedBox.saveEventsToFile();
} catch (ExeptionThaIsThrownBySaveEventsMethod e) {
// display error
}
dispose();
}
});
First of all if you do not use any particular element of ActionEvent, move logic of the method in the body of class you have.
OK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Integer h = (Integer) hourSpinner.getValue());
Integer m = (Integer) minuteSpinner.getValue();
saveEventsToFile(h,m)
dispose();
}
});
private void saveEventsToFile(Integer hour, Integer minute) {
if(hour == null || minute == null) {
throw new IllegalArgumentException("The parameters must not be null.")
}
parentPanel.createNewEvent(parentPanel.selectedBox, parentWindow, textPane.getText(), h,m);
try {
parentPanel.selectedBox.saveEventsToFile();
}catch(ExeptionThaIsThrownBySaveEventsMethod e) {
throw new IllegalStateException(e);
}
}
The things to remember here is that you should avoid to catch Exception as you may catch more than expected. This is important because after some exceptions application can proceed in other just need to be closed. In case the save cased an exception is might be possible that user can do something to retry the operation. In case the application must be close as can not longer operate you change use an unchecked (Runtime) Exception.
I am making a gui for POP3 commands I am having a problem editing my JTextPane in the GUI outside of the initialize() method
Part of the Action Listener:
public void actionPerformed(ActionEvent e)
{
String Input = Commands.getText();
verifyUserAndPass();
if(Input.substring(0).equals("QUIT")) {
System.exit(0);
}
if(Input.substring(0,4).equals("LIST")) {
ListCommand(Input);
}
if(Input.substring(0,4).equals("STAT")) {
ListCommand(Input);
}
if(Input.substring(0,4).equals("RETR")) {
try {
RETRCommand(Input);
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(Input.substring(0,4).equals("DELE")) {
Delete(Input);
}
if(Input.substring(0,4).equals("NOOP")) {
Display.setText("+OK");
}
if(Input.substring(0,4).equals("UIDL")) {
if(userEntered == true && passEntered == true) {
Display.setText("the UIDL is"+String.valueOf(ui));
ui++;
}else {
Display.setText("Please sign in first");
}
}
if(Input.substring(0,3).equals("TOP")) {
try {
TOP(Input);
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(Input.substring(0,4).equals("RSET")) {
Delete(Input);
}
the verifyUserAndPass method:
public void verifyUserAndPass() {
String Input = Commands.getText();
System.out.println(Input+"randomstring");
if(Input.substring(0, 4).equals("USER")) {
try {
if(verifyUser(Input.substring(5))) {
Display.setText("+OK");
Commands.setText("");
userEntered = true;
} else {
Display.setText("-ERR");
}
} catch (IOException e1) {
e1.printStackTrace();
Display.setText("-ERR");
}
}
if(Input.substring(0, 4).equals("PASS")) {
try {
if(userEntered == true) {
if(verifyPass(Input.substring(5))) {
Display.setText("+OK");
Display.setText("Welcome, you are now logged in");
Commands.setText("");
passEntered = true;
} else {
Display.setText("-ERR");
}
} else {
Display.setText("Please enter USER first");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Commands is a JTextField,
Display is a JTextPane.
for some reason, I can edit Commands outside the ActionListener but not Display
e.g. The Display.setText under the NOOP if works but not the one in verifyUserAndPass() method
but the Commands.setText works
What am I doing wrong?
It is quite hard to answer this question without you providing more details, but I can name a common issue:
Display may not be initialized, check your program's flow and then you can see why it is not being initialized.
Moreover, please abide the Java conventions for everyone's sake. Variables and methods are typed in camelcasing. So these ones would need to be changed:
String Input to String input.
ListCommand() to listCommand().
etc. I hope you get the idea.
I have a form that give Fname and Lname and Date and a method to write this information to a file.
If Fname or Lname contain digit, the program should display an error message and not run all below statements ,(like write to file and generate random number and...), and not exit.
since i dont know how to do like this, in my code i write if Fname or Lname have digit, exit !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
please help!
That's why you need checked exceptions. Just throw SomeException instead of System.exit(1) and process it properly in block:
catch (SomeException e){
jLabel6.setText("Error!");
}
Don't think that catching all exceptions is a good idea.
Here's one way you could do it:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
setLName(jTextField2.getText());
boolean firstNameHasDigit = havedigit(getFName());
boolean lastNameHasDigit = havedigit(getLName());
if (firstNameHasDigit || lastNameHasDigit) {
jLabel6.setText("Names cannot contain digits");
}
else {
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
As a general rule, try to stay away from using System.exit() in GUI-driven applications. It'll just make the whole program quit, leaving the user wondering what happened. System.exit() is usually better suited for command line applications that want to provide an exit code to the shell and it's a parallel to the system exit calls available in most operating systems.
Try this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(getFName())) {
jLabel6.setText("First name error!");
return;
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
jLabel6.setText("Last name error!");
return;
}
WriteToFile(getFName());
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
if(havedigit(getFName())==true) {
System.exit(1);
}
setLName(jTextField2.getText());
if(havedigit(lastName)==true) {
System.exit(1);
}
should be
if(havedigit(getFName())) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
setLName(jTextField2.getText());
if(havedigit(lastName)) {
JOptionPane.showMessageDialog(.....);
return; //get out of method, no need to continue
}
Search on Google about how to use JOptionPane.showMessageDialog.
In your if statements, instead of
System.exit(1);
You should have something
throw new MyException("Error Text");
and then your catch should look like this:
catch(MyException e){
jLabel6.setText(e.getMessage());
}
where MyException extends Exception.