我試圖實現這個代碼,基本上它是當我按下它的唯一按鈕時,它會在按鈕上方的標籤中增加一個單位。換句話說,它顯示用戶按下按鈕的次數。 但我的問題是,當我按下按鈕時似乎無法刷新標籤。保存「點擊次數」的變量會遞增,但在標籤中保留的初始聲明值爲0.有人可以幫忙嗎?actionPerformed之外的標籤不刷新
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));
}
}
}
}
非常感謝!這解決了問題 –