NumberFormatException: empty string when clicking the JButton? - java

I made a program that has a JFrame that contains a JTextField, a button, and two JLabels. When a number is typed into the JTextField, either pressing the enter key or clicking on the JButton should display the number in scientific notation on the second JLabel. When I hit the enter key, it works, however, when I click on the JButton, it does not. It gives me a NumberFormatException: empty string.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyMath extends JPanel implements ActionListener
{
private JTextField textField;
private static JLabel textArea;
private static JLabel comment;
private JButton button;
private static JFrame frame;
public MyMath()
{
comment = new JLabel("Enter a number");
textField = new JTextField();
textField.setSize(new Dimension(10 , 10));
textField.addActionListener(this);
button = new JButton("Go");
button.addActionListener(this);
}
public static void addComponentsToPane(Container pane)
{
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new MyMath().textField);
pane.add(new MyMath().button);
pane.add(new MyMath().comment);
pane.add(textArea);
}
public void actionPerformed(ActionEvent evt)
{
String text = textField.getText();
textArea.setText(SciNotation.convertToSciNotation(text));
textArea.setHorizontalAlignment(SwingConstants.CENTER);
comment.setText(text + " in Scientific Notation:");
textField.selectAll();
}
private static void createAndShowGUI()
{
frame = new JFrame("Scientific Notation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
Container bg = frame.getContentPane();
Dimension d = new Dimension(300, 150);
bg.setPreferredSize(d);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GREEN);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Point screenCenter = new Point (screen.width/2 , screen.height/2);
Point center = new Point(screenCenter.x - (150), screenCenter.y - (75));
frame.setLocation(center);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Here is SciNotation.java
import java.awt.Component;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
public class SciNotation
{
public static String convertToSciNotation(String num)
{
num = num.replaceAll("," , "");
if (num.contains("E")) //not working
{
String[] partsE = num.split("E");
String beforeE = partsE[0];
String afterE = partsE[1];
char first = num.charAt(0);
num = first + beforeE;
}
double number = Double.parseDouble(num);
double resultNumber = 0;
int power = 0;
String numString = Double.toString(number);
String[] parts = numString.split("\\.");
String decimals = parts[1];
int decimalInt = Integer.parseInt(decimals);
int numberInt = (int) number;
if(number > -1 && number < 1)
{
String[] low = numString.split("\\.");
String afterLow = low[1];
for(int i = 1; i < 10; i++)
{
String decNums = Integer.toString(i);
afterLow = afterLow.replaceAll(decNums, "");
int zeros = afterLow.length();
power = -1 * (zeros + 1);
resultNumber = number * Math.pow(10, zeros + 1);
decimals = "";
}
}
if(decimalInt == 0)
{
decimals = "";
}
if( number >= 10)
{
power = Integer.toString(numberInt).length() - 1;
resultNumber = numberInt/(Math.pow(10,(power)));
}
if((number >= 1 && number < 10) || (number <= -1 && number > -10))
{
resultNumber = number;
decimals = "";
}
if(number <= -10)
{
power = Integer.toString(numberInt).length() - 2;
resultNumber = numberInt/(Math.pow(10,(power)));
}
return resultNumber + decimals + " x 10^" + power;
}
}

This bug is pretty tricky. You constructed three MyMath instances. So your code was holding a wrong reference to your JTextFiled instance. That's why you couldn't get the right input.
public static void addComponentsToPane(Container pane) {
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new MyMath().textField); //MyMath instance 1
pane.add(new MyMath().button); //MyMath instance 2
pane.add(new MyMath().comment); //MyMath instance 3
pane.add(textArea);
}
Here is the right code:
public static void addComponentsToPane(Container pane) {
MyMath myMath = new MyMath();
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(myMath.textField);
pane.add(myMath.button);
pane.add(myMath.comment);
pane.add(textArea);
}
:)

Related

Can't figure out how to code my calculator

I am trying to code a simple calculator like the one you would see in windows (non-scientific). I can not for the life of me figure out how to properly change the text after pressing an operator but still see the original entry that wont change until the next digit is pressed, have the equals key do the same operation if used multiple times (ie: 5+5 = 10 +5 = 15), and when I input a digit that is the same (5+5) it won't accept the second digit. I know I am very close and am probably missing a certain boolean that could allow my code to work properly, but Im not sure where to look. Thanks for any help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JCalculator extends JFrame implements ActionListener {
/** intialize the jlabel, jbutton, string that makes the buttons and jpanel that will hold the buttons
*
*/
private JTextField display = new JTextField("0", SwingConstants.RIGHT);
private JPanel buttonPanel = new JPanel();
private JPanel displayPanel = new JPanel();
private JButton newButton, divButton, multiButton, equalsButton, clearButton, plusButton, minusButton;
private String[] arrayButtons = {"7","8", "9", "/", "4", "5", "6", "x", "1", "2", "3", "-", "0","C", "=", "+"};
private int operand = 0;
private int firstInput = 0, secondInput = 0, answer = 0;
JCalculator() {
/** creates the jframe */
JFrame jfrm = new JFrame("Calculator");
/** sets the size of the jfrm and then positions it in the center of screen */
jfrm.setSize(480, 300);
jfrm.setLocationRelativeTo(null);
/** sets the program to close on exit */
jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
/** ImageIcon img = new ImageIcon(JCalculator.png);
*
*/
/**sets initial layout to border */
jfrm.setLayout(new BorderLayout());
/** makes a panel named display that holds the Jtext display
* enables it and justifies it right
*/
displayPanel.setLayout(new BorderLayout());
displayPanel.add(display, BorderLayout.CENTER);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEnabled(false);
/** makes a panel for buttons that is a grid layout
*
*/
buttonPanel.setLayout(new GridLayout(4,4));
/** makes a loop to make all of the 16 buttons for the calculator
* the operands all have their own specific buttons
*/
for (int i = 0; i < arrayButtons.length; i++) {
if (arrayButtons[i].equals("/")) {
divButton = new JButton(arrayButtons[i]);
divButton.addActionListener(this);
buttonPanel.add(divButton);
} else if (arrayButtons[i].equals("x")) {
multiButton = new JButton(arrayButtons[i]);
multiButton.addActionListener(this);
buttonPanel.add(multiButton);
} else if (arrayButtons[i].equals("=")) {
equalsButton = new JButton(arrayButtons[i]);
equalsButton.addActionListener(this);
buttonPanel.add(equalsButton);
} else if (arrayButtons[i].equals("C")) {
clearButton = new JButton(arrayButtons[i]);
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
} else if (arrayButtons[i].equals("+")) {
plusButton = new JButton(arrayButtons[i]);
plusButton.addActionListener(this);
buttonPanel.add(plusButton);
} else if (arrayButtons[i].equals("-")) {
minusButton = new JButton(arrayButtons[i]);
minusButton.addActionListener(this);
buttonPanel.add(minusButton);
} else {
newButton = new JButton(arrayButtons[i]);
newButton.addActionListener(this);
buttonPanel.add(newButton);
}
}
/** adds the two panels to the jfrm
* sets jfrm visibility to true
* sets equalsButton to the default button
*/
jfrm.add(displayPanel, BorderLayout.NORTH);
jfrm.add(buttonPanel, BorderLayout.CENTER);
jfrm.getRootPane().setDefaultButton(equalsButton);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String s = ae.getActionCommand();
char stringCheck = s.charAt(0);
if (answer == Integer.parseInt(display.getText())) {
display.setText("0");
}
if (Character.isDigit(stringCheck) && display.getText().length() < 8) {
if (display.getText().equals("0")) {
display.setText(s);
} else {
display.setText(display.getText().concat(s));
}
} if (s.equals("+")){
answer = Integer.parseInt(display.getText());
operand = 1;
} if (s.equals( "-")){
answer = Integer.parseInt(display.getText());
operand = 2;
} if (s.equals("x")){
answer = Integer.parseInt(display.getText());
operand = 3;
} if (s.equals("/")){
answer = Integer.parseInt(display.getText());
operand = 4;
} if (s.equals("C")){
firstInput = 0;
secondInput = 0;
answer = 0;
operand = 0;
display.setText("0");
} if (s.equals("=")){
switch(operand){
case 1:
answer += Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
case 2:
answer -= Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
case 3:
answer *= Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
case 4:
if(Integer.parseInt(display.getText()) > 0 || Integer.parseInt(display.getText()) < 0) {
answer /= Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
} else {
display.setText("Div by 0");
}
}
if(answer > 100000000 || answer < -100000000){
display.setText("Overlow");
}
}
}
public static void main (String [] args){
/**
* run program
*/
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCalculator();
}
});
}
}

Converting a program to use arrays INSTEAD of ArrayLists

I have a class ShoppingCart that utilizes ArrayList methods to carry out the program which is basically a program where you add groceries to your cart and such. However, I want to use arrays to do the program instead of ArrayLists since I want to work on my array knowledge. Here is the ShoppingCart class
import java.util.*;
#SuppressWarnings("serial")
public class ShoppingCart extends ArrayList<Selections> {
// FIELDS
private boolean discount;
// Selections[]......
// CONSTRUCTOR
public ShoppingCart() {
super();
discount = false;
}
// Adding to the Collection
public boolean add(Selections next) {
// check to see if it's already here
for (int i = 0; i < this.size(); i++)
if (get(i).equals(next)) {
set(i, next); // replace it
return true;
}
super.add(next); // add new to the array
return false;
}
// The GUI only know if check is on or off
public void setDiscount(boolean disc) {
discount = disc; // match discount from GUI
}
// total of selections
public double getTotal() {
double sum = 0.0;
for (int i = 0; i < this.size(); i++)
sum += get(i).priceFor();
if (discount) sum *= 0.9;
return sum;
}
}
The Selections class that is being used for the individual groceries.
import java.text.*;
// W.P. Iverson, instructor
// January 2018 for CS211
// Class that combines Item and ItemOrder
public class Selections {
// FIELDS
private String name; // friendly name
private double price; // cost of one
private int bulkQuantity; // when bulk price kicks in
private double bulkPrice; // price for the bulk quantity
private int quantity; // how many we are buying
private boolean hasBulk; // internally used
private NumberFormat curr; // for nice $12.34 currency formatting
// CONSTRUCTORS
public Selections(String name, double price) {
this(name, price, -99999, 99999.); // flag that nothing is selected with 99999
}
public Selections(String thing, double amount, int qty, double bulk) {
name = thing;
price = amount;
if (qty > 0) hasBulk = true;
bulkQuantity = qty;
bulkPrice = bulk;
quantity = 0; // starts with zero selected by user, GUI changes it later
curr = NumberFormat.getCurrencyInstance();
}
// decides how many we're buying
public void setQuantity(int number) {
quantity = number;
}
// calculates the price for this quantity
public double priceFor() {
if (hasBulk && quantity >= bulkQuantity)
return quantity / bulkQuantity * bulkPrice + quantity % bulkQuantity * price;
else
return quantity * price;
}
// basic output for console or GUI text
public String toString() {
if (hasBulk)
return name + ", " + curr.format(price) + " (" + bulkQuantity + " for " + curr.format(bulkPrice) + ")";
else
return name + ", " + curr.format(price);
}
}
I made a JFrame for the program already but just want to get it to use regular arrays instead! Thanks for your help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
#SuppressWarnings("serial")
public class ShoppingFrame extends JFrame {
private ShoppingCart items;
private JTextField total;
public ShoppingFrame(Selections[] array) {
// create frame and order list
setTitle("CS211 Shopping List");
setDefaultCloseOperation(EXIT_ON_CLOSE);
items = new ShoppingCart();
// set up text field with order total
total = new JTextField("$0.00", 12);
total.setEditable(false);
total.setEnabled(false);
total.setDisabledTextColor(Color.BLACK);
JPanel p = new JPanel();
p.setBackground(Color.blue);
JLabel l = new JLabel("order total");
l.setForeground(Color.YELLOW);
p.add(l);
p.add(total);
add(p, BorderLayout.NORTH);
p = new JPanel(new GridLayout(array.length, 1));
for (int i = 0; i < array.length; i++)
addItem(array[i], p);
add(p, BorderLayout.CENTER);
p = new JPanel();
add(makeCheckBoxPanel(), BorderLayout.SOUTH);
// adjust size to just fit
pack();
}
// Sets up the "discount" checkbox for the frame
private JPanel makeCheckBoxPanel() {
JPanel p = new JPanel();
p.setBackground(Color.blue);
final JCheckBox cb = new JCheckBox("qualify for discount");
p.add(cb);
cb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
items.setDiscount(cb.isSelected());
updateTotal();
}
});
return p;
}
// adds a product to the panel, including a textfield for user input of
// the quantity
private void addItem(final Selections product, JPanel p) {
JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT));
sub.setBackground(new Color(0, 180, 0));
final JTextField quantity = new JTextField(3);
quantity.setHorizontalAlignment(SwingConstants.CENTER);
quantity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateItem(product, quantity);
quantity.transferFocus();
}
});
quantity.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
updateItem(product, quantity);
}
});
sub.add(quantity);
JLabel l = new JLabel("" + product);
l.setForeground(Color.white);
sub.add(l);
p.add(sub);
}
// When the user types a new value into one of the quantity fields,
// parse the input and update the ShoppingCart. Display an error
// message if text is not a number or is negative.
private void updateItem(Selections product, JTextField quantity) {
int number;
String text = quantity.getText().trim();
try {
number = Integer.parseInt(text);
} catch (NumberFormatException error) {
number = 0;
}
if (number <= 0 && text.length() > 0) {
Toolkit.getDefaultToolkit().beep();
quantity.setText("");
number = 0;
}
product.setQuantity(number);
items.add(product);
updateTotal();
}
// reset the text field for order total
private void updateTotal() {
double amount = items.getTotal();
total.setText(NumberFormat.getCurrencyInstance().format(amount));
}
public static void main(String[] args) {
Selections[] array = new Selections[10];
array[0] = new Selections("silly putty", 3.95, 10, 19.99);
array[1] = new Selections("silly string", 3.50, 10, 14.95);
array[2] = new Selections("bottle o bubbles", 0.99);
array[3] = new Selections("Nintendo Wii system", 389.99);
array[4] = new Selections("Mario Computer Science Party 2 (Wii)", 49.99);
array[5] = new Selections("Don Knuth Code Jam Challenge (Wii)", 49.99);
array[6] = new Selections("Computer Science pen", 3.40);
array[7] = new Selections("Rubik's cube", 9.10);
array[8] = new Selections("Computer Science Barbie", 19.99);
array[9] = new Selections("'Java Rules!' button", 0.99, 10, 5.0);
ShoppingFrame f = new ShoppingFrame(array);
f.setVisible(true);
}
}
You can use an array member variable in ShoppingCart class like this:
private Selections[] selectionsArray;
instead of extending ArrayList<Selections>. (Then you will have to handle resizing the array yourself.)

Making a calculator about letter grades

I am taking Maths and I want to make a calculator which tells me the each note I need to take in the final exam to get each letter grade. In the syllabus it tells us that our note is calculated by this:
MT1 - First midterm %26.6
MT2- Second midterm %26.6
F- Final % 26.6
Q - Quizzes % 10
HW- Homeworks % 10
These are the grade intervals:
A 80-100
A- 75-80
B+ 70-75
B 65-70
B- 60-65
C+ 55-60
C 50-55
C- 45-50
D+ 40-45
D+ 30-40
F 0-30
You enter MT1, MT2, Q, HW in the JTextFields and when you click the button it will update the jlabel's near the letter grades. When I run the code for the first time, it works but when I want to change it program doesn't update the numbers. Could you help?
Final_Calculator:
import javax.swing.*;
import java.awt.*;
public class Final_Calculator extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Final Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Results());
frame.pack();
frame.setVisible(true);
}
}
Grades:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Grades extends JPanel
{
private JLabel l1, l2, l3, l4;
private JTextField t1, t2, t3, t4;
private double sum,result, MT1, MT2, Q, HW;
private JButton button;
public Grades()
{
setPreferredSize(new Dimension(200,100));
l1 = new JLabel("MT1");
l2 = new JLabel("MT2");
l3 = new JLabel("Q");
l4 = new JLabel("HW");
t1 = new JTextField("100");
t2 = new JTextField("100");
t3 = new JTextField("100");
t4 = new JTextField("100");
button = new JButton("Click!");
TextListener listener = new TextListener();
button.addActionListener(listener);
add(l1);
add(l2);
add(l3);
add(l4);
add(t1);
add(t2);
add(t3);
add(t4);
add(button);
}
public double getMT1()
{
return Double.parseDouble(t1.getText());
}
public double getMT2()
{
return Double.parseDouble(t2.getText());
}
public double getQ()
{
return Double.parseDouble(t3.getText());
}
public double getHW()
{
return Double.parseDouble(t4.getText());
}
public void sum()
{
MT1 = getMT1();
MT2 = getMT2();
Q = getQ();
HW = getHW();
sum = (MT1 * 26.6) + (MT2 * 26.6) + (Q * 10) + (HW * 10);
}
public double getA()
{
sum();
result = (8000 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getAminus()
{
sum();
result = (7500 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getBplus()
{
sum();
result = (7000 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getB()
{
sum();
result = (6500 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getBminus()
{
sum();
result = (6000 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getCplus()
{
sum();
result = (5500 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getC()
{
sum();
result = (5000 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getCminus()
{
sum();
result = (4500 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getDplus()
{
sum();
result = (4000 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
public double getD()
{
sum();
result = (3000 - sum) / 26.6;
if (result <= 0)
{
return 0;
}
return result;
}
private class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == button)
{
MT1 = Double.parseDouble(t1.getText());
MT2 = Double.parseDouble(t2.getText());
Q = Double.parseDouble(t3.getText());
HW = Double.parseDouble(t4.getText());
sum();
getA();
getAminus();
getBplus();
getB();
getBminus();
getCplus();
getC();
getCminus();
getDplus();
getD();
}
}
}
}
Results:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Results extends JPanel
{
private JLabel f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11;
private JPanel panel1, panel2;
private Grades grades;
public Results()
{
grades = new Grades();
setPreferredSize(new Dimension(800,800));
setLayout(new BorderLayout());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(11,2));
panel1.setPreferredSize(new Dimension(200,200));
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(400,400));
f1 = new JLabel("Final");
g1 = new JLabel("Grade");
f2 = new JLabel(Double.toString(grades.getA()));
g2 = new JLabel(" A");
f3 = new JLabel(Double.toString(grades.getAminus()));
g3 = new JLabel(" A-");
f4 = new JLabel(Double.toString(grades.getBplus()));
g4 = new JLabel(" B+");
f5 = new JLabel(Double.toString(grades.getB()));
g5 = new JLabel(" B");
f6 = new JLabel(Double.toString(grades.getBminus()));
g6 = new JLabel(" B-");
f7 = new JLabel(Double.toString(grades.getCplus()));
g7 = new JLabel(" C+");
f8 = new JLabel(Double.toString(grades.getC()));
g8 = new JLabel(" C");
f9 = new JLabel(Double.toString(grades.getCminus()));
g9 = new JLabel(" C-");
f10 = new JLabel(Double.toString(grades.getDplus()));
g10 = new JLabel(" D+");
f11 = new JLabel(Double.toString(grades.getD()));
g11 = new JLabel(" D");
panel1.add(f1);
panel1.add(g1);
panel1.add(f2);
panel1.add(g2);
panel1.add(f3);
panel1.add(g3);
panel1.add(f4);
panel1.add(g4);
panel1.add(f5);
panel1.add(g5);
panel1.add(f6);
panel1.add(g6);
panel1.add(f7);
panel1.add(g7);
panel1.add(f8);
panel1.add(g8);
panel1.add(f9);
panel1.add(g9);
panel1.add(f10);
panel1.add(g10);
panel1.add(f11);
panel1.add(g11);
panel2.add(grades);
add(panel2, BorderLayout.NORTH);
add(panel1, BorderLayout.CENTER);
}
}
From the looks of it/only working once, it looks like you are not updating the label after clicking the button.Label text have to updated via label.setText(""); just calling the method wont do anything.

*new title: JButton array scope (it was:change color of button with button name)

How can is alter the color of the correct button?
It is for a small application, this app has 5 buttons from a array.(the name's are a,b,c,d,e)
The appearence of the buttons have to alter (change color) when i type in a number in a Jtextfield.
I added a name to each button:
knop = new JButton(Titel[i]);
knop.setName(tel[i]);
Here i get the text:
public void actionPerformed(ActionEvent e) {
String invoer = antwoord.getText();
try
{
int welke = Integer.parseInt(invoer);
if (welke-1 >0 && welke-1<5)
{
vraag.setText("Goeie keus!");
if (welke == 1){
knop.setBackground(Color.BLUE);
}
knop.setBackground(Color.red);
}
But now it only changes the last button to red which is created bij the array.
So the question can I select a button by its name?
So if (input = 1) alter button 1 to green. in stead of only button 5.
I have tried de solution of gile, but i can't get it to work:
I get every time a: "AWT-EventQueue-0" java.lang.NullPointerException"
package kiesknop;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//public class Paneel extends JApplet
public class Paneel extends JFrame
{
private JPanel paneel;
private JButton knop;
public JTextField antwoord;
private JLabel vraag;
public JButton[] knops;
public Paneel() {
int [][] numButtons = new int [5][4];
numButtons[0][0] = 50;
numButtons[0][1] = 10;
numButtons[0][2] = 10;
numButtons[0][3] = 10;
numButtons[1][0] = 100;
numButtons[1][1] = 10;
numButtons[1][2] = 30;
numButtons[1][3] = 30;
numButtons[2][0] = 200;
numButtons[2][1] = 10;
numButtons[2][2] = 50;
numButtons[2][3] = 50;
numButtons[3][0] = 300;
numButtons[3][1] = 10;
numButtons[3][2] = 100;
numButtons[3][3] = 100;
numButtons[4][0] = 500;
numButtons[4][1] = 10;
numButtons[4][2] = 200;
numButtons[4][3] = 200;
String [] Titel = new String [5];
Titel [0] = "*";
Titel [1] = "**";
Titel [2] = "***";
Titel [3] = "****";
Titel [4] = "*****";
String [] tel = new String [5];
tel [0] = "a";
tel [1] = "b";
tel [2] = "c";
tel [3] = "d";
tel [4] = "e";
paneel = new JPanel();
JButton[] knops = new JButton[5];
for (int i = 0; i < 5; i++)
{
knops[i] = new JButton(Titel[i]);
knops[i].setName (tel[i]);
knops[i].setBounds(numButtons[i][0],numButtons[i][1], numButtons[i][2], numButtons[i][3]);
knops[i].addActionListener(new KnopHandler());
}
for (int i = 0; i < 5; i++)
{
paneel.add(knops[i]);
}
vraag = new JLabel("Welke knop grootte vind je het mooist?");
vraag.setBounds(100, 400, 250, 20);
antwoord = new JTextField(20);
antwoord.setBounds(500, 400, 100, 20);
antwoord.setEditable(true);
antwoord.addActionListener(new AntwoordHandler());
paneel.add (vraag);
paneel.add (antwoord);
setContentPane (paneel);
}
public class KnopHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton)e.getSource();
String Text = o.getText();
String name = o.getName();
String Label =o.getLabel();
System.out.println("knop gedrukt");
System.out.println(Text);
System.out.println(name);
System.out.println(Label);
}
}
class AntwoordHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String invoer = antwoord.getText();
try
{
int welke = Integer.parseInt(invoer);
if (welke >0 && welke<5)
{
vraag.setText("Goeie keus!");
if(welke == 1)// knops[welke].setBackground(Color.BLUE);
System.out.println(knops[1]);
if(welke == 2) knops[welke].setBackground(Color.BLUE);
if(welke == 3) knops[welke].setBackground(Color.BLUE);
if(welke == 4) knops[welke].setBackground(Color.BLUE);
if(welke == 5) knops[welke].setBackground(Color.BLUE);
}
else vraag.setText("Geen geldige invoer!");
}
catch( NumberFormatException nfe)
{
if( invoer.equals("")) vraag.setText("Niets ingevuld!");
else
vraag.setText("Alleen nummers invoeren!");
}
}
}
public static void main (String arg[])
{
JFrame frame = new Paneel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
frame.setSize(900, 500);
}
}
What am i doing wrong ?
You can put buttons in an array
JButton[] knops = new JButton[5];
...
knops[i] = new JButton(Titel[i]);
...
And then set the background after user entered a number:
if (welke == 1){
knops[welke].setBackground(Color.GREEN);
}
Your title doesn't match with the given example: you are asking to get a button reference with string name but you are trying to parse the name to an integer.
However, if i understood your requirement correctly: I can think of two option:
Traverse each button of the button's array you have and compare with their name with your target name: you can get the name of the component(JButton) invoking button.getName().
Instead of using array which require traverse each time to get the target button with matching name, Create a HashMap<key, value>: HashMap<String, JButton>, map the button to their name and use it to get the component on Action Event.
HashMap<String, JButton>buttomMap = new HashMap<>();
buttonMap.put("kicker", kickerButton); // kickButton is a button
//// Then in actionPerformed() function
JButton button = buttonMap.get("kicker");
button.setBackground(Color.BLUE);

Retrieving a double from a JTextArea while solving for X

Ok, I'm kinda new to java. I'm making a program that solves for one step equations. I'm having some difficulties running it though. Here is the code for my main file, Main.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
Solve solve = new Solve();
JButton add = new JButton("Add");
JButton sub = new JButton("Subtract");
JButton mult = new JButton("Multiply");
JButton div = new JButton("Divide");
JButton solv = new JButton("Solve!");
JTextArea one = new JTextArea();
JLabel two = new JLabel(" = ");
JLabel three = new JLabel("X");
JLabel four = new JLabel();
JTextArea five = new JTextArea();
JLabel solved = new JLabel();
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
public double funct;
public Main() {
super("Solving a one step equation!");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout layout = new GridLayout();
setLayout(layout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(layout1);
row1.add(add);
row1.add(sub);
row1.add(mult);
row1.add(div);
row1.add(solv);
add(row1);
add.addActionListener(this);
sub.addActionListener(this);
mult.addActionListener(this);
div.addActionListener(this);
solv.addActionListener(this);
GridLayout layout2 = new GridLayout(1, 1, 1, 1);
row2.setLayout(layout2);
row2.add(one, BorderLayout.CENTER);
row2.add(two, BorderLayout.CENTER);
row2.add(three, BorderLayout.CENTER);
row2.add(four, BorderLayout.CENTER);
row2.add(five);
add(row2, BorderLayout.CENTER);
GridLayout layout3 = new GridLayout(5, 5, 5, 5);
row3.setLayout(layout3);
row3.add(solved);
add(row3);
}
public static void main(String[] args) {
Main frame = new Main();
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if(source == add)
{
four.setText(" + ");
funct = 1;
}
else if(source == sub)
{
four.setText(" - ");
funct = 2;
}
else if(source == mult)
{
four.setText(" * ");
funct = 3;
}
else if(source == div)
{
four.setText(" / ");
funct = 4;
}
if(source == solv)
{
if(funct == 1)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Add(Ones, Twos));
}
else if(funct == 2)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Sub(Ones, Twos));
}
else if(funct == 3)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Mult(Ones, Twos));
}
else if(funct == 4)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Div(Ones, Twos));
}
}
}
}
Here is the code for my other file, Solve.java
public class Solve {
public double Add(double One, double Two)
{
return One - Two;
}
public double Sub(double One, double Two)
{
return One + Two;
}
public double Mult(double One, double Two)
{
return One / Two;
}
public double Div(double One, double Two)
{
return One * Two;
}
}
Some help would be appreciated. Anyone see what I'm doing wrong?
You get a NumberFormatException once 'Solve' button is clicked. It seems like a copy/paste issue - you are not retrieving the correct numbers. You are trying to convert 'X' string to double. It is best if you give meaningful names to your variables. To fix the exception, try this, replace :
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
with:
double Ones = Double.parseDouble(one.getText());
double Twos = Double.parseDouble(five.getText());
Get familiar with Java Code Conventions, Naming Conventions section in particular.
In addition to #Max's helpful answer, here are a few other suggestions:
Setting the frame's layout to new GridLayout() defaults to a single row and column with no padding. As an alternative, consider new GridLayout(0, 1, 5, 5), which produces any number of rows in one column with 5x5 padding. Then you can focus on the layout of each row:
row1.setLayout(new FlowLayout(FlowLayout.CENTER));
row2.setLayout(new FlowLayout(FlowLayout.CENTER));
row3.setLayout(new GridLayout(1, 1, 5, 5));
Move your setVisible() call to the end of the frame's constructor:
pack();
setLocationRelativeTo(null);
setVisible(true);
Consider getRootPane().setDefaultButton(solv) to make the Solve button the default.
Consider making addition the default:
private JLabel four = new JLabel("+");
private int funct = 1; // add by default
Consider using JTextField for number entry:
private JTextField one = new JTextField(10);
private JTextField five = new JTextField(10);

Categories