I tried to implement this code that basically what it does is when I press the only button it has, it increments one unit in the label above the button. In other words, it shows how many times has the user pressed the button. But My problem is that I can't seem to refresh the label when I press the button. The variable that holds the number of "clicks" is incremented but in the label it remains with the initial declaration value, 0. Can someone help?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ContadorCliques extends JFrame {
private TrataEvento trataEvento;
private JButton buttonClick;
private int clickCont = 0;
private JLabel l1;
public static void main(String[] args) {
ContadorCliques contador1 = new ContadorCliques("Hello!");
}
public ContadorCliques(String titulo) {
super(titulo);
Container c = getContentPane();
BorderLayout bl = new BorderLayout();
c.setLayout(bl);
l1=new JLabel(String.valueOf(clickCont));
JPanel pBotoes = criarPainelBotao();
c.add(pBotoes, BorderLayout.SOUTH);
//add(pBotoes, BorderLayout.SOUTH);
JPanel pCliques = criarPainelCliques();
c.add(pCliques, BorderLayout.CENTER);
//add(pCliques, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setMinimumSize(new Dimension(getWidth(), getHeight()));
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel criarPainelCliques() {
JLabel lbl = new JLabel("Número de Cliques: " + l1.getText());
JPanel p = new JPanel();
lbl.setFont(lbl.getFont().deriveFont(20.0f));
p.add(lbl, BorderLayout.CENTER);
return p;
}
private JPanel criarPainelBotao() {
trataEvento = new TrataEvento();
buttonClick = criarBotao();
JPanel p = new JPanel();
p.add(buttonClick);
return p;
}
private JButton criarBotao() {
JButton btn = new JButton("Click Here!");
btn.addActionListener(trataEvento);
return btn;
}
private class TrataEvento implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String obj = (String) e.getActionCommand();
if (obj.compareTo("Click Here!")==0) {
clickCont++;
System.out.println("Funciona");
System.out.println(clickCont);
l1.setText(String.valueOf(clickCont));
}
}
}
}