Ok so I am trying to create a simple calculator with two JTextField for two numbers, three CheckBoxes so the user can choose sum,difference or multiply, a (Kryej Veprim (so that when this button is clicked if the user for example checked "shuma" at the other JTextField result(rezultati) will display the sum of these two numbers). Something is totally wrong I know because I cant connect checkboxes with "kryejveprim" button.Any help? P.s (When I run this code i write numbers but nothing happens when i check the checkboxes or when i click the button)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener,ItemListener{
JTextField numri1,numri2;
JCheckBox shuma,diferenca,shumezimi;
JButton veprimi,ok;
JTextField rezultati;
double n1,n2;
String n1tekst,n2tekst;
public Calculator(){
setLayout(new FlowLayout());
numri1=new JTextField(10);
add(numri1);
numri2=new JTextField(10);
add(numri2);
shuma=new JCheckBox("Shuma");
add(shuma);
diferenca=new JCheckBox("Diferenca");
add(diferenca);
shumezimi=new JCheckBox("Shumezimi");
add(shumezimi);
veprimi=new JButton("Kryej Veprimin");
add(veprimi);
rezultati=new JTextField(10);
add(rezultati);
ok=new JButton("OK");
add(ok);
numri1.addActionListener(this);
numri2.addActionListener(this);
rezultati.addActionListener(this);
}
public void actionPerfomed(ActionEvent e) {
if (e.getSource()==numri1)
{
n1tekst=e.getActionCommand();
n1=Double.parseDouble(n1tekst);
}
else if(e.getSource()==numri2)
{
n2tekst=e.getActionCommand();
n2=Double.parseDouble(n2tekst);
}
}
public void itemStateChanged( ItemEvent e )
{
if (e.getSource() == shuma)
{
String rez = shuma.isSelected() ? ""+(n1+n2) : "";
rezultati.setText(rez);
}
else if (e.getSource() == diferenca)
{
String rez = diferenca.isSelected() ? ""+(n1-n2) : "";
rezultati.setText(rez);
}
else if (e.getSource() == shumezimi)
{
String rez = shumezimi.isSelected() ? ""+(n1*n2) : "";
rezultati.setText(rez);
}
}
public static void main (String args[])
{
Calculator ob = new Calculator();
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ob.setSize(900,900);
ob.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
You have confused where to put ActionListeners - they belong on components like buttons where you expect an action, and ItemListeners which belong to the check boxes. Once you sort this out your code will work. This code will update the result if you press any of the operations, or the result button.
Working code:
Java class to change the background color based on a checkbox, after pressing button: