Adding 2 Integers using AWT - java

I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)

You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});

Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.

Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered

Related

Array input numbers 0-2 and output corresponding letters a,b,c

I have created the array with the elements ("A","B","C")
if the user enters ‘0’ output “A” to the outputlabel,e.g.,outputLabel.setText(array[0]).
I am just getting errors in the command prompt when i enter in the correct numbers. Any help with this would be highly appreciated. I have the gui created correctly. Just unsure about the array and outputs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiFrame extends JFrame implements ActionListener {
String[] stringArray = {"A", "B", "C"};
JTextField inputArea;
JLabel theOutputLabel;
public GuiFrame() {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Please enter the index of the array to
output: ");
JLabel outputLabel = new JLabel("Array index");
JTextField userInput = new JTextField ();
JButton inputButton = new JButton("Go");
String inputFromUser = userInput.getText();
Container contentPane = getContentPane();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label1);
panel.add(outputLabel);
panel.add(userInput);
panel.add(inputButton);
inputButton.addActionListener(this);
contentPane.add(panel);
setSize(250, 250);
setVisible(true);
userInput.setSize(250,50);
System.out.println(inputFromUser);
String stringArray[] = new String[3];
}
public static void main(String[] args){
new GuiFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
String userInput = inputArea.getText();
try {
do {
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
}while(e.getActionCommand().equals("0") || e.getActionCommand().equals("1") || e.getActionCommand().equals("2"));
System.out.println("You have entered a number that is outside of the range of the array index please try again");
}
catch (ArrayIndexOutOfBoundsException arrayError){
System.out.println("Array Index Out of Bounds");
arrayError.printStackTrace();
}
}
}
What you have now defeats the purpose of using an array. Imagine you had to do it for all letters of the Alphabet, would you add 26 conditions? What if you have thousands of options?
Thererfore, instead of
/** DON'T DO THIS */
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
You should parse the input and get element from the array according to the index.
/** DO THIS */
int index = Integer.parseInt(e.getActionCommand());
theOutputLabel.setText(stringArray[index]);
Integer.parseInt() could throw a java.lang.NumberFormatException if the input is not a valid integer, so you have to add a catch for that.
If you want to have the index available for test in the while condition, then declare it without initializing before the do block.
Hey apart from what #isapir has suggested also please check that there are few places in your code that would result into NullPointerExceptions like :
JTextField inputArea; // Not assigned will lead to NPE
JLabel theOutputLabel; // Not assigned will lead to NPE
String userInput = inputArea.getText(); // Because of inputArea unassigned this line will throw NPE for sure so fix that as well.
So I'm assuming what exception you were getting in cmdPrompt would be NPE one so better fix your basic bug first and check your constructor code properly. Lastly, it's always better to share the exception details before post questions on SO.
e.getActionCommand().equals("0") this line will not give what you have entered in frame pop-up. Check this also instead use inputArea.getText() will give you user's entered number digit.

Having trouble giving my JPanel functionality

*This is my first time using GUI, I seem to miss something my eye can't catch. The code looks fine to me however when i submit it to autoLab I get this error, which I cannot figure out where I went wrong.
{"correct":false,"feedback":"(class java.lang.NumberFormatException)
Error while attempting to call static method q2() on input [1]}
The problem question is q5:
Write a public static method named q5 that takes no parameters and returns a JPanel.
The panel will contain 1 JTextField with any number of columns, 1 JButton with any label,
and 1 JLabel. The panel will have functionality such that when a user enters a number into
the text field (we'll call this value x) and presses the button the label will display the
y-value of a parabola in standard form (https://www.desmos.com/calculator/zukjgk9iry)
where a=5.37, b=-6.07, and c=2.0 at the x-value from the text field
Hint: If you store y in the wrapper class Double instead of the primitive double you can
call toString on it to convert it to a string that can be used as the text for the label
Tip: After clicking the button you may have to resize your window to see the result since
the frame will not automatically resize to fit the new text
Do not create any JFrames in your problem set questions. Doing so will crash the
auto-grader since the grading server does not have a screen to display the JFrame.
Instead, only return the required JPanel in the problem set methods and test with a JFrame
in your main method, or other helper methods that are not graded
This is the code I wrote
public static JPanel q5() {
JPanel panel = new JPanel();
JTextField textField = new JTextField(5);
panel.add(textField);
JLabel label = new JLabel("hello!");
panel.add(label);
JButton button = new JButton("Click Me!");
panel.add(button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int x = Integer.parseInt(textField.getText());
double a=5.37*Math.pow(x, 2);
double b=-6.07*x;
double c=2.0;
String answer= ("y = " + a+ b +c);
label.setText(answer);
}
});
return panel;
}
can you explain where I went wrong , thank you.
So, a NumberFormatException can occur when trying to parse a String, when the String does not contain a number. You did not give enough information to be sure, but I am going to presume that it is this line that causes the problem:
int x = Integer.parseInt(textField.getText());
One thing that strikes me as odd, is that you initialize the JTextField with 5 columns:
JTextField textField = new JTextField(5);
Is that what you want? If you wanted to pre-initialize the text field with a value of 5, you would have to do it like this:
JTextField textField = new JTextField("5");

Calculator in Swing Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class calc implements ActionListener
{
JFrame f;
JPanel p;
JTextField jt1,jt2,jt3;
JButton j1,j2;
static double a=0,b=0,result=0;
static int operator=0;
calc()
{
f = new JFrame();
p = new JPanel();
jt1 = new JTextField(20);
jt2 = new JTextField(20);
j1 = new JButton("+");
j2 = new JButton("-");
jt3 = new JTextField();
f.add(p);
p.add(jt1);
p.add(jt2);
p.add(j1);
p.add(j2);
j1.addActionListener(this);
j2.addActionListener(this);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()=="+")
{
a=Double.parseDouble(jt1.getText());
operator = 1;
b=Double.parseDouble(jt2.getText());
switch(operator)
{
case 1: result=(a+b);
}
jt3.setText(result);
}
}
public static void main(String [] args)
{
calc obj = new calc();
}
}
i'm making a calculator using java swing, the output of this code is:
calc.java:48 error: incompatible types: double cannot be converted to String
jt3.setText(result);
i think this is not a big error, well help me to get rid of this, i just want to sum didn't add more functions like multiply or minus or etc, i just want to run as small code first then i'll add more functions to it well help will be appreciated thanks.
Easy way is:
//jt3.setText(result);
jt3.setText("" + result);
This will force the compiler to create a String of the two values.
Use jt3.setText(String.valueOf(result));.
.setText() only accept String type.
You can see it in Class TextField.
Class text can accept only string values.
where the result you provided as an argument is Double
You can use this to convert it as a string
string converted = Double.toString(result);
This error is because JTextField is expecting a String to set the text to it, not a double, so, you need to either:
jt3.setText(String.valueOf(result));
Or
jt3.setText("" + result);
The first one will convert result to a String value, while the second one will concatenate an empty String to result, and return a String as well.
However one last suggestion I want you to take note of is, don't use single letter variables, make them more descriptive, for example:
JFrame f; //This should be JFrame frame;
The same for the JPanel and the rest of your variables, since in larger programs it could be hard to remember that f means a JFrame and not the conversion to Fahrenheit from Celsius or a formula like F = m * a, it may be confusing and really hard to debug / understand later on.
And also as has been said in the comments above, use .equals to compare String in Java, see How do I compare strings in Java? for more on this

TroubleShooting JOptionPane error

I have a question I have a program where I want to test the users ability to remember a random list of colors. Based off if the users input is right or wrong it will ask for the next color.
So I got it all work up to where the user inputs the first color. Before it has the user input on the first color. The program is already assuming the user input is wrong, even tho it hasn't asked for any input.
I know from previously knowledge I could like flush the buffer, can you do that with JOptionPane?
Or is this another issue I'm not seeing?
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Testing
{
//Intialization of the whole program for everything to pass information
public JFrame main;
public JLabel lbInsturctions;
public JLabel welcomeMessage;
public JLabel homeScreen;
public JLabel homeScreenColors;
public JTextField txtInput;
public int num = 1;
public String colorList = "";
public String[] color = {"red","green","blue","brown","yellow", "gold", "orange", "silver"};
public String[] solution = new String[5];
//sets up the window and random colors
public Testing ()
{
Random r = new Random();
for (int i = 0; i<solution.length; i++)
{
solution[i] = color[r.nextInt(7)];
colorList = Arrays.toString(solution);
}
JOptionPane.showMessageDialog(null, "Lets test your memory. Memorize these colors: " + colorList);
main = new JFrame ();
main.setSize (500,300);
main.setTitle ("Ultimate Colors");
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setLayout(new FlowLayout());
intializeGame();
main.setVisible(true);
}
public void intializeGame ()
{
//All Intiazations
lbInsturctions = new JLabel();
homeScreen = new JLabel();
txtInput= new JTextField(null, 15);
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
main.add(lbInsturctions);
main.add(txtInput);
txtInput.addActionListener(new colorTester());
}
public class colorTester implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
//grabs the users input to see if it is corect
String guess= "";
guess = txtInput.getText();
System.out.println(guess);
//Checks to see if the users input is the same as the initalizaton
if (color[num+1].equalsIgnoreCase(guess) || num > 6)
{
System.out.println("You got it!");
++num;
lbInsturctions.setText("Enter color number " + num + ":");
txtInput.setText("");
}
//if the User input is wrong
else
{
System.out.println("It's a good thing your not graded!");
txtInput.setVisible(false);
lbInsturctions.setText("It's a good thing this is not graded!");
}
if (num == 5)
{
lbInsturctions.setText("You memory is perfect good job!");
txtInput.setVisible(false);
}
}
}
}//end of program
This has nothing to do with flushing buffers.
You're getting user input here: guess = txtInput.getText(); which is in the intializeGame method. Meaning you're getting the text from the txtInput JTextField on its creation, before the user has had a chance to enter anything into the field. I think that you're used to programming linear console programs, where you get the user's input immediately, but that's not how event-driven GUI's work. Instead you must get and react to the user's input on event, here perhaps the ActionListener of some button. Perhaps your code needs a "submit" JButton or something similar, and in its ActionListener, extract the input from the JTextField and respond to it. Do this and your code has a better chance of working.
Other issues:
you don't ever appear to have added your txtInput JTextField into the GUI.
same for the homeScreen JLabel
Edit your new code posted at the bottom of your question has the same problem.

JButton doesn't appear until clicked

For this program, the JButton doesn't seem to show up unless you click the area where the JButton should be; the JFrame starts up blank. The moment you click the button, the respective code runs and the button finally shows up.
How do I get the buttons to show up upon starting the program?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/*
The Amazing BlackJack Advisory Tool by JoshK,HieuV, and AlvinC.
Prepare to be amazed :O
*/
public class BlckJackUI {
//main class, will contain the JFrame of the program, as well as all the buttons.
public static void main(String args[])
{
//Creating the JFrame
JFrame GUI = new JFrame("Blackjack Advisor");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(1300, 900);
GUI.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Hieu Vo\\Desktop\\Green Background.png")));
GUI.setVisible(true);
// Because each button needs to run through the Math class.
final Math math = new Math();
// The Ace Button:
ImageIcon Ace = new ImageIcon("/Users/computerscience2/Downloads/Ace.jpg");
JButton ace = new JButton(Ace);
ace.setSize(300, 100);
ace.setLocation(100, 100);
ace.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Automatically default the the Ace to 11, and if Bust, Ace becomes 1.
if (math.array.playerhandtotal <= 21)
{
math.cardvalue = math.cardvalue + 11;
}
else
{
math.cardvalue = math.cardvalue + 1;
}
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
GUI.add(ace);
ImageIcon Two = new ImageIcon("/Users/computerscience2/Downloads/2.jpg");
JButton two = new JButton(Two);
two.setSize(300, 100);
two.setLocation(100, 200);
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
/*
This generally repeats throughout the whole class, and the only
thing different is the changing cardvalue. When a button is pressed,
respective cardvalues are added into the playerhand ArrayList, and
totaled up to form playerhandtotal, which is a major factor in
bringing up the advice.
*/
math.cardvalue = math.cardvalue + 2;
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
GUI.add(two);
Et cetera, Et cetera... Just a bunch of the same stuff, more buttons coded the same exact way as JButton two, but with different value associated to them.
JButton start = new JButton("Start/Reset");
start.setSize(300, 100);
start.setLocation(500,500);
start.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
/*
The start button also acts like a reset button, and the concept is fairly
simple. If we reset all the important values to 0 or "null," then the
program acts as if it was just opened.
*/
Arrays array = new Arrays();
array.playerhand.clear();
array.dealer = 0;
math.array.starttracker++;
math.array.clicktracker = 0;
array.playerhandtotal = 0;
math.cardvalue = 0;
array.result = null;
JOptionPane.showMessageDialog(null,"Please select the card \nthat the dealer is showing :)");
}
});
GUI.add(start);
GUI.setLayout(null);
This is all in the same class, and I understand a layout would be nicer, but perhaps there's a way to fix this issue using what I have now?
The program starts blank because you are calling setVisible before you add components. Call setVisible after you add components (in the end of contructor) and it should work fine.
Also, avoid absolute positioning and call of set|Preferred|Minimum|MaximumSize methods for your components. Learn how to use layout managers.
Write GUI.validate(); after you add all the components to your frame. Any time you add something to a frame you have to validate it like this. Otherwise, you will get the behavior that you have described.
No. The problem is caused by the layout. Before adding anything to a JFrame or a JPanel which you want it to have an absolute position, you have to setLayout(null). Otherwise, you'll have unexpected behaviours all the time. I just figured it out by myself after three hours of experimenting; suddenly, I connected your post with other different subject, and it worked, but this isn't well explained on the Internet yet.

Categories

Resources