2011-12-13 31 views
6

Tengo un JLabel y un botón, el JLabel muestra la cantidad de veces que se presionó el botón, sin embargo, no sé cómo actualizar el JLabel que muestra el número de pulsaciones de botones.Cómo cambiar un JLabel dinámicamente

import java.awt.event.*; 
import java.awt.*; 
import javax.swing.*; 

public class SimpleGui { 
    private JFrame f = new JFrame("Basic GUI"); // create Frame 
    int pressed = 0; // tracks number of button presses. 
    JLabel label1 = new JLabel("You have pressed button " + pressed + "times."); 
    private JButton start = new JButton("Click To Start!"); 

    public SimpleGui() { 
     // Setup Main Frame 
     f.getContentPane().setLayout(new GridLayout(0, 1)); 
     start.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      calculate(); 
     } 
     }); 
     // Add components 
     f.add(label1); 
     f.add(start); 
     // Allows the Swing App to be closed 
     f.addWindowListener(new ListenCloseWdw()); 
    } 

    public class ListenMenuQuit implements ActionListener { 
     public void actionPerformed(ActionEvent e) { 
     System.exit(0); 
     } 
    } 

    public class ListenCloseWdw extends WindowAdapter { 
     public void windowClosing(WindowEvent e) { 
     System.exit(0); 
     } 
    } 

    public void launchFrame() { 
     // Display Frame 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.pack(); // Adjusts panel to components for display 
     f.setVisible(true); 
    } 

    public static void main(String args[]) { 
     PrimeTime gui = new PrimeTime(); 
     gui.launchFrame(); 
    } 

    public void calculate() { 
     pressed++; 
     label1 = new JLabel("You have pressed button " + pressed + "times."); 
     // update the GUI with new jLabel 
     f.repaint(); 
    } 
} 
+0

editado a hacer que el código legible. –

+0

Gracias, no me di cuenta de los miembros anteriormente ... :) – DejanLekic

Respuesta

9

El problema es que está creando un JLabel nuevo y diferente que no se muestra en el panel.

hacer

public void calculate(){ 
    pressed++; 
    this.label1.setText("You have pressed button " + pressed + "times."); 
} 
+0

+1 Usted fue más rápido que yo y tuvo una mejor solución. – Jonas

+0

+1, ¡ustedes dos fueron más rápidos que yo! –

2

Sólo se llama calculate() cuando se hace clic en el botón start. Entonces puede mover ese método al ActionListener para el botón. Y llamando al setText en el JLabel, no tiene que llamar al repaint. Normalmente no tiene que llamar al repaint en Swing. P.ej. cambiar el código para algo como esto en su lugar:

final JLabel label1 = new JLabel("You have pressed button " + pressed + "times."); 
private JButton start = new JButton(new AbstractAction("Click To Start!") { 
    public void actionPerformed(ActionEvent e) { 
     pressed++; 
     label1.setText("You have pressed button " + pressed + "times."); 
    } 
}); 
+0

Sí, lo que dijo. :) 1+ –

2

Cambio label1 = new JLabel("You have pressed button " + pressed + "times."); a label1.setText("You have pressed button " + pressed + "times.");

1
/* try and understand this code, here i use an icon to set the labe's image and the getIcon method of Label's to change the icon of previous label using setIcon method. */     
Icon picLabelicon new ImageIcon(img); /* setting the icon initially*/ 
        JLabel picLabel = new JLabel(); 
        picLabel.setIcon(picLabelicon); 
        /* now you have set the icon initially now lets change it dynamically*/ 

     JLabel modify = new JLabel(new ImageIcon(newimg)); /* new label you wanted to use*/ 
        picLabelicon=modify.getIcon(); 

        picLabel.setIcon(picLabelicon); 
      revalidate(); 
      repaint();