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

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

Related

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

Remove Java Panels without crashing your program

So basically I am writing a GUI program that uses a JComboBox to display various finance formulas. I have everything in place in terms of it displaying the formulas but here is my problem. Everytime I go to choose a new formula in my comboBox it the other ones stay displayed. I've tried to write an if statement to disable, remove and invalidate these (not all at once) but none have worked...I need to get it so when I click a option the other panels disappear if there are any at all. Thanks!
Here is the full program the problem I am having is that when I choose a new formula the one that I chose before it is still active...I want to disable or remove it. Thanks.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class newFinanceFullClass extends JFrame {
private JMenu fileMenu;
private JMenuItem exitItem;
private JPanel presentValuePanel;
private JPanel financeFinderPanel;// A panel container
private JLabel principalMessage;
private JLabel yearlyRateMessage;
private JLabel termYearMessage;
private JPanel simpleInterestPanel;
private JPanel doublingTimePanel;
private JPanel compoundInterestPanel;
private JLabel NONEMessage;
private JLabel imageLabel;
private JLabel label;// A message to display
private JMenuBar menuBar;
private JTextField principalText; // To hold user input
private JButton calcButton; // Performs calculation
private final int WINDOW_WIDTH = 600; // Window width
private final int WINDOW_HEIGHT = 600; // Window height
private JTextField yearlyRateText;
private JTextField termYearText;
DecimalFormat dc =new DecimalFormat("####0.00"); //formater
private JComboBox financeBox;
double principal = 400.0;
double yearlyRate = .04;
double termYears = 4.0;
private String[] financeFormulas = { "NONE", "Present value", "Simple interest",
"Doubling time", "Compound interest", "Decaf"};
financeFormulaClass financeFormula = new financeFormulaClass(principal, yearlyRate, termYears);
/**
* Constructor
*/
public newFinanceFullClass()
{
// Call the JFrame constructor.
super("Finance Class");
// Set the size of the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Specify what happens when the close
// button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel and add it to the frame.
financeFinderPanel();
setLayout(new BorderLayout());
//buildPanel();
menuBar = new JMenuBar();
buildFileMenu();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Add the panel to the frame's content pane.
add(financeFinderPanel);
//add(panel);
// Display the window.
setVisible(true);
}
private void financeFinderPanel()
{
// Create a panel to hold the combo box.
financeFinderPanel = new JPanel();
//create label
label = new JLabel("Pick your formula");
ImageIcon funnyImage = new ImageIcon("funny.gif");
imageLabel = new JLabel();
imageLabel.setLocation(50, 55);
label.setForeground(Color.BLUE);
// Create the combo box
financeBox = new JComboBox(financeFormulas);
imageLabel.setIcon(funnyImage);
// Register an action listener.
financeBox.addActionListener(new financeBoxListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
// Add the combo box to the panel.
financeFinderPanel.add(financeBox);
financeFinderPanel.add(label);
financeFinderPanel.add(imageLabel);
}
/** private void menuList(){
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
menuList.add(exitItem);
} **/
private void buildMenuBar()
{
// Create the menu bar.
menuBar = new JMenuBar();
// Create the file and text menus.
buildFileMenu();
// buildTextMenu();
// Add the file and text menus to the menu bar.
menuBar.add(fileMenu);
//menuBar.add(textMenu);
// Set the window's menu bar.
setJMenuBar(menuBar);
}
private void buildFileMenu()
{
// Create an Exit menu item.
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());
// Create a JMenu object for the File menu.
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
// Add the Exit menu item to the File menu.
fileMenu.add(exitItem);
}
private void presentValuePanel()
{
// Create the label, text field, and button components.
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Present Value");
// Add an action listener to the button.
//calcButton.addActionListener(new CalcButtonListener());
calcButton.addActionListener(new financeFormListener());
// Create a panel to hold the components.
presentValuePanel = new JPanel();
// Add the label, text field, and button to the panel.
presentValuePanel.add(principalMessage);
presentValuePanel.add(principalText);
presentValuePanel.add(yearlyRateMessage);
presentValuePanel.add(yearlyRateText);
presentValuePanel.add(termYearMessage);
presentValuePanel.add(termYearText);
presentValuePanel.add(calcButton);
}
private void simpleInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Simple Interest");
simpleInterestPanel = new JPanel();
calcButton.addActionListener(new financeFormListener());
simpleInterestPanel.add(principalMessage);
simpleInterestPanel.add(principalText);
simpleInterestPanel.add(yearlyRateMessage);
simpleInterestPanel.add(yearlyRateText);
simpleInterestPanel.add(termYearMessage);
simpleInterestPanel.add(termYearText);
simpleInterestPanel.add(calcButton);
}
private void doublingTimePanel(){
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
calcButton = new JButton("Calc Doubling Time");
calcButton.addActionListener(new financeFormListener());
doublingTimePanel = new JPanel();
doublingTimePanel.add(yearlyRateMessage);
doublingTimePanel.add(yearlyRateText);
doublingTimePanel.add(calcButton);
}
private void compoundInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Compound Interest");
compoundInterestPanel = new JPanel();
calcButton.addActionListener(new financeFormListener());
compoundInterestPanel.add(principalMessage);
compoundInterestPanel.add(principalText);
compoundInterestPanel.add(yearlyRateMessage);
compoundInterestPanel.add(yearlyRateText);
compoundInterestPanel.add(termYearMessage);
compoundInterestPanel.add(termYearText);
compoundInterestPanel.add(calcButton);
}
//Listener to choose which formula
private class financeBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object actionCommand = e.getSource();
String selection = (String) financeBox.getSelectedItem();
if(selection.equals("Present value")){
//financeFinderPanel.removeAll();
presentValuePanel();
add(presentValuePanel, BorderLayout.SOUTH);
pack();
}
else if(selection.equals("Simple interest")){
simpleInterestPanel();
add(simpleInterestPanel, BorderLayout.NORTH);
pack();
}
else if(selection.equals("Doubling time")){
doublingTimePanel();
add(doublingTimePanel, BorderLayout.SOUTH);
pack();
}
else if(selection.equals("Compound interest")){
compoundInterestPanel();
add(compoundInterestPanel, BorderLayout.NORTH);
pack();
}
else if(selection.equals("NONE")){
setSize(200, 150);
financeFinderPanel();
add(financeFinderPanel, BorderLayout.NORTH);
NONEMessage = new JLabel("PICK A SELECTION");
}
}
}
private class financeFormListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Calc Simple Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double interestRate = (principal * yearlyRate * termYears);
String msg = "Simple interest is: $" + dc.format(interestRate);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Present Value"))
{
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double pValue = financeFormula.presentValue(principal, yearlyRate, termYears);
//double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
String msg = "Present value is: $" + dc.format(pValue);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Doubling Time")){
try{
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double dValue = financeFormula.doublingTime(yearlyRate);
String msg = "Doubling Time is: " + dc.format(dValue);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Compound Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double compoundInterest = financeFormula.compoundInterest(principal, yearlyRate, termYears);
String msg = "Compound Interest is: $" + dc.format(compoundInterest);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
}
}
private class ExitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
new newFinanceFullClass();
}
}
Again, use a CardLayout to help you swap your JPanels. You would create a JPanel and set its layout to CardLayout, and then you'd add the JPanels (the "cards") that you wish to swap into this holder JPanel using String constants, Strings that you will pass into the CardLayout's show(...) method to allow it to swap your components.
For instance, say you had an enum to hold your financial formula Strings, something like:
public enum FinanceFormula {
NONE("NONE"),
PRESENT_VALUE("Present value"),
SIMPLE_INTEREST("Simple interest"),
DOUBLING_TIME("Doubling time"),
COMPOUND_INTEREST("Compound interest"),
DECAF("Decaf");
private String name;
private FinanceFormula(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
};
}
Then the CardLayout and its JPanel could be set up like so:
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);
and the JComboBox like below. This works because I have overridden the enum's to String method so that a proper name will display:
private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());
You would then add all the formula JPanels into the cardHolderPanel using String constants obtained from the enum:
// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());
Then when you want to swap JPanels, simply pass in the appropriate String into the CardLayout's show method, and you're good:
private void combBoxActionPerformed(ActionEvent e) {
FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
cardLayout.show(cardHolderPanel, selectedFormula.getName());
}
The following program doesn't create any fancy formula JPanels, but it doesn't have to, since it is an MCVE built to demonstrate swapping JPanels only:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewFinance2 extends JPanel {
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);
private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());
public NewFinance2() {
// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());
comboBox.addActionListener(e -> combBoxActionPerformed(e));
JPanel northPanel = new JPanel();
northPanel.add(comboBox);
setLayout(new BorderLayout());
add(cardHolderPanel, BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
}
private void combBoxActionPerformed(ActionEvent e) {
FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
cardLayout.show(cardHolderPanel, selectedFormula.getName());
}
// A bunch of dummy methods that don't create much
// Your real methods would create more complex JPanels
private JPanel createDecafPanel() {
return createPanel(FinanceFormula.DECAF);
}
private JPanel createCompoundInterestPanel() {
return createPanel(FinanceFormula.COMPOUND_INTEREST);
}
private JPanel createDoublingTimePanel() {
return createPanel(FinanceFormula.DOUBLING_TIME);
}
private JPanel createSimpleInterestPanel() {
return createPanel(FinanceFormula.SIMPLE_INTEREST);
}
private JPanel createPresentValuePanel() {
return createPanel(FinanceFormula.PRESENT_VALUE);
}
private JPanel createNonePanel() {
return createPanel(FinanceFormula.NONE);
}
// temporary method just for demonstration purposes
private JPanel createPanel(FinanceFormula financeFormula) {
JLabel label = new JLabel(financeFormula.getName());
label.setFont(label.getFont().deriveFont(Font.BOLD, 24f));
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setPreferredSize(new Dimension(400, 300));
float split = 0.7f;
float h = (float) (split + Math.random() * (1f - split));
float s = (float) (split + Math.random() * (1f - split));
float b = (float) (split + Math.random() * (1f - split));
Color color = Color.getHSBColor(h, s, b);
panel.setBackground(color);
return panel;
}
private static void createAndShowGui() {
NewFinance2 mainPanel = new NewFinance2();
JFrame frame = new JFrame("Finance");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Using JTextField for user input

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.

Can anyone tell me why my change QTY button isnt changing the QTY?

Can anyone tell me why my change QTY button isnt changing the QTY?
The buttonlistener2 is supposed to change the number of items in arrayCount[x]
to the number in the count JTextfield, but its not, could use a new set of eyes.
thanks all
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ProduceInventory extends JFrame
{
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<Integer> arrayCount = new ArrayList<Integer>();
// declares panels and items
private final int WINDOW_WIDTH = 450;
private final int WINDOW_HEIGHT = 350;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JTextField name;
private JTextField count;
private JTextArea output;
private JButton add;
private JButton changeQTY;
private JButton delete;
private JButton clear;
private JButton report;
private JButton save;
private JButton load;
public ProduceInventory()
{
//creates Jframe
setTitle("Produce Inventory");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1(); //build panels
panel2();
panel3();
add(panel1, BorderLayout.NORTH); //add panels
add(panel2, BorderLayout.SOUTH);
add(panel3, BorderLayout.CENTER);
setVisible(true);
}
private void panel1() //builds panel 1
{
messageLabel1 = new JLabel("Name");
messageLabel2 = new JLabel("Count");
name = new JTextField(20);
count = new JTextField(5);
panel1 = new JPanel();
panel1.add(messageLabel1);
panel1.add(name);
panel1.add(messageLabel2);
panel1.add(count);
}
private void panel2() //builds panel 2
{
add = new JButton("Add");
changeQTY = new JButton("CHANGE QTY");
delete = new JButton("Delete");
clear = new JButton("Clear");
report = new JButton("Report");
save = new JButton("Save File");
load = new JButton("Load File");
add.addActionListener(new ButtonListener());
changeQTY.addActionListener(new ButtonListener2());
panel2 = new JPanel();
panel2.setLayout(new GridLayout(2,4));
panel2.add(add);
panel2.add(changeQTY);
panel2.add(delete);
panel2.add(clear);
panel2.add(report);
panel2.add(save);
panel2.add(load);
}
private void panel3() //builds panel 3
{
output = new JTextArea(10,30);
panel3 = new JPanel();
panel3.add(output);
}
private class ButtonListener implements ActionListener //add listener
{
String nameIn;
String countIn;
int number;
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
nameIn = name.getText();
arrayName.add(name.getText());
countIn = count.getText();
number = Integer.parseInt(countIn);
arrayCount.add(number);
output.setText(name.getText() + " " + count.getText() + " Item Added");
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
private class ButtonListener2 implements ActionListener //add listener
{
public void actionPerformed(ActionEvent e)
{
String nameIn;
String countIn;
int number;
String actionCommand = e.getActionCommand();
if (actionCommand.equals("CHANGE QTY"))
{
nameIn = name.getText();
countIn = count.getText();
number = Integer.parseInt(countIn);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
if(arrayName.get(x) == nameIn)
{
arrayCount.set(x, number);
}
}
output.setText("Qty is updated to: " + number);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ProduceInventory(); //runs program
}
}
In the action listener, on the line
if(arrayName.get(x) == nameIn)
you are checking if the two variables refer to the same object. Instead of that you have to check if the objects they refer to are equal:
if(nameIn.equals(arrayName.get(x)))

Basic GUI program layout positioning

I have been trying to figure out how to properly layout my program for quite a while now. I basically have 5 JLabels, 5 JTextFields, and 6 JButtons, I need to align it as shown below.
I tried using a GridLayout but it make the JTextFields really thick, I tried different combinations of flow layout with mixed results. I was wondering if someone can guide me as to how I can get the below result?
Thanks in advance.
Here is my code as it stands now:
public class MyClass extends JFrame{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JTextField item4;
private JTextField item5;
JLabel label1 = new JLabel("Enter number of items in this order:");
JLabel label2 = new JLabel("Enter CD ID for Item #1:");
JLabel label3 = new JLabel("Enter quantity for Item #1:");
JLabel label4 = new JLabel("Item #1 info:");
JLabel label5 = new JLabel("Order subtotal for 0 item(s):");
private JButton button1 = new JButton("Process Item #1");
private JButton button2 = new JButton("Confirm Item #1");
private JButton button3 = new JButton("View Order");
private JButton button4 = new JButton("Finish Order");
private JButton button5 = new JButton("New Order");
private JButton button6 = new JButton("Exit");
private Scanner x;
private int exitFlag = 0;
public String[] idArray = new String[10];
public String[] recordArray = new String[10];
public String[] priceArray = new String[10];
public int myNum=1;
private JPanel jp = new JPanel();
public void openFile(){
try{
x = new Scanner(new File("inventory.txt"));
x.useDelimiter(",|" + System.getProperty("line.separator"));
}
catch(Exception e){
System.out.println("Could not find file");
}
}
public void readFile(){
int i=0;
while(x.hasNext()){
idArray[i] = x.next();
recordArray[i] = x.next();
priceArray[i] = x.next();
i++;
}
}
public int itemNum(int num){
return num+1;
}
public MyClass(){
super("Matt's World of Music");
jp.setLayout(new FlowLayout(FlowLayout.RIGHT));
Box vertBox = Box.createVerticalBox();
Box vertBox2 = Box.createVerticalBox();
Box itemBox2 = Box.createHorizontalBox();
item1 = new JTextField(40);
item2 = new JTextField(40);
item3 = new JTextField(40);
item4 = new JTextField(40);
item5 = new JTextField(40);
vertBox.add(label1);
vertBox.add(label2);
vertBox.add(label3);
vertBox.add(label4);
vertBox.add(label5);
jp.add(vertBox);
vertBox2.add(item1);
vertBox2.add(item2);
vertBox2.add(item3);
vertBox2.add(item4);
vertBox2.add(item5);
jp.add(vertBox2);
itemBox2.add(button1);
itemBox2.add(button2);
itemBox2.add(button3);
itemBox2.add(button4);
itemBox2.add(button5);
itemBox2.add(button6);
jp.add(itemBox2);
add(jp);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
item4.setEditable(false);
item5.setEditable(false);
//Process Item
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MyClass obj = new MyClass();
button1.setEnabled(false);
button2.setEnabled(true);
item1.setEditable(false);
obj.openFile();
obj.readFile();
//start loop
for(int i=0; i < idArray.length; i++){
if(item2.getText().equals(obj.idArray[i])==true){
//set item4 text field to price id and other details
item4.setText(obj.idArray[i] + " " + obj.recordArray[i] + " $" + obj.priceArray[i].replaceAll("\\s",""));
}
}
}
});
//Confirm Item
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(myNum==Integer.parseInt(item1.getText())){
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
button2.setEnabled(false);
button1.setText("Process Item");
button2.setText("Confirm Item");
button1.setEnabled(false);
button3.setEnabled(true);
button4.setEnabled(true);
item2.setText("");
item3.setText("");
label2.setText("");
label3.setText("");
item2.setEditable(false);
item3.setEditable(false);
}else{
//Execute when button is pressed
button1.setEnabled(true);
button2.setEnabled(false);
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
item2.setText("");
item3.setText("");
label2.setText("Enter CD ID for Item #" + (myNum+1) + ":");
label3.setText("Enter quantity for Item #" + (myNum+1) + ":");
label4.setText("Item #" + (myNum+1) + " info:");
myNum++;
button1.setText("Process item #" + (myNum));
button2.setText("Confirm item #" + (myNum));
}
}
});
//View Order
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("View Order");
}
});
//Finish Order
button4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("Finish Order");
}
});
//New Order
button5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("New Order");
}
});
//Quit
button6.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//exit program
}
});
}
}
Using a simple GridBagLayout makes it look like in your screenshot:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyClass extends JFrame {
private final JTextField item1;
private final JTextField item2;
private final JTextField item3;
private final JTextField item4;
private final JTextField item5;
JLabel label1 = new JLabel("Enter number of items in this order:");
JLabel label2 = new JLabel("Enter CD ID for Item #1:");
JLabel label3 = new JLabel("Enter quantity for Item #1:");
JLabel label4 = new JLabel("Item #1 info:");
JLabel label5 = new JLabel("Order subtotal for 0 item(s):");
private final JButton button1 = new JButton("Process Item #1");
private final JButton button2 = new JButton("Confirm Item #1");
private final JButton button3 = new JButton("View Order");
private final JButton button4 = new JButton("Finish Order");
private final JButton button5 = new JButton("New Order");
private final JButton button6 = new JButton("Exit");
private Scanner x;
private final int exitFlag = 0;
public String[] idArray = new String[10];
public String[] recordArray = new String[10];
public String[] priceArray = new String[10];
public int myNum = 1;
private final JPanel jp;
public void openFile() {
try {
x = new Scanner(new File("inventory.txt"));
x.useDelimiter(",|" + System.getProperty("line.separator"));
} catch (Exception e) {
System.out.println("Could not find file");
}
}
public void readFile() {
int i = 0;
while (x.hasNext()) {
idArray[i] = x.next();
recordArray[i] = x.next();
priceArray[i] = x.next();
i++;
}
}
public int itemNum(int num) {
return num + 1;
}
public MyClass() {
super("Matt's World of Music");
jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.BASELINE_TRAILING;
// Box vertBox = Box.createVerticalBox();
// Box vertBox2 = Box.createVerticalBox();
// Box itemBox2 = Box.createHorizontalBox();
item1 = new JTextField(40);
item2 = new JTextField(40);
item3 = new JTextField(40);
item4 = new JTextField(40);
item5 = new JTextField(40);
c.gridx = 0;
c.gridy = 0;
jp.add(label1, c);
c.gridy++;
jp.add(label2, c);
c.gridy++;
jp.add(label3, c);
c.gridy++;
jp.add(label4, c);
c.gridy++;
jp.add(label5, c);
c.gridx = 1;
c.gridy = 0;
jp.add(item1, c);
c.gridy++;
jp.add(item2, c);
c.gridy++;
jp.add(item3, c);
c.gridy++;
jp.add(item4, c);
c.gridy++;
jp.add(item5, c);
JPanel btnPan = new JPanel(new FlowLayout(FlowLayout.CENTER));
btnPan.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
btnPan.add(button1);
btnPan.add(button2);
btnPan.add(button3);
btnPan.add(button4);
btnPan.add(button5);
btnPan.add(button6);
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
jp.add(btnPan, c);
add(jp);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
item4.setEditable(false);
item5.setEditable(false);
// Process Item
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MyClass obj = new MyClass();
button1.setEnabled(false);
button2.setEnabled(true);
item1.setEditable(false);
obj.openFile();
obj.readFile();
// start loop
for (int i = 0; i < idArray.length; i++) {
if (item2.getText().equals(obj.idArray[i]) == true) {
// set item4 text field to price id and other details
item4.setText(obj.idArray[i] + " " + obj.recordArray[i] + " $"
+ obj.priceArray[i].replaceAll("\\s", ""));
}
}
}
});
// Confirm Item
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (myNum == Integer.parseInt(item1.getText())) {
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
button2.setEnabled(false);
button1.setText("Process Item");
button2.setText("Confirm Item");
button1.setEnabled(false);
button3.setEnabled(true);
button4.setEnabled(true);
item2.setText("");
item3.setText("");
label2.setText("");
label3.setText("");
item2.setEditable(false);
item3.setEditable(false);
} else {
// Execute when button is pressed
button1.setEnabled(true);
button2.setEnabled(false);
JOptionPane.showMessageDialog(null, "Item #" + (myNum) + " accepted");
item2.setText("");
item3.setText("");
label2.setText("Enter CD ID for Item #" + (myNum + 1) + ":");
label3.setText("Enter quantity for Item #" + (myNum + 1) + ":");
label4.setText("Item #" + (myNum + 1) + " info:");
myNum++;
button1.setText("Process item #" + (myNum));
button2.setText("Confirm item #" + (myNum));
}
}
});
// View Order
button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("View Order");
}
});
// Finish Order
button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("Finish Order");
}
});
// New Order
button5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("New Order");
}
});
// Quit
button6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// exit program
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyClass c = new MyClass();
c.pack();
c.setVisible(true);
}
});
}
}
I would design it this way:
the main panel would have a BorderLayout as the layout manager and contain 2 panels: one in the center and one on the south
the panel in the center could have a GridBagLayout and contain the labels and the text fields
the panel on the south could have a FlowLayout or a BoxLayout and include the buttons
As a single layout, you might look to use GroupLayout or GridBagLayout. I would probably do it as a nested layout.
A BorderLayout for the outer container.
A GridLayout of text fields in LINE_END.
A GridLayout of labels in the CENTER.
A FlowLayout for the buttons at PAGE_END.
If any of the text fields are larger than needed, wrap them in a new JPanel(new FlowLayout()) - the panel will fill the parent location, while allowing the text filed to shrink to whatever size it needs to be.
Of course that is ignoring the plethora of excellent 3rd party layouts such as FormLayout, MigLayout..

Categories

Resources