Java - cambiar texto jlabel

 
Vista:
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 18/03/2017 16:30:10
Hola, estoy creando una aplicación Java y tengo que modificar el texto de un jlabel en un momento determinado.
He intentado con el método settext("string"), pero no me funciona.
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
Imágen de perfil de Yacoobs
Val: 231
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Yacoobs (10 intervenciones) el 18/03/2017 20:43:38
Tan sencillo como esto amigo mio... no hay ningún misterio espero a ver ayudado Saludos...


JLabel.setText("Estoy modificando el texto");
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
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 19/03/2017 08:07:01
Lo siento, pero eso ya lo probe y no servía.
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

cambiar texto jlabel

Publicado por Renzo (232 intervenciones) el 20/03/2017 16:36:30
Ese es el método correcto para cambiar el texto de un jlabel. Si no te funciona ha de ser por el contexto en el que lo estas ejecutando.

Renzo
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
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 20/03/2017 16:40:50
Hola Renzo, gracias por responder.
Es una aplicación para el juego del número secreto.
Se trata de que cuando el cronómetro llegue a 0, un jlabel que hay debajo del timer, cambie el texto que tiene.
He intentado tambien con el repaint, pero nada.
A continuación te pongo el código del applet para que lo veas:
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
137
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.lang.Math;
import java.text.DecimalFormat;
import javax.swing.Timer;
public class NumeroSecreto extends JApplet implements ActionListener{
	private JTextField num=null;
	private JButton probar=null;
	private JButton juegoNuevo=null;
	private JLabel timeLabel;
	private static JLabel msg=null;
	private byte centiseconds=0;
    private byte seconds=60;
    private short minutes=0;
    private DecimalFormat timeFormatter;
    private Timer timer;
	public void init(){
    	this.getContentPane().setLayout(new BorderLayout());
    	num=new JTextField();
    	num.setHorizontalAlignment(SwingConstants.RIGHT);
    	JPanel aux=new JPanel();
    	aux.setLayout(new GridLayout(2,2));
    	aux.add(new JLabel(this.getParameter("TEXTO1")));
    	aux.add(num);
    	this.getContentPane().add(aux,BorderLayout.NORTH);
    	aux=new JPanel();
    	probar=new JButton(this.getParameter("TEXTO2"));
    	probar.setName("Probar");
    	probar.addActionListener(this);
    	aux.add(probar);
    	juegoNuevo=new JButton(this.getParameter("TEXTO3"));
    	aux.add(juegoNuevo);
    	juegoNuevo.setName("Juego nuevo");
    	juegoNuevo.addActionListener(this);
    	timeLabel=new JLabel();
        timeLabel.setFont(new Font("Consolas",Font.PLAIN,13));
        timeLabel.setHorizontalAlignment(JLabel.CENTER);
        aux.add(timeLabel);
        msg=new JLabel();
        msg.setHorizontalAlignment(JLabel.CENTER);
        aux.add(msg);
    	this.getContentPane().add(aux,BorderLayout.SOUTH);
    	num.setText("0");
    	num.setEditable(false);
    	probar.setEnabled(false);
    	juegoNuevo.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                num.setEditable(true);
                probar.setEnabled(true);
                juegoNuevo.setEnabled(false);
                int numale=(int)Math.random()*100+1;
            	timer.stop();
                centiseconds=00;
                seconds=60;
                minutes=00;
                timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
                timer.start();
                String text=num.getText();
                int numa=Integer.valueOf(text);
                boolean acierto=false;
                do{
                	if(numa==numale){
                		timer.stop();
                		msg.setVisible(false);
                		msg.setText("Acertaste!");
                		msg.setVisible(true);
                		//msg.repaint();
                		num.setEditable(false);
                		probar.setEnabled(false);
                		juegoNuevo.setEnabled(true);
                		acierto=true;
                	}else{
                		if(numa<numale){
                			msg.setVisible(false);
                			msg.setText("Demasiado pequeño!");
                			msg.setVisible(true);
                			//msg.repaint();
                			acierto=false;
                		}else{
                			msg.setVisible(false);
                			msg.setText("Demasiado grande!");
                			msg.setVisible(true);
                			//msg.repaint();
                			acierto=false;
                		}
                	}
                	if(seconds==00){
                		msg.setVisible(false);
                		msg.setText("Lo siento, has perdido!");
                		msg.setVisible(true);
                		//msg.repaint();
                		timer.stop();
                		num.setEditable(false);
                		probar.setEnabled(false);
                		juegoNuevo.setEnabled(true);
                	}
                }while(acierto=false);
            }
        });
    	timeFormatter=new DecimalFormat("00");
        timer=new Timer(10,new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                if(centiseconds>0){
                    centiseconds--;
                }else{
                    if(seconds==0&&minutes==0){
                        timer.stop();
                    }else if(seconds>0){
                        seconds--;
                        centiseconds=99;
                    }else if(minutes>0){
                        minutes--;
                        seconds=59;
                        centiseconds=99;
                    }
                }
                timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
            }
        });
        timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
        add(aux);
        setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent e){
	}
}
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

cambiar texto jlabel

Publicado por Renzo (232 intervenciones) el 20/03/2017 16:44:38
veo varios setext. cuál es el del problema ?
y que hace tu programa ?
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
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 20/03/2017 16:49:06
No funciona ninguno y son los de dentro del do.
El trabajo es el siguiente:
introduzco un número y al darle a probar me tiene que decir en el jlabel si es mayor, menor o el correcto.
Y si se termina el tiempo sin acertarlo, tiene que decir que perdiste y se acabo el tiempo.
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

cambiar texto jlabel

Publicado por Renzo (232 intervenciones) el 20/03/2017 16:56:05
ocurre que nunca esta seteando el valor de numa.
se supone que debe escribir un numero en la caja de texto y luego presionar entre ? o presionar un boton ? debe haber un evento que sirva para actualizar el valor de numa.
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
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 20/03/2017 17:00:01
Te paso el enunciado del ejercicio:
El applet consiste en una implementación del juego del Número Secreto.
Al cargar el applet, tanto el campo de texto donde se podrán teclear posibles números, como el botón “Probar” estarán deshabilitados.
Al pulsar el botón de “Juego nuevo” se habilitarán los controles que estaban deshabilitados, se deshabilitará este último botón, se calculará un número aleatorio entre 0 y 100 (mirar los métodos random y rint de la clase java.lang.Math en el API), se arrancará un temporizador de 60 segundos y se irán mostrando los segundos que queden en la etiqueta de la derecha del botón “Juego nuevo”.
En el campo de texto se teclearán números y al pulsar el botón “Probar” se mostrará en la etiqueta de su derecha si ha sido mayor o menor que el número secreto.
En caso de que se acierte el número secreto, se mostrará “¡¡Acertaste!! en la etiqueta de donde mostrábamos los segundos que iban quedando, pararemos el temporizador, deshabilitamos el botón “Probar” y el campo de texto, y habilitaremos de nuevo el botón “Juego nuevo”.
Si se acabara el tiempo sin haber acertado el número secreto, pasaría lo mismo con la diferencia de que el texto a mostrar sería “Lo siento, has perdido”.
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

cambiar texto jlabel

Publicado por Renzo (232 intervenciones) el 20/03/2017 17:08:50
Modifique un poco el programa. Pruebalo (funciona para random de 0 al 10)
Espero te sirva

Me cuentas



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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.lang.Math;
import java.text.DecimalFormat;
import javax.swing.Timer;
public class NumeroSecreto extends JApplet implements ActionListener{
	private JTextField num=null;
	private JButton probar=null;
	private JButton juegoNuevo=null;
	private JLabel timeLabel;
	private static JLabel msg=null;
	private byte centiseconds=0;
    private byte seconds=60;
    private short minutes=0;
    private DecimalFormat timeFormatter;
    private Timer timer;
 
    int numale=((int)(Math.random()*10));
 
	public void init(){
    	this.getContentPane().setLayout(new BorderLayout());
    	num=new JTextField();
    	num.setHorizontalAlignment(SwingConstants.RIGHT);
    	JPanel aux=new JPanel();
    	aux.setLayout(new GridLayout(2,2));
    	aux.add(new JLabel(this.getParameter("TEXTO1")));
    	aux.add(num);
    	this.getContentPane().add(aux,BorderLayout.NORTH);
    	aux=new JPanel();
    	probar=new JButton(this.getParameter("TEXTO2"));
    	probar.setName("Probar");
    	probar.addActionListener(this);
    	aux.add(probar);
    	juegoNuevo=new JButton(this.getParameter("TEXTO3"));
    	aux.add(juegoNuevo);
    	juegoNuevo.setName("Juego nuevo");
    	juegoNuevo.addActionListener(this);
    	timeLabel=new JLabel();
        timeLabel.setFont(new Font("Consolas",Font.PLAIN,13));
        timeLabel.setHorizontalAlignment(JLabel.CENTER);
        aux.add(timeLabel);
        msg=new JLabel();
        msg.setHorizontalAlignment(JLabel.CENTER);
        aux.add(msg);
    	this.getContentPane().add(aux,BorderLayout.SOUTH);
    	num.setText("0");
    	num.setEditable(false);
    	probar.setEnabled(false);
 
 
 
 
    	juegoNuevo.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	timer.stop();
                centiseconds=00;
                seconds=60;
                minutes=00;
                timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
                timer.start();
                num.setEditable(true);
                probar.setEnabled(true);
                juegoNuevo.setEnabled(false);
            }
    	});
 
    	probar.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
 
 
 
                String text=num.getText();
                int numa=Integer.valueOf(text);
                boolean acierto=false;
                do{
 
                	if(numa==numale){
                		timer.stop();
                		msg.setVisible(false);
                		msg.setText("Acertaste!");
                		msg.setVisible(true);
                		//msg.repaint();
                		num.setEditable(false);
                		probar.setEnabled(false);
                		juegoNuevo.setEnabled(true);
                		acierto=true;
                	}else{
                		if(numa<numale){
                			msg.setVisible(false);
                			msg.setText("Demasiado pequeño!");
                			msg.setVisible(true);
                			//msg.repaint();
                			acierto=false;
                		}else{
                			msg.setVisible(false);
                			msg.setText("Demasiado grande!");
                			msg.setVisible(true);
                			//msg.repaint();
                			acierto=false;
                		}
                	}
                	if(seconds==00){
                		msg.setVisible(false);
                		msg.setText("Lo siento, has perdido!");
                		msg.setVisible(true);
                		//msg.repaint();
                		timer.stop();
                		num.setEditable(false);
                		probar.setEnabled(false);
                		juegoNuevo.setEnabled(true);
                	}
                }while(acierto=false);
            }
        });
    	timeFormatter=new DecimalFormat("00");
        timer=new Timer(10,new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                if(centiseconds>0){
                    centiseconds--;
                }else{
                    if(seconds==0&&minutes==0){
                        timer.stop();
                    }else if(seconds>0){
                        seconds--;
                        centiseconds=99;
                    }else if(minutes>0){
                        minutes--;
                        seconds=59;
                        centiseconds=99;
                    }
                }
                timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
            }
        });
        timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
        add(aux);
        setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent e){
	}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar

cambiar texto jlabel

Publicado por Renzo (232 intervenciones) el 20/03/2017 17:13:13
Si deseas cambiar el random a 100 solo debes cambiar esta linea:

int numale=((int)(Math.random()*10));

por


int numale=((int)(Math.random()*100));


Unos comentarios a tu código original.

Solo tenías un evento que inicia el timer y hacía las comparaciones y solo se ejecutaba al inicio

Debía tener dos, uno que inicie el timer y el otro que compare.

El número aleatorio lo debes generar solo una vez y debe ser una variable de todo el apple. Al tenerlo dentro del evento comparar significaba que cada vez que se intentaba se generaba un número nuevo y eso hacía imposible acertar.

Por lo demás todo bien.

Espero haberte ayudado.

Renzo
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 20/03/2017 17:15:19
Muchas gracias Renzo.
Voy a probarlo ahora mismo y luego te cuento.
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
Imágen de perfil de Charly
Val: 178
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

cambiar texto jlabel

Publicado por Charly (118 intervenciones) el 20/03/2017 17:49:40
Gracias Renzo por tomarte tu tiempo en ayudarme.
Tenía mal el actionListener y el número aleatorio.
Ahora sí que me funciona a la perfección.
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

cambiar texto jlabel

Publicado por Renzo (232 intervenciones) el 20/03/2017 17:53:34
Hay un ajuste más. Debes añadir esto:

1
2
3
4
5
if(seconds==0 && centiseconds==0){
	msg.setVisible(false);
	msg.setText("Lo siento, has perdido!");
	msg.setVisible(true);
}


Al final del actionPerformed del timer.

Debería quedar así:

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
timer=new Timer(10,new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        if(centiseconds>0){
            centiseconds--;
        }else{
            if(seconds==0&&minutes==0){
                timer.stop();
            }else if(seconds>0){
                seconds--;
                centiseconds=99;
            }else if(minutes>0){
                minutes--;
                seconds=59;
                centiseconds=99;
            }
        }
        timeLabel.setText(timeFormatter.format(minutes)+":"+timeFormatter.format(seconds)+"."+timeFormatter.format(centiseconds));
 
        if(seconds==0 && centiseconds==0){
			msg.setVisible(false);
			msg.setText("Lo siento, has perdido!");
			msg.setVisible(true);
        }
 
    }
});



Saludos

Renzo
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