Atualizar JFrame utilizando SwingUtilities

1 resposta
rafael.espiritosanto

Pessoal,

não tenho experiência com o Swing do Java, de modo que não estou conseguindo que as atualizações de um JLabel sejam exibidas no frame.

Eis o código da interface gráfica

import java.awt.event.ActionEvent;

public class Visao extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4373350317027860809L;
	private JPanel contentPane;
	private JTextField textField;
	private JPasswordField passwordField;
	private JButton btnPrd;
	private JComboBox comboBox;
	private JLabel labelOperacao;
	private JFileChooser fileChooserAbertura;
	private JFileChooser fileChooserSalvamento;
	
	private ActionListener listener;
	
	public JTextField getTextField() {
		return textField;
	}

	public void setTextField(JTextField textField) {
		this.textField = textField;
	}

	public JPasswordField getPasswordField() {
		return passwordField;
	}

	public void setPasswordField(JPasswordField passwordField) {
		this.passwordField = passwordField;
	}

	public JButton getBtnPrd() {
		return btnPrd;
	}

	public void setBtnPrd(JButton btnPrd) {
		this.btnPrd = btnPrd;
	}

	public JComboBox getComboBox() {
		return comboBox;
	}

	public void setComboBox(JComboBox comboBox) {
		this.comboBox = comboBox;
	}

	public JLabel getLabelOperacao() {
		return labelOperacao;
	}

	public void setLabelOperacao(JLabel labelOperacao) {
		this.labelOperacao = labelOperacao;
	}

	public JFileChooser getFileChooserAbertura() {
		return fileChooserAbertura;
	}

	public void setFileChooserAbertura(JFileChooser fileChooserAbertura) {
		this.fileChooserAbertura = fileChooserAbertura;
	}

	public JFileChooser getFileChooserSalvamento() {
		return fileChooserSalvamento;
	}

	public void setFileChooserSalvamento(JFileChooser fileChooserSalvamento) {
		this.fileChooserSalvamento = fileChooserSalvamento;
	}

	public ActionListener getListener() {
		return listener;
	}

	public void setListener(ActionListener listener) {
		this.listener = listener;
	}

	private class RegistraListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			listener.actionPerformed(event);
		}
	}  
	
	/**
	 * Launch the application.
	 */
	public Visao() {
		super("Gerador Case");
		initGUI();
	}

	/**
	 * Create the frame.
	 */
	private void initGUI() {
		this.setVisible(true);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblUsurio = new JLabel("Usu\u00E1rio");
		lblUsurio.setBounds(10, 21, 46, 14);
		contentPane.add(lblUsurio);
		
		JLabel lblSenha = new JLabel("Senha");
		lblSenha.setBounds(10, 49, 46, 14);
		contentPane.add(lblSenha);
		
		textField = new JTextField();
		textField.setBounds(77, 18, 137, 20);
		contentPane.add(textField);
		textField.setColumns(10);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(77, 46, 137, 20);
		contentPane.add(passwordField);
		
		comboBox = new JComboBox();
		comboBox.setBounds(77, 77, 90, 20);
		comboBox.addItem("POC07");
		comboBox.addItem("DOT01");
		
		contentPane.add(comboBox);
		
		JLabel lblRepositrio = new JLabel("Reposit\u00F3rio");
		lblRepositrio.setBounds(10, 80, 69, 14);
		contentPane.add(lblRepositrio);
		
		btnPrd = new JButton("Abrir PRD");
		btnPrd.setBounds(78, 125, 89, 23);
		btnPrd.addActionListener(new RegistraListener());
		contentPane.add(btnPrd);
		
		labelOperacao = new JLabel("");
		labelOperacao.setBounds(10, 173, 242, 32);
		contentPane.add(labelOperacao);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(10, 159, 242, 2);
		contentPane.add(separator);
		
		fileChooserAbertura = new JFileChooser();
		fileChooserSalvamento = new JFileChooser();
		
		//pack();
		this.setSize(270, 250);
	}
}

Está é uma versão resumida do Controlador

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

import jxl.Sheet;

public class GeradorCaseController implements ActionListener {

	
	private Visao visao;
	
	private LeArquivoPRD arquivoPRD;
	private GeradorCase geradorCase;

	public GeradorCaseController() {
		Thread t = new Thread() {
			public void run() {
				
			}
		};
		
		visao = new Visao();
		visao.setListener(this);
		visao.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JButton buttonAction = (JButton) e.getSource();
		JButton buttonAbrePRD = visao.getBtnPrd();
		
		if (buttonAction.equals(buttonAbrePRD)) {
			String usuario = visao.getTextField().getText().trim();
			char[] senhaInformada = visao.getPasswordField().getPassword();
			String senha = new String(senhaInformada);
			
			String repositorio = (String) visao.getComboBox().getSelectedItem();
			
			JFileChooser fileChooserAbertura = visao.getFileChooserAbertura();
			int result = fileChooserAbertura.showOpenDialog(null);
			
			if(!(result == JFileChooser.CANCEL_OPTION)){

                                exibeMsg("<html>Carregando Lista de Tabelas</html>");

                                JFileChooser fileChooserSalvamento = visao.getFileChooserSalvamento();
				int resultSalvamento = fileChooserSalvamento.showOpenDialog(null);

				if(!(resultSalvamento == JFileChooser.CANCEL_OPTION)){
                                    exibeMsg("<html>Exibir outra mensagem</html>");
                                }
                        }
		}
	}

	private void exibeMsg(final String mensagem) {
		//visao.getLabelOperacao().setText(mensagem);
		//visao.getLabelOperacao().repaint();
		
		SwingUtilities.invokeLater(new Runnable() {
		    public void run() {
		      // Here, we can safely update the GUI
		      // because we'll be called from the
		      // event dispatch thread
		      //statusLabel.setText("Query: " + queryNo);
		    	visao.getLabelOperacao().setText(mensagem);
		    	visao.getLabelOperacao().repaint();
		    }
		  });	

	}
}

Somente após envocar o segundo JFileChooser consigo atualizar o frame com a mensagem “Exibir outra mensagem”. No entanto, não consigo atualizar o frame para exibição da primeira mensagem (“Carregando Lista de Tabelas”). Sei que tem a questão de utilizar uma thread distinta para lidar com atualizações na interface, mas não estou sabendo como proceder.

Obrigado!

1 Resposta

InicianteJavaHenriqu

É uma boa prática deixar que a classe que instancia a GUI chame o método setVisible(true); do JFrame, mas caso não queria fazer isto, pelo menos chame este método ao final do initGUI();

:thumbup:

Criado 29 de junho de 2012
Ultima resposta 29 de jun. de 2012
Respostas 1
Participantes 2