1 year ago
#354059
Sai Gruheeth
How to display a JTextField in the frame based on selection from JComboBox?
Intro : This program is supposed to act as a scientific calculator with a basic GUI. An input is mandatory for which a JTextField is used to take input. Then there is a drop-down list with operators. Based on selection of binary (+ , - , * , / , % , ^) operator in JComboBox, the second JTextField has to appear in the frame. For operators like (1/n , n^2 , n^3 , sin , cos , tan , n! , sqrt) the second JTextField is not required.
I have tried to just to hide the field when not required using the .setVisible(False) method and perform the opposite when required.
How do I get this going ?
public void show()
{
JFrame frame = new JFrame("Scientific Calculator");
frame.setPreferredSize(new Dimension(600, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTextField input1 = new JTextField(10);
JComboBox<String> operator = new JComboBox<String>(
new String[] { "+", "-", "*", "/", "%", "^", "1/n", "n^2", "n^3", "sin", "cos", "tan", "n!", "sqrt"}
);
JTextField input2 = new JTextField(10);
JButton calcbutton = new JButton("Calculate");
result = new JLabel(" ");
result.setBorder(BorderFactory.createLineBorder(Color.BLACK));
calcbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1 = input1.getText();
op = operator.getItemAt(operator.getSelectedIndex());
if(op == "+" | op == "-" | op == "*" | op == "/" | op == "%" | op == "^")
{
String s2 = input2.getText();
controller.handleUserInput(s1, op, s2);
}
else if(op == "1/n" | op == "n^2" | op == "n^3" | op == "sin" | op == "cos" | op == "tan" | op == "n!" | op == "sqrt")
{
controller.handleUserInput(s1, op);
}
}
});
panel.add(input1);
panel.add(operator);
panel.add(input2).setVisible(false);
operator.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
op = e.getSource().toString();
if(op == "+" | op == "-" | op == "*" | op == "/" | op == "%" | op == "^")
{
panel.add(input2).setVisible(true);
}
}
});
// panel.add(input2);
panel.add(calcbutton);
panel.add(result);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
java
swing
jpanel
jtextfield
jcombobox
0 Answers
Your Answer