Java - actualizar mi label o otros objetos desde otra clase

 
Vista:
Imágen de perfil de jorge

actualizar mi label o otros objetos desde otra clase

Publicado por jorge (5 intervenciones) el 25/01/2017 15:00:33
hola amigos , necesito urgente la ayuda para resolver mi problema . tengo un frame con label y desde otra clase que tiene un temporizador timer , cada vez que produce un tiempo necesito que me modifique el label.
, para eso cree un metodo setHora()
pero no cambia el label ...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Timer;
import java.util.TimerTask;
 
 
public class Reloj {
 
  monitores mon = new monitores();
 
    Timer timer = new Timer(); // El timer que se encarga de administrar los tiempo de repeticion
    public int segundos; // manejar el valor del contador
    public boolean frozen; // manejar el estado del contador TIMER AUTOMATICO -- True Detenido | False    Corriendo
    int cont = 0;
    // clase interna que representa una tarea, se puede crear varias tareas y asignarle al timer luego
 
    class MiTarea extends TimerTask {
 
        public void run() {
            segundos++;
            System.out.println(segundos);
 
                                     // aqui se puede escribir el codigo de la tarea que necesitamos ejecutar
 
     mon.setHora();
 
        }
    }
 
    public void Start() {
        frozen = false;
        // le asignamos una tarea al timer
        timer.schedule(new MiTarea(), 0, 1000);
 
    }// end Start
 
    public void Stop() {
        System.out.println("Stop");
        frozen = true;
    }// end Stop
 
    public void Reset() {
        System.out.println("Reset");
        frozen = true;
        segundos = 0;
    }// end Reset
 
}// end Reloj


la clase principal del frame



/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package monitoreo;


/**
*
* @author daniel
*/
public class monitores extends javax.swing.JFrame {

public void setHora() {
Hora.setText("ok");
Hora.setVisible(false);
}




/**
* Creates new form monitores
*/
public monitores() {
initComponents();

}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jRadioButton1 = new javax.swing.JRadioButton();
Hora = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();

jRadioButton1.setText("jRadioButton1");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

Hora.setText("jLabel1");

jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(69, 69, 69)
.addComponent(Hora)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(231, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(92, 92, 92))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(Hora)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 113, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(112, 112, 112))
);

Hora.getAccessibleContext().setAccessibleParent(Hora);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {

/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new monitores().setVisible(true);
Reloj ns = new Reloj();


}

});

}

// Variables declaration - do not modify
private javax.swing.JLabel Hora;
private javax.swing.JButton jButton1;
private javax.swing.JRadioButton jRadioButton1;
// End of variables declaration
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 349
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

actualizar mi label o otros objetos desde otra clase

Publicado por Andrés (340 intervenciones) el 26/01/2017 15:32:03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
 
/**
 *
 * @author andreas
 */
public class Monitores extends JFrame {
 
    public void setHora(int segundos) {
 
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Hora.setText("" + segundos);
 
            }
 
        });
 
    }
 
    /**
     * Creates new form monitores
     */
    public Monitores() {
        initComponents();
 
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() {
 
        jRadioButton1 = new javax.swing.JRadioButton();
        Hora = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
 
        jRadioButton1.setText("jRadioButton1");
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        Hora.setText("jLabel1");
 
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(Hora)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(231, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(92, 92, 92))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(Hora)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 113, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(112, 112, 112))
        );
 
        Hora.getAccessibleContext().setAccessibleParent(Hora);
 
        pack();
    }// </editor-fold> 
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
 
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
 
        /* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Monitores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
//</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Monitores mon = new Monitores();
                mon.setVisible(true);
                Reloj ns = new Reloj();
                ns.setMon(mon);
                ns.Start();
            }
 
        });
 
    }
 
// Variables declaration - do not modify 
    private javax.swing.JLabel Hora;
    private javax.swing.JButton jButton1;
    private javax.swing.JRadioButton jRadioButton1;
// End of variables declaration 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Reloj {
 
 private Monitores mon;
 
    public Monitores getMon() {
        return mon;
    }
 
    public void setMon(Monitores mon) {
        this.mon = mon;
    }
 
    Timer timer = new Timer(); // El timer que se encarga de administrar los tiempo de repeticion
    public int segundos; // manejar el valor del contador
    public boolean frozen; // manejar el estado del contador TIMER AUTOMATICO -- True Detenido | False    Corriendo
    int cont = 0;
    // clase interna que representa una tarea, se puede crear varias tareas y asignarle al timer luego
 
    class MiTarea extends TimerTask {
 
        public void run() {
            segundos++;
            System.out.println(segundos);
 
                                     // aqui se puede escribir el codigo de la tarea que necesitamos ejecutar
 
     mon.setHora(segundos);
 
        }
    }
 
    public void Start() {
        frozen = false;
        // le asignamos una tarea al timer
        timer.schedule(new MiTarea(), 0, 1000);
 
    }// end Start
 
    public void Stop() {
        System.out.println("Stop");
        frozen = true;
    }// end Stop
 
    public void Reset() {
        System.out.println("Reset");
        frozen = true;
        segundos = 0;
    }// end Reset
 
}// end Reloj
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar