Using JTextField for user input - java

Thanks for your help guys...now the program works and runs like it should.. but I have 2 more question.
1.How can I get the output into a JTestField t4 or t5
2.How can I close the application using the JButton Buton3
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TriangleFarfan{
JFrame Triangle = new JFrame("Triangle Calculator");
JButton Button1 = new JButton ("Area");
JButton Button2 = new JButton("Perimeter");
JButton Button3 = new JButton("Close");
JTextField t1 = new JTextField(20);
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
JPanel j1 = new JPanel (new FlowLayout());
JLabel l1 = new JLabel("Enter side 1:");
JTextField t2 = new JTextField();
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
JPanel j2 = new JPanel (new FlowLayout());
JLabel l2 = new JLabel("Enter side 2:");
JTextField t3 = new JTextField();
String t3TextBox = t3.getText();
double side3 = Double.parseDouble(t3TextBox);
JPanel j3 = new JPanel (new FlowLayout());
JLabel l3 = new JLabel("Enter side 3:");
JTextField t4 = new JTextField();
JPanel j4 = new JPanel (new FlowLayout());
JLabel l4 = new JLabel("Area Result");
JTextField t5 = new JTextField(20);
JPanel j5 = new JPanel (new FlowLayout());
JLabel l5 = new JLabel("Perimeter Result");
public TriangleFarfan()
{
j1.add(l1);
j1.add(t1);
j2.add(l2);
j2.add(t2);
j3.add(l3);
j3.add(t3);
j4.add(l4);
j4.add(t4);
j5.add(l5);
j5.add(t5);
Triangle.add(j1);
Triangle.add(j2);
Triangle.add(j3);
Triangle.add(j4);
Triangle.add(j5);
Triangle.add(Button1);
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Triangle.add(Button2);
Button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Perimeter Button");
}
});
Triangle.add(Button3);
Button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Close Button");
}
});
Triangle.setLayout(new FlowLayout());
Triangle.setSize(450,400);
Triangle.setVisible(true);
Triangle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

In addition to missing a main method, as Reimeus pointed out, your order of instructions is wrong. You are trying to read the user input before anything is even shown on the screen, and even before an object is created. For example, this line:
String t1TextBox = t1.getText();
tries to obtain a text from a TextBox that wasn't even added to a Panel that wasn't yet created.
To solve this, you need to rethink the logic of your program. Here are a few hints:
avoid assignments outside methods. Instead of writing
JFrame Triangle = new JFrame("Triangle Calculator");
declare the variable in the class body like this:
JFrame Triangle;
and assign it inside the constructor like this:
Triangle = new JFrame("Triangle Calculator");
Build the whole UI, then worry about listeners. This way you can be sure that you are not referencing an UI element that does not exist when getting the user input.
Get the user input inside the listeners, like this:
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// get the size of side1 from the textbox
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
// get the size of side2 from the textbox
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
// now we can calculate the area
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});

Add a main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TriangleFarfan();
}
});
}
The declaration
JTextField t1 = new JTextField(20);
doesn't set the value in the JTextField to 20. Instead it sets the number of columns for the JTextComponent but with an empty String. Therefore the line
double side1 = Double.parseDouble(t1TextBox);
will throw an NumberFormatException on startup.

Related

JButton won't show another jframe

I'm currently working on a project and whenever I click the jbutton on jframe 2 (the 2nd jframe after the log in) "set appointments"/btn1, it won't show the other jframe which is jframe3.
The program itself works but the button won't show the other jframe.
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Container;
public class me {
public static void main (String [] args) {
JFrame jframe = new JFrame();
jframe.setSize(450,350);
jframe.getContentPane().setBackground(Color.WHITE);
ImageIcon c = new ImageIcon("teethlogo5.png");
JLabel bi = new JLabel("",c,JLabel.RIGHT);
bi.setBounds(25,35,400,40);
jframe.add(bi);
ImageIcon a = new ImageIcon("teethlogo2.png");
JLabel si = new JLabel("",a,JLabel.RIGHT);
si.setBounds(50,90,100,120);
jframe.add(si);
JLabel jl1 = new JLabel("Username:");
jl1.setBounds(190,100,100,50);
jframe.add(jl1);
JTextField uss = new JTextField();
uss.setBounds(270,110,120,30);
jframe.add(uss);
JLabel jl2 = new JLabel("Password:");
jl2.setBounds(190,150,100,50);
jframe.add(jl2);
JPasswordField pss = new JPasswordField();
pss.setBounds(270,160,120,30);
jframe.add(pss);
JButton enter = new JButton("log in");
enter.setBounds(250,210,100,40);
jframe.add(enter);
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String userText;
String pwdText;
userText = uss.getText();
pwdText = String.valueOf(pss.getPassword());
if (userText.equals("user") && pwdText.equals("pass")) {
JOptionPane.showMessageDialog(null, "LoginSuccessful","Message",JOptionPane.PLAIN_MESSAGE);
jframe.setVisible(false);
JFrame jframe2 = new JFrame();
jframe2.setSize(850,560);
jframe2.getContentPane().setBackground(Color.WHITE);
ImageIcon b = new ImageIcon("teethlogo4.png");
JLabel sii = new JLabel("",b,JLabel.RIGHT);
sii.setBounds(10,0,600,100);
jframe2.add(sii);
JButton btn1 = new JButton("Set an Appointment");
btn1.setBounds(100,100,150,30);
jframe2.add(btn1);
JButton btn2 = new JButton("View Appointments");
btn2.setBounds(270,100,150,30);
jframe2.add(btn2);
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (btn1.isSelected()){
jframe2.setVisible(false);
JFrame jframe3 = new JFrame();
jframe3.setSize(850,560);
jframe3.getContentPane().setBackground(Color.WHITE);
jframe3.setLayout(null);
jframe3.setVisible(true);
jframe3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
});
jframe2.setLayout(null);
jframe2.setVisible(true);
jframe2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else {
JOptionPane.showMessageDialog(null, "Invalid Username or Password","Message",JOptionPane.PLAIN_MESSAGE);
uss.setText(null);
pss.setText(null);
}
}
});
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setResizable(false);
jframe.setLayout(null);
jframe.setVisible(true);
}
}
I'm a beginner in java and I really want to know how to fix this problem.
You're shooting your own self in the foot with:
if (btn1.isSelected()){
// ...
}
There is no need for this block of code -- a button isn't "selected" unless it extends from JToggleButton (such as JCheckBox) and has been checked, something that a JButton does not allow, and what is more, it is preventing the listener's code that it holds from running. Solution: just get rid of it.

JOptionpane.showMessageDialog not working inside of if-statement (event handler Program)

Context
I'm trying to build a percentage calculator using JFrame and event handling by having blank text fields and "enter" buttons and displaying the answer depending on which button they click (two different calculations for each button).
Problem
Thing is, when I put the JOptionPane.showMessageDialog line inside of the if/else if statement (all in the actionPerformed method), the program runs, but clicking the buttons does nothing. But if I put it outside of the statements, it says the answer variable is undeclared.
I realize a percentage calculator can be done in a million other, simpler ways, but this is simply what I had in mind and wanted to see if I could do it (I'm a complete beginner).
Code
public class PercentageCalc extends JFrame{
private JTextField item2, item4, item5, item7;
private JButton button, button2;
public PercentageCalc(){
super("Percentage Calculator");
setLayout(new FlowLayout());
JLabel item1 = new JLabel("What is");
add(item1);
JTextField item2 = new JTextField(3);
add(item2);
JLabel item3 = new JLabel("% of");
add(item3);
JTextField item4 = new JTextField(2);
add(item4);
button = new JButton("Enter");
add(button);
JLabel spacer = new JLabel(" ");
add(spacer);
JTextField item5 = new JTextField(3);
add(item5);
JLabel item6 = new JLabel("is what % of");
add(item6);
JTextField item7 = new JTextField(3);
add(item7);
button2 = new JButton("Enter");
add(button2);
thehandler handler = new thehandler();
button.addActionListener(handler);
button2.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String strx;
String stry;
double x, y, answer;
if(e.getSource()==button){
strx = item2.getText();
stry = item4.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
}
else if(e.getSource()==button2){
strx = item5.getText();
stry = item7.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = x/y*100;
JOptionPane.showMessageDialog(null, answer);
}
}
You have member-variable and local variable with the same name. Please read ere and here about it.
Here is the corrected variant of you program
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class PrecentageCalc extends JFrame {
private JTextField item2, item4, item5, item7;
private JButton button, button2;
public PrecentageCalc() {
super("Percentage Calculator");
setLayout(new FlowLayout());
JLabel item1 = new JLabel("What is");
add(item1);
item2 = new JTextField(3);
add(item2);
JLabel item3 = new JLabel("% of");
add(item3);
item4 = new JTextField(2);
add(item4);
button = new JButton("Enter");
add(button);
JLabel spacer = new JLabel(" ");
add(spacer);
item5 = new JTextField(3);
add(item5);
JLabel item6 = new JLabel("is what % of");
add(item6);
item7 = new JTextField(3);
add(item7);
button2 = new JButton("Enter");
add(button2);
thehandler handler = new thehandler();
button.addActionListener(handler);
button2.addActionListener(handler);
}
private class thehandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String strx;
String stry;
double x, y, answer;
if (e.getSource() == button) {
strx = item2.getText();
stry = item4.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
} else if (e.getSource() == button2) {
strx = item5.getText();
stry = item7.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = x / y * 100;
JOptionPane.showMessageDialog(null, answer);
}
}
}
public static void main(String[] args) {
JFrame frm = new PrecentageCalc();
frm.pack();
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
Use separate ActionListeners for your buttons. Both use the same calculation method with different parameters:
public PercentageCalc() {
// Part of your code
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
handleInput(item2.getText(), item4.getText());
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
handleInput(item5.getText(), item7.getText());
}
});
}
private void handleInput(final String strx, final String stry) {
final double x = Double.parseDouble(strx);
final double y = Double.parseDouble(stry);
final double answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
}

JTextField calculate JButton Multiply and JButton Divide. Why is it not printing my results when clicking either button?

I simply need to have two JTextFields that take in two numbers and when clicking the Multiply or Divide button it produces the answer. It looks good to me, but not good enough to work.. Please any help would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
String result;
JLabel introduction = new JLabel("Solve Math Problems");
Font myFont = new Font("Arial", Font.BOLD, 16);
JTextField jtNum1 = new JTextField(10);
JTextField jtNum2 = new JTextField(10);
JTextField jtResponse = new JTextField(10);
JButton multiply = new JButton(" X ");
JButton divide = new JButton(" / ");
JLabel answer = new JLabel("");
final int WIDTH = 400;
final int HEIGHT = 135;
public Calculator(){
super("My First Calculator");
setLayout(new FlowLayout());
setSize(WIDTH, HEIGHT);
introduction.setFont(myFont);
answer.setFont(myFont);
add(introduction);
add(jtNum1);
add(jtNum2);
add(multiply);
add(divide);
multiply.addActionListener(this);
divide.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
int int1 = Integer.parseInt(jtNum1.getText());
int int2 = Integer.parseInt(jtNum2.getText());
if (e.getSource() == multiply) {
jtResponse.setText(String.valueOf(int1*int2));
} else if (e.getSource() == divide) {
jtResponse.setText(String.valueOf(int1/int2));
System.out.println(jtResponse);
}
}
}
public class CalculatorAction {
public static void main(String[] args) {
Calculator frame = new Calculator();
frame.setVisible(true);
}
}
You must add the action listener to the button.
jbutton.addActionListener(new ActionListener()

How to turn a random int into a String for use in if/else?

So I'm writing a program for my AP Comp Sci class and I need some help with parsing ints and such.
How do I take a random integer and turn it into a string that can be used inside an if/else statement?
import java.awt.*;
import java.awt.event.*;
import java.awt.Container;
import javax.swing.*;
import java.lang.*;
import java.io.*;
import java.util.*;
class LibraryGUI {
// variables and objects
JFrame frame, frame2, frame3;
JPanel panel, panel2, panel3;
JLabel label, label2, label3, label4;
JButton button1;
JButton button2, button3, enter2;
JTextField username, logincred;
Random r = new Random();
public LibraryGUI()
{
frame = new JFrame("LexCorp Library");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Welcome to LexCorp Library");
button1 = new JButton("Login");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame3 = new JFrame("Find Account");
panel3 = new JPanel();
enter2 = new JButton("Enter");
frame3.setLayout(new GridLayout(1,1));
panel3.setBackground(Color.white);
panel3.setSize(700,700);
label4 = new JLabel("Enter account number");
logincred = new JTextField("\t\t");
logincred.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent j){
String choose = logincred.getText();
}
});
panel3.add(label4);
panel3.add(logincred);
panel3.add(enter2);
frame3.getContentPane().add (panel3);
frame3.pack();
frame3.setVisible(true);
//internalcode
}
});
button2 = new JButton("Make a new Account");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent f){
//GUI Section
frame2 = new JFrame("Make a new account");
//frame2.setLayout(new GridLayout(4,4));
panel2 = new JPanel();
panel2.setLayout(new GridLayout(4,3));
//panel2.setLayout(new FlowLayout());
label2 = new JLabel("Account's name");
username = new JTextField();
int acc = r.nextInt(1000);
label3 = new JLabel("Your account number is " +acc);
button3 = new JButton("Enter");
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ent){
JOptionPane.showMessageDialog(frame, "Account Created");
frame2.dispose();
}
});
panel2.add(label2);
panel2.add(username);
panel2.add(button3);
panel2.add(label3);
frame2.pack();
username.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String user = username.getText();
System.out.println(user);
}
});
panel2.setSize(700,700);
panel2.setBackground(Color.LIGHT_GRAY);
frame2.getContentPane().add (panel2);
frame2.pack();
frame2.setVisible(true);
//internalCode
}
});
//panel properties
panel = new JPanel();
panel.setSize(700,700);
panel.setLayout(new GridLayout(10,10));
panel.setBackground(Color.yellow);
//add-ins
panel.add(label);
panel.add(button1);
panel.add(button2);
frame.getContentPane().add (panel);
}
public void display()
{
frame.pack();
frame.setVisible(true);
}
}
(take an..) integer and turn it into a string that can be used inside an IF ElSE
How about instead don't convert it? The conditions of an if statement can work with integers, and do it more easily than strings!
E.G.
int x = random.nextInt(100);
if (x < 50) {
//..
if an int primitive type goes with a string, then the result will be a string.
for example,
int b=3;
String bs = b+"";
then the bs will be "3"
If you are interested in programming, I will suggest you to read "Think in Java." Reading it helps me a lot.
Please use:
Integer.toString(int)
and not:
int + ""
It is the more elegant way and also easier to process by the JVM. It is not a complex operation either way but is the correct way to do it.

How to Validate a textfield in java

Hello I need some help validing textfield in my gui. My professor gave me a hint on how to do but it freezes up my program. I've tried other methods but if If I enter text the text field the next window doesn't show.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.*;
//import statements here
public class UserWindow extends JFrame
{
private JTextField nameField, ageField, creditCardField;
private JButton backButton, nextButton;
public UserWindow()
{
super("Please enter your information");
setSize(700,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4,2));
buildPanel();
setVisible(true);
}
private void buildPanel(){
nameField = new JTextField(10);
ageField = new JTextField(2);
creditCardField = new JTextField(10);
backButton = new JButton("Back");
nextButton = new JButton("Next");
nextButton.addActionListener(new NextButton());
backButton.addActionListener(new BackButton());
JLabel NameLabel = new JLabel("Please enter your name");
JLabel ageLabel = new JLabel("Enter your age");
JLabel creditCardLabel = new JLabel("Enter your credit card number");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
add(panel1);
add(panel2);
add(panel3);
add(panel4);
add(panel5);
add(panel6);
add(panel7);
add(panel8);
panel1.add(NameLabel);
panel2.add(nameField);
panel4.add(ageField);
panel6.add(creditCardField);
panel3.add(ageLabel);
panel5.add(creditCardLabel);
panel7.add(backButton);
panel8.add(nextButton);
}//end of panel building
//action listeners for fields/buttons
private class NextButton implements ActionListener{
public void actionPerformed(ActionEvent e){
String str;
int age;
str = nameField.getText();
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
if(e.getSource() == nextButton)
new MovieSelection();
setVisible(false);
}
}
private class BackButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == backButton)
setVisible(false);
new SelectUserWindow();
}
}
}
You never assign a new value to str if it is initially the empty string.
I think you need something like
str = nameField.getText();
inside your while(true) loop.
It is freezing because you have a this:
if (str.equals("")){
JOptionPane.showMessageDialog(null,"Please enter your name.");
while(true){ //<- Runs forever
nameField.requestFocusInWindow();
if(!str.equals(""))
break;
}
}
AcId is correct when he say you never assign any value to str after you enter the loop (or the if). This means you never change the value of str and it will never not be equal to "" and it will run in the loop forever. The loop runs in the same thread as the user interface, so the user interface will not have time to do anything else (hence it is freezing).
It doesn't make sense to have a loop that runs forever in this situation. It seems you are trying to make the GUI busy wait until the user has entered a name. Don't do that. Instead check if the user have entered something, if not, alert the user and wait for the user to click the button again.
So remove the loop and use a simple if-else statement.
if (str.equals("")){ //User have not entered anything.
JOptionPane.showMessageDialog(null,"Please enter your name.");
nameField.requestFocusInWindow();
//Do NOT loop here.
}
else {
//Do everything you need to do when the user have entered something
}

Categories

Resources