Calculator Coding Errors. Please correct it - java

I have tried to code a simple calculator using GUI in java but got stuck with this code and repeatedly getting a message of 'ENTER VALID NUMBERS' .I'm open to suggestions. Suggest the possible corrections in my code.I think I have wrongly used the try and check the exception feature of the java.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.SwingConstants;
public class FIRSTCALC {
private JFrame frame;
private JTextField txtfield1;
private JTextField txtfield2;
private JTextField textfieldans;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FIRSTCALC window = new FIRSTCALC();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FIRSTCALC() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtfield1 = new JTextField();
txtfield1.setHorizontalAlignment(SwingConstants.LEFT);
txtfield1.setText("ENTER NUMBER 1 : ");
txtfield1.setBounds(28, 11, 178, 68);
frame.getContentPane().add(txtfield1);
txtfield1.setColumns(10);
txtfield2 = new JTextField();
txtfield2.setHorizontalAlignment(SwingConstants.LEFT);
txtfield2.setText("ENTER NUMBER 2 : ");
txtfield2.setBounds(228, 11, 175, 68);
frame.getContentPane().add(txtfield2);
txtfield2.setColumns(10);
JButton btnNewButton = new JButton("ADD");
btnNewButton.setToolTipText("TO ADD NUMBERS");
btnNewButton.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,sum;
try
{
num1=Integer.parseInt(txtfield1.getText());
num2=Integer.parseInt(txtfield2.getText());
sum=num1+num2;
textfieldans.setText(Integer.toString(sum));
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "ENTER VALID NUMBER");
}
}
});
btnNewButton.setBounds(61, 121, 120, 42);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("SUBTRACT");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,sum;
try
{
num1=Integer.parseInt(txtfield1.getText());
num2=Integer.parseInt(txtfield2.getText());
sum=num1-num2;
textfieldans.setText(Integer.toString(sum));
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "ENTER VALID NUMBER");
}
}
});
btnNewButton_1.setToolTipText("TO SUBTRACT NUMBERS");
btnNewButton_1.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton_1.setBounds(251, 121, 128, 42);
frame.getContentPane().add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("THE ANSWER IS :");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Sitka Text", Font.BOLD, 18));
lblNewLabel.setBounds(28, 192, 193, 58);
frame.getContentPane().add(lblNewLabel);
textfieldans = new JTextField();
textfieldans.setBounds(251, 196, 109, 48);
frame.getContentPane().add(textfieldans);
textfieldans.setColumns(10);
}
}

You are obviously getting an exception because you are appending or adding the entered number to the text already contained within one of the JTextFields. This would generate a NumberFormatException when trying to parse the string contained within JTextField to a Integer value with the Integer.parseInt() method. If anything other than numerical digits are supplied then this exception would be thrown. You're just making the exception display a Message Box indicating to the User to "ENTER VALID NUMBER".
If you want to keep the text within you text field components then apply a Focus Listener to highlight the text currently in the component so that it gets overwritten when the User enters a number. Generally this pre-text is in a lighter gray color. Here is an example:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class FIRSTCALC {
private JFrame frame;
private JTextField txtfield1;
private JTextField txtfield2;
private JTextField textfieldans;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FIRSTCALC window = new FIRSTCALC();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FIRSTCALC() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setAlwaysOnTop(true);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtfield1 = new JTextField("Enter First Number");
txtfield1.setForeground(Color.lightGray);
// Add a Focus Listener to txtfield1
txtfield1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfield1.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
txtfield1.setForeground(Color.black);
}
});
txtfield1.setHorizontalAlignment(SwingConstants.CENTER);
txtfield1.setBounds(28, 11, 178, 68);
txtfield1.setColumns(10);
frame.getContentPane().add(txtfield1);
txtfield2 = new JTextField("Enter Second Number");
txtfield2.setForeground(Color.lightGray);
// Add a Focus Listener to txtfield2
txtfield2.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfield2.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
txtfield2.setForeground(Color.black);
}
});
txtfield2.setHorizontalAlignment(SwingConstants.CENTER);
txtfield2.setBounds(228, 11, 175, 68);
txtfield2.setColumns(10);
frame.getContentPane().add(txtfield2);
JButton btnNewButton = new JButton("ADD");
btnNewButton.setToolTipText("TO ADD NUMBERS");
btnNewButton.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int num1, num2, sum;
try {
num1 = Integer.parseInt(txtfield1.getText());
num2 = Integer.parseInt(txtfield2.getText());
sum = num1 + num2;
textfieldans.setText(Integer.toString(sum));
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "<html><center>The following formula:<br><br>"
+ "<font size='4' color=red>" + txtfield1.getText() +
"</font> + <font size='4' color=red>"+ txtfield2.getText() +
"</font><br><br>contains invalid digits!</center></html>");
}
}
});
btnNewButton.setBounds(61, 121, 120, 42);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("SUBTRACT");
btnNewButton_1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int num1, num2, sum;
try {
num1 = Integer.parseInt(txtfield1.getText());
num2 = Integer.parseInt(txtfield2.getText());
sum = num1 - num2;
textfieldans.setText(Integer.toString(sum));
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "<html><center>The following formula:<br><br>"
+ "<font size='4' color=red>" + txtfield1.getText() +
"</font> - <font size='4' color=red>"+ txtfield2.getText() +
"</font><br><br>contains invalid digits!</center></html>");
}
}
});
btnNewButton_1.setToolTipText("TO SUBTRACT NUMBERS");
btnNewButton_1.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton_1.setBounds(251, 121, 128, 42);
frame.getContentPane().add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("THE ANSWER IS :");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Sitka Text", Font.BOLD, 18));
lblNewLabel.setBounds(28, 192, 193, 58);
frame.getContentPane().add(lblNewLabel);
textfieldans = new JTextField();
textfieldans.setHorizontalAlignment(SwingConstants.CENTER);
textfieldans.setBounds(251, 196, 109, 48);
textfieldans.setColumns(10);
frame.getContentPane().add(textfieldans);
frame.setLocationRelativeTo(null);
}
}

Related

How do you select CSV file to perform calculations on based on user input?

I'm currently making a user-input based program on Java Eclipse that is supposed perform calculations on data from a local csv file the user selects. The GUI code below is the source code that I have been using to make the GUI for the program. While I have managed to create the GUI, I am having trouble with "combining" the code listed under "CSVReader," which is a class I created, with the code for the GUI so that the user can select the CSV file. The user is supposed to select this CSV file by typing its path name into the text field box on the GUI.
Any help would be appreciated
GUI CODE
//GUI CODE
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextField;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField txtCountryChosen;
/**
* #wbp.nonvisual location=71,14
*/
private final JTextField Program = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Program.setText("Statistics Manager");
Program.setColumns(10);
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Submit file path");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String textFieldValue = textField.getText();
}
});
btnNewButton.setBounds(145, 48, 150, 25);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(116, 13, 200, 22);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("Mean GDP");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(0, 154, 97, 25);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Mean GDP_per_capita");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_2.setBounds(250, 154, 170, 25);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Mean pop");
btnNewButton_3.setBounds(109, 154, 120, 25);
frame.getContentPane().add(btnNewButton_3);
txtCountryChosen = new JTextField();
txtCountryChosen.setBounds(42, 104, 116, 22);
frame.getContentPane().add(txtCountryChosen);
txtCountryChosen.setColumns(10);
JButton btnNewButton_4 = new JButton("Select country");
btnNewButton_4.setBounds(270, 103, 150, 25);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Print Results in Txt File");
btnNewButton_5.setBounds(131, 201, 200, 20);
frame.getContentPane().add(btnNewButton_5);
}
}
CSVReader
//CSVREADER
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class CSVReader {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter file path name");
String file_path_name = scan.nextLine();
System.out.println(file_path_name);
String path= file_path_name;
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while((line = br.readLine()) !=null){
String[] values = line.split(",");
System.out.println("Country: " + values[0] + ", Year: " + values[2] + ", GDP: " + values[6] + ", GDP_per_capita: " + values[12] + ", Population: " + values[10]);
/*PrintStream myconsole= new PrintStream(new File("E://java.txt"));
System.setOut(myconsole);
myconsole.print(path);*/
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

is the method to create simple login wrong

I am a newbie in Java GUI development and I am stuck in the following code.
I am open to suggestions. I am actually trying to create a simple login that gives OK if the password is matched to the number 3124, and otherwise shows the error message. Please help me.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testing window = new testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
final int num;
num=Integer.parseInt(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(num==3124)
{JOptionPane.showMessageDialog(null, "correct");}
else
{JOptionPane.showMessageDialog(null, "wrong");}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}
You were checking the password even before the user has had the chance to enter anything into the text box. You need to get and check the value of num in the event listener code i.e. in actionPerformed. Also, don't convert the password to int (someone may enter some non-numeric string).
This code below works better.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class Testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing window = new Testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String num;
num = (password.getText());
if (num.equalsIgnoreCase("3124")) {
JOptionPane.showMessageDialog(null, "correct");
} else {
JOptionPane.showMessageDialog(null, "wrong");
}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}

What should I do when it says "Syntax error, insert "}" to complete ClassBody" [duplicate]

This question already has answers here:
syntax error: insert } to complete ClassBody
(11 answers)
Closed 6 years ago.
I'm having trouble with the error "Syntax error, insert "}" to complete ClassBody"
and i don't know what to do.
This is my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class Password {
private JFrame frame;
private JTextField PassField;
private JTextField txtSecretPasswords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Password window = new Password();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Password() {
initialize();
}/* Here*/
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 700, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
PassField = new JTextField();
PassField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
PassField.setBounds(0, 42, 150, 32);
frame.getContentPane().add(PassField);
PassField.setColumns(10);
txtSecretPasswords = new JTextField();
txtSecretPasswords.setEditable(false);
txtSecretPasswords.setText("Secret passwords");
txtSecretPasswords.setBounds(0, 11, 131, 20);
frame.getContentPane().add(txtSecretPasswords);
txtSecretPasswords.setColumns(10);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
private JTextField txtMessage;
private JTextField txtMessage2;
private JTextField txtMessage3;
private JTextField txtPass2;
private JButton btnEnter2;
public void actionPerformed(ActionEvent e) {
int pass;
pass = Integer.parseInt(PassField.getText());
if (pass == 3333) {
txtMessage = new JTextField();
txtMessage.setEditable(false);
txtMessage.setText("Postal Code: 3333");
txtMessage.setBounds(0, 100, 130, 20);
frame.getContentPane().add(txtMessage);
txtMessage.setColumns(10);
txtMessage2 = new JTextField();
txtMessage2.setEditable(false);
txtMessage2 .setText("Email password: 3333");
txtMessage2.setBounds(0, 125, 150, 20);
frame.getContentPane().add(txtMessage2);
txtMessage2.setColumns(10);
txtMessage3 = new JTextField();
txtMessage3.setEditable(false);
txtMessage3.setText("Steam password: 3333");
txtMessage3.setBounds(0, 170, 200, 20);
frame.getContentPane().add(txtMessage3);
txtMessage3.setColumns(10);
btnEnter2 = new JButton();
btnEnter2.setText("Enter");
btnEnter2.setBounds(175, 250, 100, 15);
frame.getContentPane().add(btnEnter2);
btnEnter2.addActionListener(new ActionListener() {
public void actionPreformed(ActionEvent e) {
int pass2;
pass2 = Integer.parseInt(txtPass2.getText());
if (pass2 == 030303) {
txtMessage3 = new JTextField();
txtMessage3.setEditable(false);
txtMessage3.setText("Steam password: 3333");
txtMessage3.setBounds(0, 170, 200, 20);
frame.getContentPane().add(txtMessage3);
txtMessage3.setColumns(10);
}
else {
JOptionPane.showMessageDialog(null, "Wrong");
}
}/* And here*/);
txtPass2 = new JTextField();
txtPass2.setEditable(true);
txtPass2.setBounds(0, 250, 150, 20);
frame.getContentPane().add(txtPass2);
txtPass2.setColumns(10);
}
else {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
});
btnEnter.setBounds(160, 47, 99, 23);
frame.getContentPane().add(btnEnter);
}
I know its a long one. I've tried to look through the code but I'm not that experienced with Java or coding.
I don't know why the errors there or what to do so if you could help it would be appreciated a lot by a beginner!
I suggest using a good editor or IDE. Any decent editor should allow to "go to matching parenthesis". For example, if you use vi, position the cursor on a brace and type "%" to go to the matching one. You can use this to verify that parenthesis are matching as you expect.
IDEs such as Eclipse or IntelliJ allow you to reformat code, which will also help you spot where you're missing a closing brace. They also offer other invaluable features when programming in Java, so I strongly suggest spending the time to install and learn one.
This said, you're missing a close brace right before the "And here" comment.
You should use an IDE in order to be able to indent your code and see any missing curly braces.
If you use auto-indent from your text editor, you notice that the last '}' is still indented by one tab.
It means there are more { than }.
With a good IDE (e.g. Eclipse) it's easier to find out where it should be added (Once at the end, once before the last /* And here */ comment). Note that the first error shown by Eclipse isn't the right location in this case.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class Password
{
private JFrame frame;
private JTextField PassField;
private JTextField txtSecretPasswords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Password window = new Password();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Password() {
initialize();
}/* Here */
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 700, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
PassField = new JTextField();
PassField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
PassField.setBounds(0, 42, 150, 32);
frame.getContentPane().add(PassField);
PassField.setColumns(10);
txtSecretPasswords = new JTextField();
txtSecretPasswords.setEditable(false);
txtSecretPasswords.setText("Secret passwords");
txtSecretPasswords.setBounds(0, 11, 131, 20);
frame.getContentPane().add(txtSecretPasswords);
txtSecretPasswords.setColumns(10);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
private JTextField txtMessage;
private JTextField txtMessage2;
private JTextField txtMessage3;
private JTextField txtPass2;
private JButton btnEnter2;
public void actionPerformed(ActionEvent e) {
int pass;
pass = Integer.parseInt(PassField.getText());
if (pass == 5441) {
txtMessage = new JTextField();
txtMessage.setEditable(false);
txtMessage.setText("Postal Code: 42658");
txtMessage.setBounds(0, 100, 130, 20);
frame.getContentPane().add(txtMessage);
txtMessage.setColumns(10);
txtMessage2 = new JTextField();
txtMessage2.setEditable(false);
txtMessage2.setText("Email password: Vauxhal1");
txtMessage2.setBounds(0, 125, 150, 20);
frame.getContentPane().add(txtMessage2);
txtMessage2.setColumns(10);
txtMessage3 = new JTextField();
txtMessage3.setEditable(false);
txtMessage3.setText("Steam password: Vauxhal12");
txtMessage3.setBounds(0, 170, 200, 20);
frame.getContentPane().add(txtMessage3);
txtMessage3.setColumns(10);
btnEnter2 = new JButton();
btnEnter2.setText("Enter");
btnEnter2.setBounds(175, 250, 100, 15);
frame.getContentPane().add(btnEnter2);
btnEnter2.addActionListener(new ActionListener() {
public void actionPreformed(ActionEvent e) {
int pass2;
pass2 = Integer.parseInt(txtPass2.getText());
if (pass2 == 030303) {
txtMessage3 = new JTextField();
txtMessage3.setEditable(false);
txtMessage3.setText("Steam password: Vauxhal12");
txtMessage3.setBounds(0, 170, 200, 20);
frame.getContentPane().add(txtMessage3);
txtMessage3.setColumns(10);
} else {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}/* And here */);
txtPass2 = new JTextField();
txtPass2.setEditable(true);
txtPass2.setBounds(0, 250, 150, 20);
frame.getContentPane().add(txtPass2);
txtPass2.setColumns(10);
} else {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
});
btnEnter.setBounds(160, 47, 99, 23);
frame.getContentPane().add(btnEnter);
}
}
PS: If you just want to use a basic text editor, Java is the wrong language. Either use Java + full IDE (Netbeans or Eclipse), or Ruby/Python with pluma/notepad2/vim/...
The problem, as many others have suggested here, is in the balancing of the braces, meaning each { opens a block of code and thus needs a matching } to close that block of code.
IDEs do make it easier to do this matching for you, many free text editors are available to do this matching for you.
So a few changes to your code:
This line }/* And here*/); delete /* And here*/ and replace it with }.
Next, the main class public class Password needs to be closed on the last line with a }.
Lastly, since the btnEnter2 needs to override the addActionListener abstract method, you have a typo in line public void actionPreformed(ActionEvent e) {, actionPreformed should be spelled actionPerformed to successfully override the addActionListener anonymous method.
The final code should resemble:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class Password {
private JFrame frame;
private JTextField PassField;
private JTextField txtSecretPasswords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Password window = new Password();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Password() {
initialize();
}/* Here*/
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 700, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
PassField = new JTextField();
PassField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
PassField.setBounds(0, 42, 150, 32);
frame.getContentPane().add(PassField);
PassField.setColumns(10);
txtSecretPasswords = new JTextField();
txtSecretPasswords.setEditable(false);
txtSecretPasswords.setText("Secret passwords");
txtSecretPasswords.setBounds(0, 11, 131, 20);
frame.getContentPane().add(txtSecretPasswords);
txtSecretPasswords.setColumns(10);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
private JTextField txtMessage;
private JTextField txtMessage2;
private JTextField txtMessage3;
private JTextField txtPass2;
private JButton btnEnter2;
public void actionPerformed(ActionEvent e) {
int pass;
pass = Integer.parseInt(PassField.getText());
if (pass == 5441) {
txtMessage = new JTextField();
txtMessage.setEditable(false);
txtMessage.setText("Postal Code: 42658");
txtMessage.setBounds(0, 100, 130, 20);
frame.getContentPane().add(txtMessage);
txtMessage.setColumns(10);
txtMessage2 = new JTextField();
txtMessage2.setEditable(false);
txtMessage2 .setText("Email password: Vauxhal1");
txtMessage2.setBounds(0, 125, 150, 20);
frame.getContentPane().add(txtMessage2);
txtMessage2.setColumns(10);
txtMessage3 = new JTextField();
txtMessage3.setEditable(false);
txtMessage3.setText("Steam password: Vauxhal12");
txtMessage3.setBounds(0, 170, 200, 20);
frame.getContentPane().add(txtMessage3);
txtMessage3.setColumns(10);
btnEnter2 = new JButton();
btnEnter2.setText("Enter");
btnEnter2.setBounds(175, 250, 100, 15);
frame.getContentPane().add(btnEnter2);
btnEnter2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int pass2;
pass2 = Integer.parseInt(txtPass2.getText());
if (pass2 == 030303) {
txtMessage3 = new JTextField();
txtMessage3.setEditable(false);
txtMessage3.setText("Steam password: Vauxhal12");
txtMessage3.setBounds(0, 170, 200, 20);
frame.getContentPane().add(txtMessage3);
txtMessage3.setColumns(10);
}
else {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
});
txtPass2 = new JTextField();
txtPass2.setEditable(true);
txtPass2.setBounds(0, 250, 150, 20);
frame.getContentPane().add(txtPass2);
txtPass2.setColumns(10);
}
else {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
});
btnEnter.setBounds(160, 47, 99, 23);
frame.getContentPane().add(btnEnter);
}
}
Hope this helps.
Insert } at the start of line 122 and at the end of code to complete classBody.
But you should really consider Roberto Attia's suggestion.

How can activate another gui class with JButton

I have two GUI classes named Menu and convert. I want to run the convert class when I click the "open" button. It looks so simple, but I couldn't figure it out.
Menu class
package com.ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnConvert = new JButton("open");
btnConvert.setBounds(44, 52, 89, 23);
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//???
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnConvert);
}
}
convert class
package com.ui;
import java.awt.EventQueue;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class convert {
private JFrame frmTitle;
private JTextField textField;
private double value;
private ButtonGroup group;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
convert window = new convert();
window.frmTitle.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public convert() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTitle = new JFrame();
frmTitle.setTitle("TITLE");
frmTitle.setBounds(100, 100, 450, 300);
frmTitle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTitle.getContentPane().setLayout(null);
JLabel lblInputValue = new JLabel("Input value:");
lblInputValue.setBounds(29, 22, 79, 14);
frmTitle.getContentPane().add(lblInputValue);
textField = new JTextField();
textField.setBounds(22, 47, 86, 20);
frmTitle.getContentPane().add(textField);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Convert", TitledBorder.LEADING, TitledBorder.TOP, null, Color.RED));
panel.setBounds(29, 118, 264, 133);
frmTitle.getContentPane().add(panel);
panel.setLayout(null);
final JRadioButton rdbtnKelvin = new JRadioButton("Kelvin");
rdbtnKelvin.setBounds(6, 30, 67, 23);
panel.add(rdbtnKelvin);
final JRadioButton rdbtnFahrenheit = new JRadioButton("Fahrenheit");
rdbtnFahrenheit.setBounds(71, 30, 77, 23);
panel.add(rdbtnFahrenheit);
final JRadioButton rdbtnCelcius = new JRadioButton("Celcius");
rdbtnCelcius.setBounds(174, 30, 67, 23);
panel.add(rdbtnCelcius);
group = new ButtonGroup();
group.add(rdbtnCelcius);
group.add(rdbtnFahrenheit);
group.add(rdbtnKelvin);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Celcius", "Fahrenheit", "Kelvin"}));
comboBox.setBounds(177, 47, 116, 20);
frmTitle.getContentPane().add(comboBox);
JButton btnConvert = new JButton("CONVERT");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value = Double.parseDouble(textField.getText().toString());
if(comboBox.getSelectedItem().toString().equals("Celcius")){
if(rdbtnCelcius.isSelected()==true){
value = value;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= 1.8*value +32;
}
else{
value =value+273;
}
}
else if (comboBox.getSelectedItem().toString().equals("Fahrenheit")){
if(rdbtnFahrenheit.isSelected()==true){
value = value;
}
else if (rdbtnCelcius.isSelected()==true){
value= (value-32)*1.8;
}
else{
value =(value-32)/1.8+273;
}
}
else{
if(rdbtnCelcius.isSelected()==true){
value = value-273;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= value -273*1.8+32;
}
else{
value =value;
}
}
textField.setText(value +"");
textField.setEnabled(false);
}
});
btnConvert.setBounds(303, 114, 89, 23);
frmTitle.getContentPane().add(btnConvert);
JButton btnClear = new JButton("CLEAR");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField.setEnabled(true);
comboBox.setSelectedIndex(0);
rdbtnKelvin.setSelected(true);
}
});
btnClear.setBounds(303, 170, 89, 23);
frmTitle.getContentPane().add(btnClear);
}
}
First of all, class names and constructors should start with an upper case letter, like you did it for class Menu, but not for class convert.
A Java programm should have just one and only one main method for all classes. So, delete complete your main method from Convert class, put new Convert(); in the actionPerformed() method of btnConvert in Menu class:
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Convert();
}
});
and add frmTitle.setVisible(true); to the end of the initialize() method of Convert class.
First, your class names should begin with a capital letter, so instead of "convert" it should be "Convert.
Create a public method in Convert:
public JFrame getFrame() {
return frmTitle;
}
Then in your button's actionPerformed() method, just:
Convert w = new Convert();
w.getFrame().setVisible(true);

Java GUI not appearing correctly in IDE

I am using windows 8, 64 bit.
I am learning GUI in Java. Generally I use eclipse IDE. I have also installed Net-beans.
I am trying to do a simple GUI program which will add two number and show their result. But the problem is that when I am running the program from IDE it is looking like this. . But when I am running this same class file from command line it is showing correctly. I have test the same code in both eclipse and Net-beans. But the result is same.
Source code for first picture.
import javax.swing.JOptionPane; // program uses JOptionPane
public class Addition
{
public static void main( String[] args )
{
// obtain user input from JOptionPane input dialogs
String firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
// convert String inputs to int values for use in a calculation
int number1 = Integer.parseInt( firstNumber );
int number2 = Integer.parseInt( secondNumber );
int sum = number1 + number2; // add numbers
// display result in a JOptionPane message dialog
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum Integers", JOptionPane.PLAIN_MESSAGE );
} // end method main
} // end class Addition
then I have made another simple program by window-builder which will perform the four arithmetic operattion between two number. But the result is same for this case. Another picture has added named picture two.
source code for second picture.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Button;
import java.awt.Label;
import javax.swing.JMenuBar;
import javax.swing.JToggleButton;
import javax.swing.JCheckBox;
import java.awt.Color;
import java.awt.SystemColor;
import javax.swing.SwingConstants;
import javax.swing.JTable;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class test extends JFrame {
private JPanel contentPane;
private JTextField one;
private JTextField two;
private JTextField ans;
private JLabel lblNumone;
private JLabel lblNumtwo;
private JButton btnDiv;
private JButton btnMult;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
test frame = new test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public test()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 294, 322);
contentPane = new JPanel();
contentPane.setBackground(Color.GREEN);
contentPane.setForeground(SystemColor.desktop);
contentPane.setBorder(new EmptyBorder(19, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
one = new JTextField();
one.setBounds(125, 5, 89, 25);
contentPane.add(one);
one.setColumns(10);
two = new JTextField();
two.setBounds(125, 50, 89, 25);
contentPane.add(two);
two.setColumns(20);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 + num2;
ans.setText(Integer.toString(answer));
}catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnAdd.setBounds(125, 86, 89, 23);
contentPane.add(btnAdd);
JButton btnMinus = new JButton("Minus");
btnMinus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 - num2;
ans.setText(Integer.toString(answer));
}catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnMinus.setBounds(125, 119, 89, 23);
contentPane.add(btnMinus);
ans = new JTextField();
ans.setBounds(125, 221, 89, 25);
contentPane.add(ans);
ans.setColumns(10);
JLabel lblAnswer = new JLabel("Answer");
lblAnswer.setBounds(58, 230, 46, 14);
contentPane.add(lblAnswer);
lblNumone = new JLabel("NumberOne ");
lblNumone.setBounds(10, 10, 78, 14);
contentPane.add(lblNumone);
lblNumtwo = new JLabel("NumberTwo");
lblNumtwo.setBounds(10, 55, 78, 14);
contentPane.add(lblNumtwo);
btnDiv = new JButton("Div");
btnDiv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 / num2;
ans.setText(Integer.toString(answer));
}catch (Exception eDiv)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnDiv.setBounds(125, 153, 89, 23);
contentPane.add(btnDiv);
btnMult = new JButton("Mult");
btnMult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 * num2;
ans.setText(Integer.toString(answer));
}catch (Exception eMult)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnMult.setBounds(125, 187, 89, 23);
contentPane.add(btnMult);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(293, 28, 200, 50);
contentPane.add(menuBar);
}
}
it is not appearing correctly in IDE, but when the class file is running in command line, it is appearing correctly.
I have updated my JDK.
what may the cause and solution?

Categories