Jump to content
  • Revista PROGRAMAR: Já está disponível a edição #60 da revista programar. Faz já o download aqui!

Sign in to follow this  
rsacramento

melhorar o código

Recommended Posts

rsacramento

a aplicação que mostro a seguir funciona tal qual eu quero: se a tecla CAPS estiver ligada então a aplicação mostra que sim, tendo um label a dizer CAPS; caso alterne, o label também, e por aí fora

contudo tenho código duplicado e não sei como optimizá-lo

já li o how to Use Actions dos sun java tutorials mas fiquei mais ou menos na mesma

alguém tem alguma ideia?

obrigado antecipadamente

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

public class PanelPrincipal extends JPanel {
static final String CAPS_SELECCIONADO = "clicado";
static final String CAPS_LOCK = "CAPS_LOCK";
JPanel panel, rodape;
Action capsAction;
JLabel labelCaps;
static final Toolkit toolkit = Toolkit.getDefaultToolkit();

public PanelPrincipal() {
	super();

	// sem isto não funciona
	capsAction = new AbstractAction() {
		public void actionPerformed(ActionEvent e) {
			rodape = (PanelRodape)e.getSource();
			labelCaps = (JLabel)rodape.getComponent(0);

			if (toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK))
				labelCaps.setText("CAPS");
			else
				labelCaps.setText("");
		}
	};

	povoaPanel();
	criaGui();
}

public void povoaPanel() {
	rodape = new PanelRodape();
	labelCaps = (JLabel)rodape.getComponent(0);

	// faz o esquema funcionar desde o arranque
	if (toolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK))
		labelCaps.setText("CAPS");
	else
		labelCaps.setText("");

	rodape.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(CAPS_LOCK), CAPS_SELECCIONADO);
	rodape.getActionMap().put(CAPS_SELECCIONADO, capsAction);

	setLayout(new BorderLayout());
	add(new JScrollPane(new JTable(2, 2)));
	add(rodape, BorderLayout.PAGE_END);
}

private void criaGui() {
	JFrame frame = new JFrame("CAPS ligado?");
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.getContentPane().add(this);
	frame.pack();
	frame.setLocationRelativeTo(null);
	frame.setVisible(true);
}

public static void main (String args[]) {
	SwingUtilities.invokeLater(new Runnable() {
		public void run() {
			new PanelPrincipal();
		}
	});
}
}

class PanelRodape extends JPanel {
public PanelRodape() {
	add(new JLabel());
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.