I'm using a GUI for a prefix expression program. The programme itself works fine, but the GUI is a bit problematic. When I run it, the result label doesn't show up. I've tried everything, but I don't know why it's not working. Any help would be greatly appreciated. Thanks!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import javax.swing.*;
public class PrefixExpression extends JFrame
{
private JPanel panel;
private JTextField expression;
private JLabel title;
private JLabel instruction;
private JLabel results;
private final int WIDTH = 310;
private final int HEIGHT = 175;
private JButton calculateBtn;
public PrefixExpression()
{
setTitle("Prefix Expression Calculator");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
title = new JLabel("Calculating Prefix Expressions");
instruction = new JLabel("Please enter your expression");
expression = new JTextField(10);
calculateBtn = new JButton("Calculate");
calculateBtn.addActionListener(new ButtonListener());
panel = new JPanel();
panel.add(title);
panel.add(instruction);
panel.add(expression);
panel.add(calculateBtn);
}
public static void main(String[] args)
{
PrefixExpression main = new PrefixExpression();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Stack <Integer> numberStack = new Stack <Integer>();
Stack <Character> operatorStack = new Stack <Character>();
String input = expression.getText();
StringTokenizer strToken = new StringTokenizer(input, " ", false);
while (strToken.hasMoreTokens())
{
String i = strToken.nextToken();
int number;
char operator;
try
{
number = Integer.parseInt(i);
numberStack.push(number);
}
catch (NumberFormatException nfe)
{
operator = i.charAt(0);
operatorStack.push(operator);
}
}
int answer = calculateMethod(numberStack, operatorStack);
results = new JLabel("Here is your answer: " + answer);
panel.add(results); //This is where the results label is added to panel
}
public int calculateMethod(Stack <Integer> numberStack, Stack <Character> operatorStack)
{
int result = 0;
while(! numberStack.empty())
{
char operator = (char) operatorStack.pop();
if (operator == '+')
result = addition(numberStack);
else if (operator == '*')
result = multiplication(numberStack);
}
return result;
}
public int addition(Stack <Integer> numberStack)
{
int numb1 = (int) numberStack.pop();
int numb2 = (int) numberStack.pop();
int answer = numb1 + numb2;
return answer;
}
public int multiplication(Stack <Integer> numberStack)
{
int numb1 = (int) numberStack.pop();
int numb2 = (int) numberStack.pop();
int answer = numb1 * numb2;
return answer;
}
}
}