2015-04-22 89 views
-1

我試圖實現這個代碼,基本上它是當我按下它的唯一按鈕時,它會在按鈕上方的標籤中增加一個單位。換句話說,它顯示用戶按下按鈕的次數。 但我的問題是,當我按下按鈕時似乎無法刷新標籤。保存「點擊次數」的變量會遞增,但在標籤中保留的初始聲明值爲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)); 

      } 

     } 
    } 

} 

回答

0

更改方法criarPainelCliques()後,看起來像這樣:

private JPanel criarPainelCliques() { 

     JLabel lbl = new JLabel("Número de Cliques: "); 
     JPanel p = new JPanel(); 
     lbl.setFont(lbl.getFont().deriveFont(20.0f)); 
     p.add(lbl, BorderLayout.CENTER); 
     p.add(l1); 

     return p; 
    } 

目前喲ü只是讀取您的clickvalue曾經在這裏:

 JLabel lbl = new JLabel("Número de Cliques: " + l1.getText()); 

L1是永遠不會再次讀取等你點擊計數器停留在0

+0

非常感謝!這解決了問題 –

0

你永遠不添加JLabel命名l1到任何東西,所以它的文字不會被顯示。我建議你通過將它添加到GUI來解決這個問題。

0

嘗試添加

l1.revalidate(); 

l1.repaint(); 

或兩者的順序的setText()

+0

氣墊船的答案是你的第一個賭注 – misterti