Este documento presenta varias clases en Java que prueban diferentes componentes gráficos de interfaz de usuario (GUI) en Swing, incluyendo marcos, paneles de flujo, diseños de borde, campos de texto, etiquetas, botones, listas desplegables y más. Cada clase crea una ventana que prueba y demuestra el uso de un componente GUI específico.
1. PruebaFrame
import javax.swing.*;
public class PruebaFrame {
public static void main(String[] args) {
JFrame marco = new JFrame("Hola Mundo");
marco.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
marco.setSize(300, 100);
marco.setVisible(true);
}
}
2. PruebaFlowLayout
import java.awt.*;
import javax.swing.*;
public class PruebaFlowLayout extends JFrame{
private JButton botones[] = {
new JButton("Botón 1"),
new JButton("Botón 2"),
new JButton("Botón 3"),
new JButton("Botón 4"),
new JButton("Botón 5"),
new JButton("Botón 6")
};
public PruebaFlowLayout(){
super("Prueba de FlowLayout()");
Container contenedor = getContentPane();
setLayout(new FlowLayout());
for (int i = 0; i < botones.length; i++){
contenedor.add(botones[i]);
}
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]){
PruebaFlowLayout ventana =
new PruebaFlowLayout();
ventana.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
3. PruebaBorderLayout
import java.awt.*;
import javax.swing.*;
public class PruebaBorderLayout extends JFrame {
public PruebaBorderLayout() {
super("Prueba de BorderLayout()");
Container cont = getContentPane();
setLayout(new BorderLayout());
cont.add(new JLabel("Etiqueta Norte"), BorderLayout.NORTH);
cont.add(new JLabel("Etiqueta Sur"), BorderLayout.SOUTH);
cont.add(new JLabel("Etiqueta Centro"),
BorderLayout.CENTER);
cont.add(new JLabel("Etiqueta Este"), BorderLayout.EAST);
cont.add(new JLabel("Etiqueta Oeste"), BorderLayout.WEST);
setSize(300, 250);
setVisible(true);
} //constructor
public static void main(String args[]) {
PruebaBorderLayout ventana =
new PruebaBorderLayout();
ventana.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
} //método main
} //clase PruebaBorderLAyout
4. PruebaGridLayout.java
import java.awt.*;
import javax.swing.*;
public class PruebaGridLayout extends JFrame{
public PruebaGridLayout(){
super("Prueba de GridLayout()");
Container cont = getContentPane();
setLayout(new GridLayout(3, 2));
cont.add(new JLabel("Etiqueta 1"));
cont.add(new JTextField());
cont.add(new JLabel("Etiqueta 2"));
cont.add(new JTextField());
cont.add(new JLabel("Etiqueta 3"));
cont.add(new JTextField());
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]){
PruebaGridLayout ventana =
new PruebaGridLayout();
ventana.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
5. PruebaEtiqueta
import java.awt.*;
import javax.swing.*;
public class PruebaEtiqueta extends JFrame{
private JLabel lbEtq1, lbEtq2, lbEtq3;
public PruebaEtiqueta(){
super("Prueba de Etiqueta");
Container cont = getContentPane();
setLayout(new FlowLayout());
lbEtq1 = new JLabel("Etiqueta con texto");
lbEtq1.setToolTipText("Etiqueta1");
cont.add(lbEtq1);
Icon icoImagen = new ImageIcon("playbutton.gif"); //.gif, .jpg, png
lbEtq2 = new JLabel("Etiqueta con texto e icono", icoImagen, SwingConstants.LEFT);
lbEtq2.setToolTipText(“Etiqueta2");
cont.add(lbEtq2);
lbEtq3 = new JLabel();
lbEtq3.setText("Etiqueta con icono y texto en parte inferior");
lbEtq3.setIcon(icoImagen);
lbEtq3.setHorizontalTextPosition(SwingConstants.CENTER);
//Interfaz SwingConstants
lbEtq3.setVerticalTextPosition(SwingConstants.BOTTOM);
//posición texto en etiqueta
lbEtq3.setToolTipText(“Etiqueta3");
cont.add(lbEtq3);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]){
PruebaGridLayout ventana =
new PruebaGridLayout();
ventana.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
6. PruebaCamposTexto
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaCamposTexto extends JFrame{
private JTextField campoTexto1, campoTexto2, campoTexto3;
private JPasswordField clave;
public PruebaCamposTexto() {
super("Ejemplo de Campos de Texto");
Container contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());
campoTexto1 = new JTextField(10);
campoTexto2 = new JTextField("Escribe aquí el texto");
campoTexto3 = new JTextField("Campo de texto no editable", 20);
campoTexto3.setEditable(false);
clave = new JPasswordField("Texto Oculto");
contenedor.add(campoTexto1);
contenedor.add(campoTexto2);
contenedor.add(campoTexto3);
contenedor.add(clave);
ManejadorCampoTexto escucha = new ManejadorCampoTexto();
campoTexto1.addActionListener(escucha);
campoTexto2.addActionListener(escucha);
campoTexto3.addActionListener(escucha);
clave.addActionListener(escucha);
setSize(275, 170);
setVisible(true);
}
public static void main(String args[]) {
PruebaCamposTexto ventana = new PruebaCamposTexto();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
7. private class ManejadorCampoTexto implements ActionListener {
public void actionPerformed(ActionEvent evento) {
String cadena = "";
if (evento.getSource() == campoTexto1)
cadena = "CampoTexto1: " + campoTexto1.getText();
else if (evento.getSource() == campoTexto2)
cadena = "CampoTexto2: " + evento.getActionCommand();
else if (evento.getSource() == campoTexto3)
cadena = "CampoTexto3: " + evento.getActionCommand();
else if (evento.getSource() == clave)
cadena = "Clave " + new String(clave.getPassword());
JOptionPane.showMessageDialog(null, cadena);
} //actionPerformed
}//ManejadorCampoTexto
}//clase
8. DIALOGO
Dialogo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Dialogo extends Dialog {
public Dialogo(JFrame padre){
super(padre, "Prueba JDialog", true);
setLayout(new FlowLayout());
add(new JLabel("Ventana de diálogo"));
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dispose();
}
});
add(ok);
setSize(150, 125);
}
}
9. DIALOGO
PruebaDialogo
import java.awt.event.*;
import javax.swing.*;
public class PruebaDialogo extends JFrame{
private JButton boton = new JButton("Mostrar Caja de Diálogo");
private Dialogo dialogo = new Dialogo(this);
public PruebaDialogo(){
super("Prueba JDialog");
boton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dialogo.setVisible(true);
}
});
add(boton);
setSize(425, 150);
setVisible(true);
}
public static void main(String args[]){
PruebaDialogo ventana = new PruebaDialogo();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
10. PruebaAreaTexto
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaAreaTexto extends JFrame {
private JButton btCopiar;
private JTextArea aTexto1, aTexto2;
public PruebaAreaTexto(){
super("Prueba Áreas de Texto");
Box cuadro = Box.createHorizontalBox();
String cadena = "Esta es un cadena de ndemostración paran" +
"ilustrar cómo copiar texton de un área de texto a n" +
"otra, utilizando unnevento externon";
aTexto1 = new JTextArea(cadena, 10, 15);
cuadro.add(new JScrollPane(aTexto1));
btCopiar = new JButton("Copiar >>>");
cuadro.add(btCopiar);
btCopiar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evento){
aTexto2.setText(aTexto1.getSelectedText());
}
});
aTexto2 = new JTextArea(10, 15);
aTexto2.setEditable(false);
cuadro.add(new JScrollPane(aTexto2));
Container contenedor = getContentPane();
contenedor.add(cuadro);
setSize(425, 200);
setVisible(true);
}
public static void main(String args[]){
PruebaAreaTexto ventana = new PruebaAreaTexto();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
11. PruebaBotonesComando
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaBotonesComando extends JFrame {
private JButton btSimple, btImagen;
public PruebaBotonesComando() {
super("Prueba de Botones de Comando");
Container contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());
btSimple = new JButton("Botón simple");
contenedor.add(btSimple);
Icon imagen1 = new ImageIcon("img00007.gif");
Icon imagen2 = new ImageIcon("bookbig.gif");
btImagen = new JButton("Botón con Imagen", imagen1);
btImagen.setRolloverIcon(imagen2); //cambia cuando el
contenedor.add(btImagen); //ratón se coloca sobre él
ManejadorBoton escucha = new ManejadorBoton();
btSimple.addActionListener(escucha);
btImagen.addActionListener(escucha);
setSize(275, 170);
setVisible(true);
}
public static void main(String[] args) {
PruebaBotonesComando ventana = new PruebaBotonesComando();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ManejadorBoton implements ActionListener {
public void actionPerformed(ActionEvent evento) {
JOptionPane.showMessageDialog(
PruebaBotonesComando.this, "Se seleccionó: " +
evento.getActionCommand());
} //actionPerformed
}//ManejadorBoton
}
12. PruebaCasillaVerificacion
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PruebaCasillaVerificacion extends JFrame{
private JCheckBox negrita, cursiva;
private JTextField texto;
public PruebaCasillaVerificacion(){
super("Prueba Casillas de Verificación");
Container contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());
texto = new JTextField("Observar el cambio en el estilo" + " de tipo de letra");
texto.setFont(new Font("Serif", Font.PLAIN, 14));
negrita = new JCheckBox("Negrita");
cursiva = new JCheckBox("Cursiva");
contenedor.add(texto);
contenedor.add(negrita);
contenedor.add(cursiva);
ManejadorCasillaVerificacion manejador = new ManejadorCasillaVerificacion();
negrita.addItemListener(manejador);
cursiva.addItemListener(manejador);
setSize(300,100);
setVisible(true);
}
public static void main(String args[]){
PruebaCasillaVerificacion aplicacion = new PruebaCasillaVerificacion();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ManejadorCasillaVerificacion implements ItemListener{
private int valNegrita = Font.PLAIN;
private int valCursiva = Font.PLAIN;
public void itemStateChanged(ItemEvent evento){
if (evento.getSource() == negrita){
valNegrita = negrita.isSelected() ? Font.BOLD : Font.PLAIN;
}
if (evento.getSource() == cursiva){
valCursiva = cursiva.isSelected() ? Font.ITALIC : Font.PLAIN;
}
texto.setFont(new Font("Serif", valNegrita + valCursiva, 14));
}
}
}
13. PruebaBotonOpcion
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PruebaBotonOpcion extends JFrame{
private Font tipoLetraSimple, tipoLetraNegrita, tipoLetraCursiva, tipoLetraNegritaCursiva;
private JTextField texto;
private JRadioButton btSimple, btNegrita, btCursiva, btNegritaCursiva;
private ButtonGroup grupoBotones;
public PruebaBotonOpcion(){
super("Prueba Botones de Opción");
Container contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());
texto = new JTextField("Observar el cambio en el estilo de tipo de letra");
btSimple = new JRadioButton("Simple", true);
btNegrita = new JRadioButton("Negrita", false);
btCursiva = new JRadioButton("Cursiva", false);
btNegritaCursiva = new JRadioButton("Negrita/Cursiva", false);
grupoBotones = new ButtonGroup();
grupoBotones.add(btSimple);
grupoBotones.add(btNegrita);
grupoBotones.add(btCursiva);
grupoBotones.add(btNegritaCursiva);
tipoLetraSimple = new Font("Serif", Font.PLAIN, 14);
tipoLetraNegrita = new Font("Serif", Font.BOLD, 14);
tipoLetraCursiva = new Font("Serif", Font.ITALIC, 14);
tipoLetraNegritaCursiva = new Font("Serif",Font.BOLD + Font.ITALIC,14);
texto.setFont(tipoLetraSimple);
btSimple.addItemListener(new ManejadorBotonOpcion(tipoLetraSimple));
btNegrita.addItemListener(new ManejadorBotonOpcion(tipoLetraNegrita));
btCursiva.addItemListener(new ManejadorBotonOpcion(tipoLetraCursiva));
btNegritaCursiva.addItemListener(new ManejadorBotonOpcion(tipoLetraNegritaCursiva));
contenedor.add(texto);
contenedor.add(btSimple);
contenedor.add(btNegrita);
contenedor.add(btCursiva);
contenedor.add(btNegritaCursiva);
setSize(345,100);
setVisible(true);
}
14. public static void main(String args[]){
PruebaBotonOpcion aplicacion = new PruebaBotonOpcion();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ManejadorBotonOpcion implements ItemListener{
private Font tipoLetra;
public ManejadorBotonOpcion(Font f){
tipoLetra = f;
}
public void itemStateChanged(ItemEvent evento){
texto.setFont(tipoLetra);
}
}
}
15. PruebaListaDesplegable
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PruebaListaDesplegable extends JFrame{
private JComboBox lista;
private JLabel etiqueta;
private String nombres*+ = ,“p.jpg", “v.jpg", “o.jpg", “i.jpg"-;
private Icon iconos[] = {
new ImageIcon(nombres[0]), new ImageIcon(nombres[1]),
new ImageIcon(nombres[2]), new ImageIcon(nombres[3])
};
public PruebaListaDesplegable(){
super("Prueba Lista Desplegable");
Container contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());
etiqueta = new JLabel("iconos[0]");
lista = new JComboBox(nombres);
lista.setMaximumRowCount(3);
lista.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evento){
if (evento.getStateChange() == ItemEvent.SELECTED) {
etiqueta.setIcon(iconos[lista.getSelectedIndex()]);
}
}
});
contenedor.add(etiqueta);
contenedor.add(lista);
setSize(350,200);
setVisible(true);
}
public static void main(String args[]){
PruebaListaDesplegable aplicacion = new PruebaListaDesplegable();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
16. PruebaLista
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
public class PruebaLista extends JFrame{
private JList lista;
private Container contenedor;
private final String nombres[] = {
"Negro", "Azul", "Cyan", "Gris Oscuro", "Gris", "Verde", "Gris Claro",
"Magenta", "Naranja", "Rosa", "Rojo", "Blanco", "Amarillo"};
private final Color colores[] = {
Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY,
Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.RED, Color.WHITE, Color.YELLOW};
public PruebaLista(){
super("Prueba Lista");
contenedor = getContentPane();
contenedor.setLayout(new FlowLayout());
lista = new JList(nombres);
lista.setVisibleRowCount(5);
lista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lista.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent evento){
contenedor.setBackground(colores[lista.getSelectedIndex()]);
}
});
contenedor.add(new JScrollPane(lista));
setSize(370,200);
setVisible(true);
}
public static void main(String args[]){
PruebaLista aplicacion = new PruebaLista();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
17. PruebaDeslizador
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class PruebaDeslizador extends JFrame{
private JProgressBar barraProgreso;
private ProgressMonitor monitorProgreso;
private JSlider deslizador;
public PruebaDeslizador() {
super("Ejemplo de Deslizador");
Container contenedor = getContentPane();
contenedor.setLayout(new GridLayout(2, 1));
monitorProgreso = new ProgressMonitor(this, "Monitor de Progreso", "Prueba", 0, 100);
monitorProgreso.setProgress(0);
monitorProgreso.setMillisToPopup(1000);
//el monitor de progreso se incrementa y cierra al llegar al máximo
deslizador = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
//orientación, valor mínimo, máximo y valor inicial
deslizador.setValue(0);//define el valor inicial en 0 (otra vez)
deslizador.setPaintTicks(true); //muestra las marcas del deslizador
deslizador.setMajorTickSpacing(20);//define marcas mayores cada 20%
deslizador.setMinorTickSpacing(5);//define marcas menores cada 5%
deslizador.setPaintLabels(true);//muestra etiquetas en las marcas
deslizador.setBorder(new TitledBorder("Deslízame"));//agrega borde
deslizador.addChangeListener(new ChangeListener() {//(JComponent) con título
public void stateChanged(ChangeEvent e) {
monitorProgreso.setProgress(deslizador.getValue());
}
});
barraProgreso = new JProgressBar();
barraProgreso.setStringPainted(true); //muestra etiqueta de porcentaje
barraProgreso.setForeground(Color.blue); //indica color de fondo
barraProgreso.setModel(deslizador.getModel());
//asocia el deslizador y la barra de progreso al compartir modelos
contenedor.add(barraProgreso);
contenedor.add(deslizador);
setSize(275, 170);
setVisible(true);
}
18. public static void main(String args[]){
PruebaDeslizador aplicacion = new PruebaDeslizador();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} //clase
19. PruebaMenu
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaMenu extends JFrame {
private Color coloresVal[] = {Color.black, Color.blue,Color.red, Color.green};
private JMenuBar barraMenu;
private JMenu menuArchivo, menuFormato, menuColor, menuFont;
private JMenuItem opcionAcercaDe, opcionSalir;
private JToolBar barraHtas;
private ButtonGroup gbFont, gbColor;
private JButton btSalir;
private JRadioButtonMenuItem opcionesColor[], opcionesFont[];
private JCheckBoxMenuItem opcionesEstilo[];
private JLabel despliega;
private int estilo;
public PruebaMenu(){
super("Uso de Menus y Barra de Herramientas");
EventoSalir evSalir = new EventoSalir(); //objetos manejadores de eventos
EventoOpcion evOpcion = new EventoOpcion();
EventoEstilo evEstilo = new EventoEstilo();
menuArchivo = new JMenu("Archivo"); //definición del menú Archivo
menuArchivo.setMnemonic('A');
opcionAcercaDe = new JMenuItem("Acerca de..."); //subopción AcercaDe
opcionAcercaDe.setMnemonic('A');
opcionAcercaDe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(PruebaMenu.this,
"Este es un ejemplo nde uso de menús",
"Acerca De...", JOptionPane.PLAIN_MESSAGE);
}
});
20. menuArchivo.add(opcionAcercaDe);
opcionSalir = new JMenuItem("Salir"); //subopción salir del menú Archivo
opcionSalir.setMnemonic('S');
opcionSalir.setToolTipText("Salir del Programa");
opcionSalir.addActionListener (evSalir);
menuArchivo.add(opcionSalir);
menuFormato = new JMenu("Formato"); //definición del menú Formato
menuFormato.setMnemonic('F');
menuFormato.setToolTipText("Cambia Formato de Texto");
String colores[] = {"Negro", "Azul", "Rojo", "Verde"}; //Submenú Color
menuColor = new JMenu("Color");
menuColor.setMnemonic('C');
menuColor.setToolTipText("Cambia Color del Texto");
opcionesColor = new JRadioButtonMenuItem[colores.length]; //subopcion Color
gbColor = new ButtonGroup();
for (int i = 0; i < colores.length; i++) {
opcionesColor[i] = new JRadioButtonMenuItem(colores[i]);
menuColor.add(opcionesColor[i]);
opcionesColor[i].setMnemonic(colores[i].charAt(0)); //opciones de colores
gbColor.add(opcionesColor[i]);
opcionesColor[i].addActionListener(evOpcion);
}
opcionesColor[0].setSelected(true);
String nombresFont[] = {"TimesRoman", "Courier", "Helvética"}; //submenú Font
menuFont = new JMenu("Font");
menuFont.setMnemonic('F');
opcionesFont = new JRadioButtonMenuItem[nombresFont.length];
gbFont = new ButtonGroup();
for(int i = 0; i < opcionesFont.length; i++){ //definición de subopciones Font
opcionesFont[i] = new JRadioButtonMenuItem(nombresFont[i]);
menuFont.add(opcionesFont[i]);
gbFont.add(opcionesFont[i]);
opcionesFont[i].setMnemonic(nombresFont[i].charAt(0)); //opciones tipo letra
opcionesFont[i].addActionListener(evOpcion);
}
21. opcionesFont[0].setSelected(true);
menuFont.addSeparator();
String nombresEstilo[] = {"Negritas", "Itálica"}; //submenú Estilo de Formato
opcionesEstilo = new JCheckBoxMenuItem[nombresEstilo.length];
for(int i = 0; i < nombresEstilo.length; i++) {
opcionesEstilo[i] = new JCheckBoxMenuItem(nombresEstilo[i]);
menuFont.add(opcionesEstilo[i]);
opcionesEstilo[i].setMnemonic(nombresEstilo[i].charAt(0));
opcionesEstilo[i].addItemListener(evEstilo);
}
menuFormato.add(menuColor); //termina la definición del menú formato
menuFormato.addSeparator();
menuFormato.add(menuFont);
barraHtas = new JToolBar(); //definición de la barra de herramientas
btSalir = new JButton(new ImageIcon("img00007.gif")); //botón salir de la barra
btSalir.setToolTipText("Salir del Sistema");
btSalir.addActionListener(evSalir);
barraHtas.add(btSalir);
despliega = new JLabel("Texto Ejemplo", SwingConstants.CENTER); //Etiqueta
despliega.setForeground(coloresVal[0]);
despliega.setFont(new Font("TimesRoman", Font.PLAIN, 72));
getContentPane().setBackground(Color.cyan); //contenedor de ventana
getContentPane().add(barraHtas, BorderLayout.NORTH);
getContentPane().add(despliega, BorderLayout.CENTER);
barraMenu = new JMenuBar(); //barra de menús
barraMenu.add(menuArchivo);
barraMenu.add(menuFormato);
setJMenuBar(barraMenu); //definición de ventana
setSize(600, 300);
setVisible(true);
}
public static void main(String args[]) {
PruebaMenu app = new PruebaMenu();
app.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private class EventoSalir implements ActionListener {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
22. private class EventoOpcion implements ActionListener {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < opcionesColor.length; i++) {
if (opcionesColor[i].isSelected() ) {
despliega.setForeground(coloresVal[i]);
break;
}
}
for (int i = 0; i < opcionesFont.length; i++) {
if (e.getSource() == opcionesFont[i] ) {
despliega.setFont(new Font( opcionesFont[i].getText(), estilo, 72));
break;
}
}
repaint();
}
}
private class EventoEstilo implements ItemListener {
public void itemStateChanged(ItemEvent e) {
estilo = 0;
if ( opcionesEstilo[0].isSelected() ) {
estilo += Font.BOLD;
}
if ( opcionesEstilo[1].isSelected() ) {
estilo += Font.ITALIC;
}
despliega.setFont(new Font(despliega.getFont().getName(), estilo, 72));
repaint();
}
}
}
23. PruebaMenuContextual
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaMenuContextual extends JFrame {
private JRadioButtonMenuItem opcionesColor[];
private ButtonGroup gbColor;
private final Color coloresVal[]={Color.BLUE,Color.YELLOW,Color.RED, Color.GREEN};
private JPopupMenu menuContextual;
public PruebaMenuContextual(){
super("Uso de Menú Contextual");
EventoFondo evFondo = new EventoFondo(); //objeto manejador de eventos
String colores[] = {"Azul", "Amarillo", "Rojo", "Verde"}; //menú contextual
gbColor = new ButtonGroup();
menuContextual = new JPopupMenu();
opcionesColor = new JRadioButtonMenuItem[colores.length]; //subopciones Color
for (int i = 0; i < opcionesColor.length; i++) {
opcionesColor[i] = new JRadioButtonMenuItem(colores[i]);
menuContextual.add(opcionesColor[i]);
gbColor.add(opcionesColor[i]); //agrega opciones de colores al menú
opcionesColor[i].addActionListener(evFondo);
}
getContentPane().addMouseListener (new MouseAdapter() { //evento muestrar menú contextual
public void mousePressed(MouseEvent evento){
checkForTriggerEvent(evento);
}
public void mouseClicked(MouseEvent evento){
checkForTriggerEvent(evento);
}
public void mouseRelease(MouseEvent evento){
checkForTriggerEvent(evento);
}
private void checkForTriggerEvent(MouseEvent evento){
//NOTA IMPORTANTE: si la JVM no identifica el evento como disparador de menú
//contextual en la plataforma no se muestra el menú, en ese caso, para probar
//el programa se puede modificar la siguiente línea, indicando el evento
//if(evento.isPopupTrigger()){
if( ! evento.isPopupTrigger()){
menuContextual.show(evento.getComponent(), evento.getX(), evento.getY());
}
}
});
24. getContentPane().setBackground(Color.WHITE); //definición de la ventana
setSize(300, 200);
setVisible(true);
}
public static void main(String args[]) {
PruebaMenuContextual ventana = new PruebaMenuContextual();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class EventoFondo implements ActionListener {
public void actionPerformed(ActionEvent evento) {
for (int i = 0; i < opcionesColor.length; i++) {
if (evento.getSource() == opcionesColor[i]){
getContentPane().setBackground(coloresVal[i]);
return;
}
}
}
}
}
25. PruebaBoxLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaBoxLayout extends JFrame{
public PruebaBoxLayout() {
super("Prueba BoxLayout");
Box horizontal1 = Box.createHorizontalBox();
Box vertical1 = Box.createVerticalBox();
Box horizontal2 = Box.createHorizontalBox();
Box vertical2 = Box.createVerticalBox();
final int TAMANO = 3;
for (int i = 0; i < TAMANO; i++){
horizontal1.add(new JButton("Botón " + i)); //juntos
}
for (int i = 0; i < TAMANO; i++){
vertical1.add(Box.createVerticalStrut(25)); //espacio fijo
vertical1.add(new JButton("Botón " + i));
}
for (int i = 0; i < TAMANO; i++){
horizontal2.add(Box.createHorizontalGlue()); //ajusta
horizontal2.add(new JButton("Botón " + i));
}
for (int i = 0; i < TAMANO; i++){
vertical2.add(Box.createRigidArea(new Dimension(12, 8)));
vertical2.add(new JButton("Botón " + i));
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (int i = 0; i < TAMANO; i++){
panel.add(Box.createGlue()); //ajusta en Y
panel.add(new JButton("Botón " + i));
}
JTabbedPane folders = new JTabbedPane(JTabbedPane.TOP,
JTabbedPane.SCROLL_TAB_LAYOUT);
folders.addTab("Cuadro Horizontal", horizontal1);
folders.addTab("Cuadro Vertical con montante", vertical1);
folders.addTab("Cuadro Horizontal con pegamento", horizontal2);
folders.addTab("Cuadro Vertical con área rígida", vertical2);
folders.addTab("Cuadro Vertical con pegamento", panel);
26. getContentPane().add(folders);
setSize(400, 220);
setVisible(true);
}
public static void main(String[] args){
PruebaBoxLayout ventana = new PruebaBoxLayout();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
27. PruebaCardLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PruebaCardLayout extends JFrame {
JPanel pnSuperior, pnCentral, pnFicha1, pnFicha2;
JComboBox lsPaneles;
//arreglo necesario para que nombre sea siempre el mismo
String opcionesS[] = {"Panel con Botones", "Panel con Campo de Texto"};
public PruebaCardLayout() {
super("Prueba CardLayout");
setLayout( new BorderLayout() );
lsPaneles = new JComboBox();
lsPaneles.addItem(opcionesS[0]);
lsPaneles.addItem(opcionesS[1]);
pnSuperior = new JPanel();
pnSuperior.add( lsPaneles );
add( BorderLayout.NORTH, pnSuperior );
pnCentral = new JPanel();
pnCentral.setLayout( new CardLayout() );
pnFicha1 = new JPanel(); //prepara la primera ficha del CardLayout
pnFicha1.add( new JButton( "Botón 1" ) );
pnFicha1.add( new JButton( "Botón 2" ) );
pnFicha1.add( new JButton( "Botón 3" ) );
pnFicha2 = new JPanel(); //prepara la segunda ficha del CardLayout
pnFicha2.add( new JTextField( "Texto",20 ) );
pnCentral.add(pnFicha1, opcionesS[0]);
pnCentral.add(pnFicha2, opcionesS[1]);
add( BorderLayout.CENTER, pnCentral );
lsPaneles.addItemListener(new ItemListener() { //evento intercambia las fichas
public void itemStateChanged(ItemEvent evento){
((CardLayout)pnCentral.getLayout()).show(pnCentral,(String)evento.getItem());
}
});
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
PruebaCardLayout ventana = new PruebaCardLayout();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
28.
29. DemoGridBag
// Demostración de GridBagLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DemoGridBag extends JFrame
{
private Container contenedor;
private GridBagLayout esquema;
private GridBagConstraints restricciones;
// configurar GUI
public DemoGridBag()
{
super( "GridBagLayout" );
contenedor = getContentPane();
esquema = new GridBagLayout();
contenedor.setLayout( esquema );
// instanciar restricciones de GridBagLayout
restricciones = new GridBagConstraints();
// crear componentes de GUI
JTextArea areaTexto1 = new JTextArea( "AreaTexto1", 5, 10 );
JTextArea areaTexto2 = new JTextArea( "AreaTexto2", 2, 2 );
String nombres[] = { "Hierro", "Acero", "Cobre" };
JComboBox cuadroCombinado = new JComboBox( nombres );
JTextField campoTexto = new JTextField( "CampoTexto" );
JButton boton1 = new JButton( "Botón 1" );
JButton boton2 = new JButton( "Botón 2" );
JButton boton3 = new JButton( "Botón 3" );
// weightx y weighty para areaTexto1 son 0: el valor predeterminado
// anchor para todos los componentes es CENTER: el valor predeterminado
restricciones.fill = GridBagConstraints.BOTH;
agregarComponente( areaTexto1, 0, 0, 1, 3 );
30. // weightx y weighty para boton1 son 0: el valor predeterminado // establecer gridwidth y gridheight
restricciones.fill = GridBagConstraints.HORIZONTAL; restricciones.gridwidth = anchura;
agregarComponente( boton1, 0, 1, 2, 1 ); restricciones.gridheight = altura;
// weightx y weighty para cuadroCombinado son 0: el valor predeterminado // establecer restricciones y agregar componente
// fill es HORIZONTAL esquema.setConstraints( componente, restricciones );
agregarComponente( cuadroCombinado, 2, 1, 2, 1 ); contenedor.add( componente );
}
// boton2
restricciones.weightx = 1000; // puede hacerse más ancho public static void main( String args[] )
restricciones.weighty = 1; // puede hacerse más largo {
restricciones.fill = GridBagConstraints.BOTH; DemoGridBag aplicacion = new DemoGridBag();
agregarComponente( boton2, 1, 1, 1, 1 ); aplicacion.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// fill es BOTH para boton3
restricciones.weightx = 0; }
restricciones.weighty = 0;
agregarComponente( boton3, 1, 2, 1, 1 );
// weightx y weighty para campoTexto son 0, fill es BOTH
agregarComponente( campoTexto, 3, 0, 2, 1 );
// weightx y weighty para areaTexto2 son 0, fill es BOTH
agregarComponente( areaTexto2, 3, 2, 1, 1 );
setSize( 300, 150 );
setVisible( true );
} // fin del constructor de DemoGridBag
// método para establecer restricciones
private void agregarComponente( Component componente,
int fila, int columna, int anchura, int altura )
{
// establecer gridx y gridy
restricciones.gridx = columna;
restricciones.gridy = fila;
42. private int getMejorAnchoColumna(TableColumn columna){
int anchoEncabezado = anchoEncabezado(columna),
anchoInfo = anchoInfo(columna);
return anchoEncabezado > anchoInfo ? anchoEncabezado : anchoInfo;
}
private int anchoEncabezado(TableColumn columna){
return (columna.getHeaderValue().toString()).length();
}
private int anchoInfo(TableColumn columna){
int col = columna.getModelIndex(), ancho = 0, max = 0;
for (int renglon = 0; renglon < tabla.getRowCount(); renglon++){
TableCellRenderer exhibidor =
tabla.getCellRenderer(renglon, col);
Component comp = exhibidor.getTableCellRendererComponent(
tabla, tabla.getValueAt(renglon, col),
false, false, renglon, col);
ancho = comp.getPreferredSize().width;
max = ancho > max ? ancho : max;
}
return max;
}
private class ExhibidorMonedaListaCelda extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList lista, Object valor, int indice,
boolean seleccionado, boolean tieneFoco){
JLabel etiqueta = (JLabel)super.getListCellRendererComponent(
lista, valor, indice, seleccionado, tieneFoco);
Format formato = NumberFormat.getCurrencyInstance();
etiqueta.setText(valor == null ? "" : formato.format(valor));
return etiqueta;
}
}
private class ExhibidorMonedaTablaCelda extends DefaultTableCellRenderer {
public void setValur(Object valor){
Format formato = NumberFormat.getCurrencyInstance();
setText(valor == null ? "" : formato.format(valor));
}
}
}
43.
44. TABLA
PruebaTabla
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class PruebaTabla extends JFrame{
JTable tabla = new JTable(
new AbstractTableModel(){
int rens = 100, cols = 10;
public int getRowCount(){
return rens;
}
public int getColumnCount(){
return cols;
}
public Object getValueAt(int ren, int col){
return "(" + ren + ", " + col + ")";
}
}
);
public PruebaTabla(){
super ("Ventana de Prueba de Tabla");
Container cont = getContentPane();
cont.add(tabla, BorderLayout.CENTER);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]){
PruebaTabla ventana = new PruebaTabla();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
45. PruebaIGU
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class PruebaIGU extends JFrame {
private Container cont;
private JDesktopPane escritorio;
private JMenuBar barraMenu;
private JMenu menuAlumno;
private JMenuItem opAlta, opConsulta, opSalir;
public PruebaIGU(){
super("Prueba Ventanas");
escritorio = new JDesktopPane();
cont = getContentPane();
cont.add(escritorio);
menuAlumno = new JMenu("Alumno");
menuAlumno.setMnemonic('A');
opAlta = new JMenuItem("Alta de Alumnos");
opAlta.setMnemonic('A');
opAlta.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
VentanaAlta vnAlta = new VentanaAlta();
vnAlta.pack();
escritorio.add(vnAlta);
vnAlta.setSize(680, 430);
vnAlta.setVisible(true);
}
});
menuAlumno.add(opAlta);
opConsulta = new JMenuItem("Lista de Alumnos");
opConsulta.setMnemonic('L');
opConsulta.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
VentanaConsulta vnConsulta = new VentanaConsulta();
vnConsulta.pack();
escritorio.add(vnConsulta);
vnConsulta.setSize(680, 430);
vnConsulta.setVisible(true);
}
});
46. menuAlumno.add(opConsulta);
opSalir = new JMenuItem("Salir");
opSalir.setMnemonic('S');
opSalir.setToolTipText("Salir del Programa");
opSalir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
menuAlumno.add(opSalir);
barraMenu = new JMenuBar();
barraMenu.add(menuAlumno);
setJMenuBar(barraMenu);
setDefaultLookAndFeelDecorated(true);
setLocation(200, 150);
setSize(700, 500);
setVisible(true);
}
private class VentanaConsulta extends JInternalFrame{
private GridBagLayout gridBag = new GridBagLayout();
private JPanel pnOtros = new JPanel();
private JButton btLimpiar, btSalir;
private JTextField txNombre, txApPaterno, txApMaterno;
JInternalFrame ventana = this;
public VentanaConsulta(){
super("Consulta de Alumno", true, true, true, true);
setLayout(new GridLayout(3, 1));
ventana = this;
JPanel pnNombre = new JPanel();
pnNombre.setLayout(new FlowLayout());
pnNombre.add( new JLabel( "Consulta:" ) );
JPanel pnBotones = new JPanel();
pnBotones.setLayout(new FlowLayout());
btSalir = new JButton( "Cerrar" );
btSalir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ventana.doDefaultCloseAction();
}
});
pnBotones.add( btSalir );
add(pnNombre);
add(pnBotones);
}
47. }
public static void main(String args[]){
PruebaIGU ventana = new PruebaIGU();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
48. FACTURAS
NO.FACTURA
FECHA
IVA
TOTAL
NOTA NOTA_REFERENCIA
NO.NOTA
FECHA NOTAS
TIPO.NOTA COMPRA GATOS
MATERIAL VENTA FECHA
PESO CONCEPTO
PRECIO TOTAL
TOTAL TIPO_PAGO TIPO_PAGO
TIPO_PAGO CHEQUE
EFECTIVO
CHEQUES
MATERIALES
NO.CHEQUE
A/C FECHA
2DA CONCEPTO
ANGULO CANTIDAD
CORTE
PLACA
DISCOS
FLECHA
LAMINA
MONTEN
PTR
REDONDO
SOLERA
TUBO
VIGUETA