blog de daniel

Crear teclas aceleradoras para actions

Con este método podemos asignar teclas acelaradoras a nuestros actions

        protected void crearAcelerador(int key, Action action) {
                getRootPane()
                                .getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                                .put(KeyStroke.getKeyStroke(key, 0),
                                                action.getValue(Action.SHORT_DESCRIPTION));
                getRootPane().getActionMap().put(
                                action.getValue(Action.SHORT_DESCRIPTION), action);
        }

Lo podemos usar de la siguiente manera:
crearAcelerador(KeyEvent.VK_ESCAPE, salirAction);

Con esto al presionar la tecla escape se ejecutará el código que tenemos en la acción salir.

Fábrica de ventanas

Este código lo podemos usar en nuestro menú principal para crear las ventanas de la aplicación a partir del nombre del action que este asignado a un menú o botón

        private class VentanaAction extends AbstractAction {
                private static final long serialVersionUID = 1L;

                VentanaAction(String name, int key) {
                        super(name);
                        putValue(MNEMONIC_KEY, key);
                }

                private void crearVentana(AbstractAction action) {
                        try {
                                JFrame form = (JFrame) Class.forName(
                                                "presentacion." + action.getValue(NAME) + "Form")
                                                .newInstance();
                                form.setVisible(true);
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                }

                public void actionPerformed(ActionEvent e) {
                        crearVentana(this);
                }
        }

Nuestro action puede estar declarado así:
private VentanaAction consultasAction = new VentanaAction("Consultas", KeyEvent.VK_C);

Con esto al presionar alt + c se instanciara la clase presentacion.ConsultasForm que hereda de JFrame.

Métodos para mostrar mensajes

Métodos sencillos para mostrar un mensaje de advertencia y otro para confirmar con si o no.

        protected void mostrarMensaje(String mensaje) {
                JOptionPane.showMessageDialog(this, mensaje, "Advertencia",
                                JOptionPane.WARNING_MESSAGE);
        }

        protected boolean confirmarMensaje(String mensaje) {
                return JOptionPane.showConfirmDialog(this, mensaje, "Confirmar",
                                JOptionPane.YES_NO_OPTION) == 0;
        }

Código para habilitar/deshabilitar JTextFields

Con este método podemos habilitar o deshabilitar uno o varios JTextFields además de asignar otros colores

        protected void habilitarControles(Component component, boolean b) {
                if (component instanceof JTextField) {
                        JTextField text = ((JTextField) component);
                        text.setEnabled(b);
                        if (b) {
                                text.setDisabledTextColor(new Color(0, 0, 0));
                                text.setBackground(new Color(255, 255, 255));
                        } else {
                                text.setDisabledTextColor(new Color(0, 40, 240));
                                text.setBackground(new Color(240, 240, 240));
                        }
                } else {
                        if (component instanceof Container) {
                                for (Component c : ((Container) component).getComponents()) {
                                        habilitarControles(c, b);
                                }
                        }
                }
        }

Código para limpiar JTextFields

Con este método podemos limpiar uno o varios JTextFields

        protected void limpiar(Component component) {
                if (component instanceof JTextField) {
                        JTextField text = (JTextField) component;
                        text.setText("");
                } else {
                        if (component instanceof Container) {
                                for (Component c : ((Container) component).getComponents()) {
                                        limpiar(c);
                                }
                        }

                }
        }

Código para convertir flechas y enter en tab

Con este código al presionar enter y flecha abajo se hará un tab. También al presionar shift + enter y flecha arriba se hará un shift + tab.

                Set<AWTKeyStroke> teclasTab = new HashSet<AWTKeyStroke>();
                teclasTab.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
                teclasTab.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_DOWN, 0));
                teclasTab.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0));
                getContentPane().setFocusTraversalKeys(
                                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, teclasTab);
                Set<AWTKeyStroke> teclasShiftTab = new HashSet<AWTKeyStroke>();
                teclasShiftTab.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER,
                                InputEvent.SHIFT_DOWN_MASK));
                teclasShiftTab.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_UP, 0));
                teclasShiftTab.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,
                                InputEvent.SHIFT_DOWN_MASK));
                getContentPane().setFocusTraversalKeys(
                                KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, teclasShiftTab);

Código para centrar JFrame

Agrega este código a tu Frame y luego llamas el método centrarVentana en el evento windowOpened

        protected void this_windowOpened(WindowEvent e) {
                centrarVentana();
        }

        private void centrarVentana() {
                // Se obtienen las dimensiones en pixels de la pantalla.
                Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();

                // Se obtienen las dimensiones en pixels de la ventana.
                Dimension ventana = getSize();

                // Una cuenta para situar la ventana en el centro de la pantalla.
                setLocation((pantalla.width - ventana.width) / 2,
                                (pantalla.height - ventana.height) / 2);
        }

Código para arrastrar JFrame con el mouse

En los eventos mousePressed y mouseDragged del JFrame agrega este código

import java.awt.MouseInfo;
import java.awt.Point;

        private int x;
        private int y;

        protected void this_mousePressed(MouseEvent e) {
                x = e.getX();
                y = e.getY();
        }

        protected void this_mouseDragged(MouseEvent e) {
                Point point = MouseInfo.getPointerInfo().getLocation();
                setLocation(point.x - x, point.y - y);
        }

JTextField Númerico

Crea un clase NumericDocument con el siguiente código

package presentacion;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class NumericDocument extends PlainDocument {
        private static final long serialVersionUID = 1L;

        public void insertString(int offset, String str, AttributeSet a)
                        throws BadLocationException {
                if (str == null) {
                        return;
                }
                StringBuffer buf = new StringBuffer(str.length());
                for (int i = 0; i < str.length(); i++) {
                        if (Character.isDigit(str.charAt(i))) {
                                buf.append(str.charAt(i));
                        } else {
                                java.awt.Toolkit.getDefaultToolkit().beep();
                        }
                }
                super.insertString(offset, buf.toString(), a);
        }

}

Ahora solo hay que asignarselo al JTextField así:
numeroText.setDocument(new NumericDocument());

Panel con imagen redimensionable

Aquí los comparto el código que use para incluir imagenes en un panel

package presentacion;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class FondoPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        private Image image = null;
        private Image intermediateImage = null;
        private Icon icon;

        public FondoPanel() {
                super();
        }

        public void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (getImage() != null) {
                        if (intermediateImage == null
                                        || intermediateImage.getWidth(null) != getWidth()
                                        || intermediateImage.getHeight(null) != getHeight()) {
                                intermediateImage = createImage(getWidth(), getHeight());
                                Graphics gImg = intermediateImage.getGraphics();
                                gImg.drawImage(getImage(), 0, 0, getWidth(), getHeight(), null);
                        }
                        g.drawImage(intermediateImage, 0, 0, null);
                }
        }

        private Image getImage() {
                return image;
        }

        private void setImage(Image image) {
                this.image = image;
        }

        public Icon getIcon() {
                return icon;
        }

        public void setIcon(Icon icon) {

Distribuir contenido