blog de daniel
Crear teclas aceleradoras para actions
Posted Agosto 7th, 2008 by danielCon este método podemos asignar teclas acelaradoras a nuestros actions
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.
- Inicie sesión o regístrese para enviar comentarios
Fábrica de ventanas
Posted Agosto 7th, 2008 by danielEste 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 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.
- Inicie sesión o regístrese para enviar comentarios
Métodos para mostrar mensajes
Posted Agosto 7th, 2008 by danielMétodos sencillos para mostrar un mensaje de advertencia y otro para confirmar con si o no.
JOptionPane.showMessageDialog(this, mensaje, "Advertencia",
JOptionPane.WARNING_MESSAGE);
}
protected boolean confirmarMensaje(String mensaje) {
return JOptionPane.showConfirmDialog(this, mensaje, "Confirmar",
JOptionPane.YES_NO_OPTION) == 0;
}
- Inicie sesión o regístrese para enviar comentarios
Código para habilitar/deshabilitar JTextFields
Posted Agosto 7th, 2008 by danielCon este método podemos habilitar o deshabilitar uno o varios JTextFields además de asignar otros colores
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);
}
}
}
}
- Inicie sesión o regístrese para enviar comentarios
Código para limpiar JTextFields
Posted Agosto 7th, 2008 by danielCon este método podemos limpiar uno o varios JTextFields
if (component instanceof JTextField) {
JTextField text = (JTextField) component;
text.setText("");
} else {
if (component instanceof Container) {
for (Component c : ((Container) component).getComponents()) {
limpiar(c);
}
}
}
}
- Inicie sesión o regístrese para enviar comentarios
Código para convertir flechas y enter en tab
Posted Agosto 7th, 2008 by danielCon 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.
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);
- Inicie sesión o regístrese para enviar comentarios
Código para centrar JFrame
Posted Agosto 7th, 2008 by danielAgrega este código a tu Frame y luego llamas el método centrarVentana en el evento windowOpened
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);
}
- Inicie sesión o regístrese para enviar comentarios
Código para arrastrar JFrame con el mouse
Posted Agosto 7th, 2008 by danielEn los eventos mousePressed y mouseDragged del JFrame agrega este código
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);
}
- Inicie sesión o regístrese para enviar comentarios
JTextField Númerico
Posted Agosto 7th, 2008 by danielCrea un clase NumericDocument con el siguiente código
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());
- Inicie sesión o regístrese para enviar comentarios
Panel con imagen redimensionable
Posted Agosto 7th, 2008 by danielAquí los comparto el código que use para incluir imagenes en un panel
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) {
- Inicie sesión o regístrese para enviar comentarios
- Leer más
Comentarios recientes
hace 4 días 4 horas
hace 6 días 23 horas
hace 1 semana 4 horas
hace 1 semana 14 horas
hace 1 semana 15 horas
hace 1 semana 1 día
hace 1 semana 3 días
hace 1 semana 4 días
hace 1 semana 4 días
hace 1 semana 6 días