Swing show up multiple child jframe - java

I was doing a project in JAVA Swing Netbeans IDE 7.1. I created one jFrame with some button and Dropdowns on it. On selecting a choice from the dropdown,another frame object is created and setVisible is set to true. But instead of showing one window, it is showing up 2 windows. There are other similar calls, but none have this issue, someone please help me. Thanks.
Code:
private void itemListItemStateChanged(java.awt.event.ItemEvent evt) {
String item = null;
String filename = null;
item = (String) itemList.getSelectedItem();
if(item=="P"){
filename="p";
description.setText("Description: P");
}
else if(item=="A"){
filename="a";
description.setText("Description: A");
}
else if(item=="R"){
filename="r";
description.setText("Description: R");
}
else if(item=="S"){
filename="s";
description.setText("Description: S");
}
else if(item=="X"){
displayText.setText("");
x xl = new x();
xl.setVisible(true);
}
else if(item=="Xx"){
filename="xx";
description.setText("Description: xx");
}
else {
System.out.println("invalid selection.");
}
if (item=="X"){
return;
}
else {
displayText.setText("");
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader ("/home/sfred/"+filename+".mile"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
line = b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
while (line != null){
displayText.append(line + "\n");
try {
line=b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

See The Use of Multiple JFrames, Good/Bad Practice? rather use :
1) JDialog
2) CardLayout which will allow you to flip between multiple components on a single JFrame.
You cannot compare String using ==operator must use equals(String s) or else it wont evaluate correctly
if(item.equals("X")) {
}
Rather use switch statement (Java 7+) when comparing String:
switch(item) {
case "P":
//do something
break;
case "X":
//do something
break;
default:
//if no match with above was found..
break;
}

Related

Prepared statement inserting String " " into database instead of null

my problem here is that if i try to leave blank spaces in my app, this code inserts an empty string into database on lines txtIme.getText() and txtPrezime.getText() and for that reason my if statement doesn't recognize .executeUpdate() as 0 and therefore doesn't print that nothing has been changed. Can I somehow change it so the app can reach my if statement if blank spaces are left in JTextField? Thank you.
private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {
try {
izraz = veza.prepareStatement("insert into autor (ime,prezime)" + "value (?,?)");
izraz.setString(1, txtIme.getText());
izraz.setString(2, txtPrezime.getText());
if (izraz.executeUpdate()== 0) {
JOptionPane.showMessageDialog(getRootPane(), "Nothing was changed.");
} else {
ucitajIzBaze();
ocistiPolja();
}
izraz.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
In case you dont want to use any lib
private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {
try {
if(txtIme.getText() == null || "".equals(txtIme.getText())) return;
if(txtPrezime.getText() == null || "".equals(txtPrezime.getText())) return;
izraz = veza.prepareStatement("insert into autor (ime,prezime)" + "value (?,?)");
izraz.setString(1, txtIme.getText());
izraz.setString(2, txtPrezime.getText());
if (izraz.executeUpdate()== 0) {
JOptionPane.showMessageDialog(getRootPane(), "Nothing was changed.");
} else {
ucitajIzBaze();
ocistiPolja();
}
izraz.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
But I recommend use any library for string related operations like
if(StringUtils.isBlank(txtIme.getText())) return;
if(StringUtils.isBlank(txtPrezime.getText())) return;
It in apache common lang package.

JTextfield - String split and intparse

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();

Why am I getting a false value at if (users.contains(user))?

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...?
}

NullPointerException error when editing JTextPane Outside ActionListener

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.

method flow control

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.

Categories