I try to do a simple and simple calculator on my own, but I run into a problem trying to change the value of the JTextField by pressing a button.
Here the code:
Frame Class:
public class Frame extends JFrame{
public Frame(){
setTitle("Calculadora...");
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new PanelResultado(), BorderLayout.NORTH);
add(new PanelOperaciones(), BorderLayout.CENTER);
setVisible(true);
}
}
PanelResult Class (This is where the values are entered)
class PanelResultado extends JPanel{
private JTextField res = null;
public PanelResultado() {
setLayout(new BorderLayout());
res = new JTextField("0");
res.setFont(new Font("Arial", Font.PLAIN, 16));
res.setBackground(Color.BLACK);
res.setForeground(Color.WHITE);
res.setPreferredSize(new Dimension(400, 50));
res.setHorizontalAlignment(JTextField.RIGHT);
res.setEditable(false);
add(res);
}
public JTextField getRes() {
return res;
}
public void setRes(String texto) {
this.res.setText(texto);
}
}
Panel Panel Operations (These are the buttons for the numbers and operators)
class PanelOperaciones extends JPanel{
private JButton b1 = null;
private PanelResultado panel;
public PanelOperaciones() {
setLayout(new GridLayout(4, 4));
agregarBoton("9");
agregarBoton("8");
agregarBoton("7");
agregarBoton("( / )");
agregarBoton("6");
agregarBoton("5");
agregarBoton("4");
agregarBoton("( * )");
agregarBoton("3");
agregarBoton("2");
agregarBoton("1");
agregarBoton("( + )");
agregarBoton("0");
agregarBoton("Limpiar");
agregarBoton("( = )");
agregarBoton("( - )");
panel = new PanelResultado();
}
private void agregarBoton(String n) {
b1 = new JButton(n);
b1.setBackground(Color.BLACK);
b1.setForeground(Color.WHITE);
b1.setFont(new Font("Arial",Font.PLAIN, 15));
add(b1);
ejecutar();
}
void ejecutar() {
ActionListener oyente = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panel.setRes("cambiando..");
}
};
b1.addActionListener(oyente);
}
}
Well, here is the class where I try to do what I said at the beginning and it does not work for me. I also tried a separate class where it was implemented to ActionListener, and it does not work for me either ... to clarify that everything is in the same file and that it matters what is necessary for it to work, the IDE does not mark me any error, so it does not It's nothing like that.
I hope you can help me, thank you.