Java - Problema con ActionListener en ventana en segundo plano

 
Vista:
Imágen de perfil de Alejandro
Val: 54
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Problema con ActionListener en ventana en segundo plano

Publicado por Alejandro (19 intervenciones) el 22/11/2019 17:48:56
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Tengo un JFrame que implementa ActionListener y una clase que extiende ActionEvent para generar los eventos.
El programa reacciona a los eventos mientras la ventana tenga el Foco, si cambio de ventana el programa deja de responder a los eventos. Yo necesito que aunque la ventana este minimizada responda a los eventos.
Cualquier ayuda es bienvenida, gracias.

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
package servidorHuellero;
import servidorHuellero.Gui;
 
import java.awt.event.ActionListener;
import java.util.Vector;
 
import javax.swing.*;
 
import com.digitalpersona.uareu.*;
 
public class Servidor {
	public static Socket miServidor;
	public static Gui frmServidor;
	public static ReaderCollection m_collection;
 
	public static ActionListener prueba;
 
	public static void main(String args[]){
        SwingUtilities.invokeLater(
        	new Runnable() {
        		@Override
        		public void run() {
        			frmServidor = new Gui();
 
        	        try{
        				m_collection = UareUGlobal.GetReaderCollection();
        				m_collection.GetReaders();
        			}
        			catch(UareUException e) {
        			    JOptionPane.showMessageDialog(null, "UareUGlobal.getReaderCollection()"+e);
        				return;
        			}
 
        	        Vector<String> lectores = new Vector<String>();
        			for(int i = 0; i < m_collection.size(); i++){
        				lectores.add(m_collection.get(i).GetDescription().name);
        			}
        			frmServidor.poblarLectores(lectores);
        		}
        	}
        );
	}
}


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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package servidorHuellero;
 
import java.awt.*;
import java.net.URL;
import javax.swing.*;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Vector;
 
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.digitalpersona.uareu.*;
 
import servidorHuellero.EnrollmentThread;
 
public class Gui extends JFrame implements ActionListener  {
	private JComboBox lstLectores;
	private Reader           m_reader;
	private EnrollmentThread m_enrollment;
	private CaptureThread 	 m_capture;
	private boolean m_bJustStarted;
	private Fmd fmdCandidato;
	private Fmd fmdUsuario;
 
	private static final String ACT_SELECTION = "selection";
	private static final String ACT_TOGGLE_SERVICE = "toggleService";
 
	private JTextField txtPuerto;
	private JRadioButton rdoInscripcion;
 
	JTextArea txtLogs;
	public Gui() {
		initComponents();
	}
 
	private void initComponents() {
        if (!SystemTray.isSupported()) {
            JOptionPane.showMessageDialog(null, "SystemTrya no esta soportado");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon = new TrayIcon(createImage("img/fingerprint.gif", "tray icon"));
        final SystemTray tray = SystemTray.getSystemTray();
 
        MenuItem showItem = new MenuItem("Abrir ventana");
        MenuItem exitItem = new MenuItem("Cerrar programa");
 
        popup.add(showItem);
        popup.add(exitItem);
 
        trayIcon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	Servidor.frmServidor.setVisible(true);
            }
        });
 
        showItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	Servidor.frmServidor.setVisible(true);
            }
        });
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	System.exit(0);
            }
        });
 
        trayIcon.setPopupMenu(popup);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }
 
		m_bJustStarted = true;
 
		setTitle("Servidor Huellero");
		setLayout(null);
		setResizable(false);
		setBounds(0, 0, 480, 437);
 
		JLabel lblLectores = new javax.swing.JLabel();
		lblLectores.setText("Lector");
		lblLectores.setBounds(10, 10, 100, 20);
		getContentPane().add(lblLectores);
 
		lstLectores = new JComboBox();
		lstLectores.setBounds(10, 30, 455, 20);
		lstLectores.setActionCommand(ACT_SELECTION);
		lstLectores.addActionListener(this);
		getContentPane().add(lstLectores);
 
		JLabel lblPuerto = new JLabel();
		lblPuerto.setText("Puerto:");
		lblPuerto.setBounds(10, 60, 100, 20);
		getContentPane().add(lblPuerto);
 
		txtPuerto = new JTextField();
		txtPuerto.setText("8080");
		txtPuerto.setBounds(60, 60, 50, 20);
		getContentPane().add(txtPuerto);
 
		JLabel lblModo = new JLabel();
		lblModo.setText("Modo:");
		lblModo.setBounds(125,60,100,20);
		getContentPane().add(lblModo);
 
		rdoInscripcion = new JRadioButton();
		rdoInscripcion.setText("Inscripción");
		rdoInscripcion.setBounds(160,60,90,20);
		getContentPane().add(rdoInscripcion);
 
		JRadioButton rdoIdentificacion = new JRadioButton();
		rdoIdentificacion.setText("Identificación");
		rdoIdentificacion.setBounds(255,60,110,20);
		rdoIdentificacion.setSelected(true);
		getContentPane().add(rdoIdentificacion);
 
		ButtonGroup gpoModo = new ButtonGroup();
		gpoModo.add(rdoInscripcion);
		gpoModo.add(rdoIdentificacion);
 
		javax.swing.JButton cmdServicio = new javax.swing.JButton();
		cmdServicio.setText("Iniciar");
		cmdServicio.setBounds(365,60,100,20);
		cmdServicio.setActionCommand(ACT_TOGGLE_SERVICE);
		cmdServicio.addActionListener(this);
		getContentPane().add(cmdServicio);
 
		txtLogs = new javax.swing.JTextArea();
		txtLogs.setEditable(false);
		txtLogs.setBackground(new java.awt.Color(200, 200, 200));
		javax.swing.JScrollPane scrollLogs = new javax.swing.JScrollPane();
		scrollLogs.setViewportView(txtLogs);
		scrollLogs.setBounds(10, 90, 455, 200);
		getContentPane().add(scrollLogs);
	}
 
	public void poblarLectores(Vector<String> lectores) {
		lstLectores.setModel(new DefaultComboBoxModel(lectores.toArray()));
 
		if( lstLectores.getModel().getSize() > 0 ) {
			lstLectores.setSelectedIndex(0);
		}
 
		try{
			m_reader.Open(Reader.Priority.COOPERATIVE);
		}
		catch(UareUException e){ JOptionPane.showMessageDialog(null,"Reader.Open() " + e); }
 
	}
 
	private void StartCaptureThread(){
		m_capture = new CaptureThread(m_reader, false, Fid.Format.ANSI_381_2004, Reader.ImageProcessing.IMG_PROC_DEFAULT);
		m_capture.start(this);
	}
	private void WaitForCaptureThread(){
		if(null != m_capture) m_capture.join(1000);
	}
	private boolean ProcessCaptureResult(CaptureThread.CaptureEvent evt){
		boolean bCanceled = false;
 
		if(null != evt.capture_result){
			if(null != evt.capture_result.image && Reader.CaptureQuality.GOOD == evt.capture_result.quality){
				Engine engine = UareUGlobal.GetEngine();
 
				try{
					Fmd fmd = engine.CreateFmd(evt.capture_result.image, Fmd.Format.ANSI_378_2004);
					if(null == fmdUsuario) fmdUsuario = fmd;
				}
				catch(UareUException e){ JOptionPane.showMessageDialog(null,"Engine.CreateFmd() " + e); }
 
				if(null != fmdUsuario &&  null != fmdCandidato){
					try{
						int falsematch_rate = engine.Compare(fmdUsuario, 0, fmdCandidato, 0);
 
						int target_falsematch_rate = Engine.PROBABILITY_ONE / 100000;
						if(falsematch_rate < target_falsematch_rate){
							writeLog("Las huellas coinciden.\n");
							String str = String.format("Puntaje de falta de parecido: 0x%x.\n", falsematch_rate);
							writeLog(str);
							str = String.format("Taza de falsa coincidencia: %e.\n\n\n", (double)(falsematch_rate / Engine.PROBABILITY_ONE));
							writeLog(str);
						}
						else{
							writeLog("Las huellas no coinciden.\n\n\n");
						}
					}
					catch(UareUException e){ JOptionPane.showMessageDialog(null,"Engine.CreateFmd() " + e); }
 
					fmdUsuario = null;
				}
			}
			else if(Reader.CaptureQuality.CANCELED == evt.capture_result.quality){
				bCanceled = true;
			}
			else{
				JOptionPane.showMessageDialog(null,evt.capture_result.quality);
			}
		}
		else if(null != evt.exception){
			JOptionPane.showMessageDialog(null,"Captura " + evt.exception);
			bCanceled = true;
		}
		else if(null != evt.reader_status){
			JOptionPane.showMessageDialog(null,evt.reader_status);
			bCanceled = true;
		}
 
		return !bCanceled;
	}
 
	public void actionPerformed(ActionEvent e){
		if(e.getActionCommand().equals(ACT_SELECTION)){
			if(lstLectores.getSelectedIndex() != -1) {
				m_reader = Servidor.m_collection.get(lstLectores.getSelectedIndex());
			}
		}else if(e.getActionCommand().equals(ACT_TOGGLE_SERVICE)) {
			int port = Integer.parseInt(txtPuerto.getText());
			if(Servidor.miServidor==null) {
				Servidor.miServidor = new Socket(port);
				Servidor.miServidor.start();
			}
			if(Servidor.miServidor.isStarted()) {
				txtPuerto.setEnabled(false);
				txtLogs.append("Servidor iniciado.\n");
				txtLogs.append("Recibiendo conexiones en el puerto "+Servidor.miServidor.getPort()+".\n\n");
 
				File file = new File("fmd.dat");
				byte[] bytesArray = new byte[(int) file.length()];
 
				FileInputStream fileFMD;
				try {
					fileFMD = new FileInputStream(file);
					fileFMD.read(bytesArray);
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
 
				try {
					fmdCandidato = UareUGlobal.GetImporter().ImportFmd(bytesArray,Fmd.Format.ANSI_378_2004,Fmd.Format.ANSI_378_2004);
				}catch(UareUException e1){
					System.out.println(e1);
				}
 
				StartCaptureThread();
 
 
			}else {
				txtLogs.append("Error al iniciar el servidor.\n");
			}
 
		}else if(e.getActionCommand().equals(CaptureThread.ACT_CAPTURE)){
			if( rdoInscripcion.isSelected() ) {
				m_enrollment = new EnrollmentThread(m_reader, this);
				m_enrollment.start();
 
			}else {
				CaptureThread.CaptureEvent evt = (CaptureThread.CaptureEvent)e;
				if(ProcessCaptureResult(evt)){
					WaitForCaptureThread();
					StartCaptureThread();
				}
			}
		}else{
			EnrollmentThread.EnrollmentEvent evt = (EnrollmentThread.EnrollmentEvent)e;
			if(e.getActionCommand().equals(EnrollmentThread.ACT_PROMPT)){
				if(m_bJustStarted){
					txtLogs.append("Iniciando enrolamiento\n");
					txtLogs.append("\tpon cualquier dedo en el lector\n");
				}
				else{
					txtLogs.append("\tpon de nuevo el dedo en el lector\n");
				}
				m_bJustStarted = false;
			}
			else if(e.getActionCommand().equals(EnrollmentThread.ACT_CAPTURE)){
				if(null != evt.capture_result){
					JOptionPane.showMessageDialog(null,evt.capture_result.quality);
				}
				else if(null != evt.exception){
					JOptionPane.showMessageDialog(null,"Captura " + evt.exception);
				}
				else if(null != evt.reader_status){
					JOptionPane.showMessageDialog(null,evt.reader_status);
				}
				m_bJustStarted = false;
			}
			else if(e.getActionCommand().equals(EnrollmentThread.ACT_FEATURES)){
				if(null == evt.exception){
					txtLogs.append("\thuella capturada, caracteristicas extraidas\n\n");
				}
				else{
					JOptionPane.showMessageDialog(null,"Extracción de caracteristicas" + evt.exception);
				}
				m_bJustStarted = false;
			}
			else if(e.getActionCommand().equals(EnrollmentThread.ACT_DONE)){
				if(null == evt.exception){
					String str = String.format("    plantilla de enrolamiento creada, tamaño: %d\n\n\n", evt.enrollment_fmd.getData().length);
					txtLogs.append(str);
				}
				else{
					JOptionPane.showMessageDialog(null,"Creando plantilla de enrolamiento." + evt.exception);
				}
				m_bJustStarted = true;
			}
 
		}
	}
 
	public void writeLog(String mensaje) {
		txtLogs.append(mensaje);
	}
 
    protected static Image createImage(String path, String description) {
        URL imageURL = Gui.class.getResource(path);
 
        if (imageURL == null) {
            System.err.println("Recurso no encontrado: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }
 
}

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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package servidorHuellero;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import com.digitalpersona.uareu.*;
 
public class CaptureThread extends Thread
{
	public static final String ACT_CAPTURE = "capture_thread_captured";
 
	public class CaptureEvent extends ActionEvent{
		private static final long serialVersionUID = 101;
 
		public Reader.CaptureResult capture_result;
		public Reader.Status        reader_status;
		public UareUException       exception;
 
		public CaptureEvent(Object source, String action, Reader.CaptureResult cr, Reader.Status st, UareUException ex){
			super(source, ActionEvent.ACTION_PERFORMED, action);
			capture_result = cr;
			reader_status = st;
			exception = ex;
		}
	}
 
	private ActionListener m_listener;
	private boolean m_bCancel;
	private Reader  m_reader;
	private boolean m_bStream;
	private Fid.Format             m_format;
	private Reader.ImageProcessing m_proc;
	private CaptureEvent m_last_capture;
 
	public CaptureThread(Reader reader, boolean bStream, Fid.Format img_format, Reader.ImageProcessing img_proc){
		m_bCancel = false;
		m_reader = reader;
		m_bStream = bStream;
		m_format = img_format;
		m_proc = img_proc;
	}
 
	public void start(ActionListener listener){
		m_listener = listener;
		super.start();
	}
 
	public void join(int milliseconds){
		try{
			super.join(milliseconds);
		}
		catch(InterruptedException e){ e.printStackTrace(); }
	}
 
	public CaptureEvent getLastCaptureEvent(){
		return m_last_capture;
	}
 
	private void Capture(){
		try{
			//wait for reader to become ready
			boolean bReady = false;
			while(!bReady && !m_bCancel){
				Reader.Status rs = m_reader.GetStatus();
				if(Reader.ReaderStatus.BUSY == rs.status){
					//if busy, wait a bit
					try{
						Thread.sleep(100);
					}
					catch(InterruptedException e) {
						e.printStackTrace();
						break;
					}
				}
				else if(Reader.ReaderStatus.READY == rs.status || Reader.ReaderStatus.NEED_CALIBRATION == rs.status){
					//ready for capture
					bReady = true;
					break;
				}
				else{
					//reader failure
					NotifyListener(ACT_CAPTURE, null, rs, null);
					break;
				}
			}
			if(m_bCancel){
				Reader.CaptureResult cr = new Reader.CaptureResult();
				cr.quality = Reader.CaptureQuality.CANCELED;
				NotifyListener(ACT_CAPTURE, cr, null, null);
			}
 
 
			if(bReady){
				//capture
				Reader.CaptureResult cr = m_reader.Capture(m_format, m_proc, m_reader.GetCapabilities().resolutions[0], -1);
				NotifyListener(ACT_CAPTURE, cr, null, null);
			}
		}
		catch(UareUException e){
			NotifyListener(ACT_CAPTURE, null, null, e);
		}
	}
 
	private void Stream(){
		try{
			//wait for reader to become ready
			boolean bReady = false;
			while(!bReady && !m_bCancel){
				Reader.Status rs = m_reader.GetStatus();
				if(Reader.ReaderStatus.BUSY == rs.status){
					//if busy, wait a bit
					try{
						Thread.sleep(100);
					}
					catch(InterruptedException e) {
						e.printStackTrace();
						break;
					}
				}
				else if(Reader.ReaderStatus.READY == rs.status || Reader.ReaderStatus.NEED_CALIBRATION == rs.status){
					//ready for capture
					bReady = true;
					break;
				}
				else{
					//reader failure
					NotifyListener(ACT_CAPTURE, null, rs, null);
					break;
				}
			}
 
			if(bReady){
				//start streaming
				m_reader.StartStreaming();
 
				//get images
				while(!m_bCancel){
					Reader.CaptureResult cr = m_reader.GetStreamImage(m_format, m_proc, m_reader.GetCapabilities().resolutions[0]);
					NotifyListener(ACT_CAPTURE, cr, null, null);
				}
 
				//stop streaming
				m_reader.StopStreaming();
			}
		}
		catch(UareUException e){
			NotifyListener(ACT_CAPTURE, null, null, e);
		}
 
		if(m_bCancel){
			Reader.CaptureResult cr = new Reader.CaptureResult();
			cr.quality = Reader.CaptureQuality.CANCELED;
			NotifyListener(ACT_CAPTURE, cr, null, null);
		}
	}
 
	private void NotifyListener(String action, Reader.CaptureResult cr, Reader.Status st, UareUException ex){
		final CaptureEvent evt = new CaptureEvent(this, action, cr, st, ex);
 
		//store last capture event
		m_last_capture = evt;
 
		if(null == m_listener || null == action || action.equals("")) return;
 
		//invoke listener on EDT thread
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				m_listener.actionPerformed(evt);
			}
		});
	}
 
	public void cancel(){
		m_bCancel = true;
		try{
			if(!m_bStream) m_reader.CancelCapture();
		}
		catch(UareUException e){}
	}
 
	public void run(){
		if(m_bStream){
			Stream();
		}
		else{
			Capture();
		}
	}
}
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 Alejandro
Val: 54
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Problema con ActionListener en ventana en segundo plano

Publicado por Alejandro (19 intervenciones) el 22/11/2019 20:14:49
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Olvidenlo ya pude ¬_¬ era cosa del SDK del u.are.u, el parámetro en el método de apertura del lector.

Cambie la linea
1
m_reader.Open(Reader.Priority.COOPERATIVE);
por
1
m_reader.Open(Reader.Priority.EXCLUSIVE);
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
3
Comentar