Vous êtes sur la page 1sur 14

Package com.chuidiang.ejemplos.

toolbar;
Import java.awt.BorderLayout;
Import javax.swing.JButton;
Import javax.swing.JFrame;
Import javax.swing.JTextArea;
Import javax.swing.JToolBar;
Public class PruebaJToolBar {
Public Static void main (String [] args) {
New PruebaJToolBar ();
}
Public PruebaJToolBar () {
JFrame ventana Principal = new JFrame ("Prueba JToolBar");
JTextArea componentePrincipal = new JTextArea (25, 80);
JToolBar toolBar = getToolBar ();
ventanaPrincipal.getContentPane ().add (componentePrincipal);
ventanaPrincipal.getContentPane ().add (toolBar, BorderLayout.NORTH);
ventanaPrincipal.pack ();
ventanaPrincipal.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
ventanaPrincipal.setLocationRelativeTo (null);
ventanaPrincipal.setVisible (true);
}
Private JToolBar getToolBar () {
JToolBar barra Botones = new JToolBar ();
barraBotones.add (new JButton ("1"));
barraBotones.add (new JButton ("2"));
barraBotones.add (new JButton ("3"));
barraBotones.add (new JButton ("4"));
barraBotones.add (new JButton ("5"));
Return barra Botones;
}
}

// ToolBarExample.java
// An example of JToolBar. The actions used to build the toolbar are also
// placed in a JMenu to further demonstrate the flexibility of the Action
// class. (See the examples in Chapter 3 for more details on Action.)
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class ToolBarExample extends JPanel {
public JTextPane pane;
public JMenuBar menuBar;
public JToolBar toolBar;
String fonts[] =
{"Serif","SansSerif","Monospaced","Dialog","DialogInput"};
public ToolBarExample() {
menuBar = new JMenuBar();
// Create a set of actions to use in both the menu and toolbar
DemoAction leftJustifyAction = new DemoAction("Left",
new ImageIcon("left.gif"), "Left justify text", 'L');
DemoAction rightJustifyAction = new DemoAction("Right",
new ImageIcon("right.gif"), "Right justify text", 'R');
DemoAction centerJustifyAction = new DemoAction("Center",
new ImageIcon("center.gif"), "Center justify text", 'M');
DemoAction fullJustifyAction = new DemoAction("Full",
new ImageIcon("full.gif"), "Full justify text", 'F');
JMenu formatMenu = new JMenu("Justify");
formatMenu.add(leftJustifyAction);
formatMenu.add(rightJustifyAction);
formatMenu.add(centerJustifyAction);
formatMenu.add(fullJustifyAction);
menuBar.add(formatMenu);
toolBar = new JToolBar("Formatting");
toolBar.add(leftJustifyAction);
toolBar.add(rightJustifyAction);
toolBar.add(centerJustifyAction);
toolBar.add(fullJustifyAction);
toolBar.addSeparator();
JLabel label = new JLabel("Font");
toolBar.add(label);

toolBar.addSeparator();
JComboBox combo = new JComboBox(fonts);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try { pane.getStyledDocument().insertString(0,
"Font [" + ((JComboBox)e.getSource()).getSelectedItem() +
"] chosen!\n", null);
} catch (Exception ex) { ex.printStackTrace(); }
}
});
toolBar.add(combo);
// Disable one of the Actions
fullJustifyAction.setEnabled(false);
}
public static void main(String s[]) {
ToolBarExample example = new ToolBarExample();
example.pane = new JTextPane();
example.pane.setPreferredSize(new Dimension(250, 250));
example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));
example.toolBar.setMaximumSize(example.toolBar.getSize());
JFrame frame = new JFrame("Menu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(example.menuBar);
frame.getContentPane().add(example.toolBar, BorderLayout.NORTH);
frame.getContentPane().add(example.pane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
class DemoAction extends AbstractAction {
public DemoAction(String text, Icon icon, String description,
char accelerator) {
super(text, icon);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(accelerator,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
putValue(SHORT_DESCRIPTION, description);
}
public void actionPerformed(ActionEvent e) {
try { pane.getStyledDocument().insertString(0,
"Action [" + getValue(NAME) + "] performed!\n", null);
} catch (Exception ex) { ex.printStackTrace(); }
}
}
}

JToolBar
Un JToolBar es una barra de herramientas, la cual nos facilita el uso de
alguna opcin de nuestro programa. A esta barra se le puede aadir varios
componentes ya sean etiquetas, botones, campos de texto, etc.
Imgenes

Cmo se Crea un JToolBar?

JToolBar t=new JToolBar ();


Esto crea una barra de herramientas por defecto.
JToolBar t=new JToolBar (int orientacin);
Esto crea una barra de herramientas con la orientacin especificada, existen
dos constantes para este parmetro y son JToolBar. HORIZONTAL o JToolBar.
VERTICAL.
JToolBar t=new JToolBar (String nombre);
Esto crea una barra de herramientas con el nombre pasado por parmetro.
JToolBar t=new JToolBar (String nombre, int orientacin);
Esto crea una barra de herramientas con el nombre y orientacin pasados
por parmetro.
Si deseas saber ms sobre esta clase, sus mtodos o cualquier informacin
puedes verla aqu.
Cdigo
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Principal extends JApplet {
JTextArea texto;
public void init(){
JToolBar barra=new JToolBar();
JLabel etiqueta=new JLabel("Simbolos");
barra.add(etiqueta);
JButton arroba=new JButton("@");
arroba.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent arg0) {


texto.append("@");
}
});
JButton reir=new JButton(":)");
reir.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
texto.append(":)");
}
});
barra.addSeparator();
barra.add(arroba);
barra.addSeparator();
barra.add(reir);
texto=new JTextArea();
JScrollPane scroll=new JScrollPane(texto);
add(barra,BorderLayout.NORTH);
add(scroll,BorderLayout.CENTER);
}
}
Explicacin
Como se puede ver en el cdigo primero creo la barra de herramientas, un
JTextArea y un JScrollPane. Luego creo una etiqueta y dos botones que son
los que van a estar en la barra de herramientas. Primero agrego la etiqueta
luego coloco un espacio o separador, para que no se vea tan juntos los
componentes, con el metodo addSeparator(). Luego agrego el botn arroba y
agrego otro separador y por ultimo agrego el otro botn.
Tambin se puede observar que al momento de crear el JScrollPane le mando
el JTextArea para que cuando el usuario digite y se pase, aparezcan las barras
de desplazamiento. Por ultimo agrego la barra en la parte superior del Applet y
el JScrollPane en el centro.
Applet
La barra de herramientas se puede arrastrar a otra posicin e incluso sacar del
Applet como una ventana independiente.

package jtoolbardemo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame("JToolBar Demo");
JToolBar toolbar = new JToolBar("Applications");
JButton btnCalendar = new JButton(new ImageIcon("images/Calendar.png"));
btnCalendar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Calendar clicked");
}
});
JButton btnClock = new JButton(new ImageIcon("images/Clock.png"));
btnClock.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Clock clicked");
}
});
JButton btnContacts = new JButton(new ImageIcon("images/Contacts.png"));
btnContacts.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Contact clicked");
}
});
JButton btnMail = new JButton(new ImageIcon("images/Mail.png"));
btnMail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Mail clicked");
}
});
JButton btnMessages = new JButton(new ImageIcon("images/Messages.png"));
btnMessages.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Messages clicked");
}
});
JButton btnPhone = new JButton(new ImageIcon("images/Phone.png"));
btnPhone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Phone clicked");
}
});
toolbar.add(btnCalendar);
toolbar.add(btnClock);
toolbar.add(btnContacts);
toolbar.add(btnMail);
toolbar.add(btnMessages);
toolbar.add(btnPhone);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(toolbar, BorderLayout.PAGE_START);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setVisible(true);
}
}

ejemplo de borderlayout
package layout;
/*
* BorderLayoutDemo.java
*
*/
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
public class BorderLayoutDemo {
public static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (!(pane.getLayout() instanceof BorderLayout)) {
pane.add(new
JLabel("Container
doesn't
BorderLayout!"));
return;
}
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(
java.awt.ComponentOrientation.RIGHT_TO_LEFT);
}
JButton button = new JButton("Button 1 (PAGE_START)");
pane.add(button, BorderLayout.PAGE_START);
//Make the center component big, since that's the
//typical usage of BorderLayout.
button = new JButton("Button 2 (CENTER)");
button.setPreferredSize(new Dimension(200, 100));
pane.add(button, BorderLayout.CENTER);
button = new JButton("Button 3 (LINE_START)");
pane.add(button, BorderLayout.LINE_START);
button = new JButton("Long-Named Button 4 (PAGE_END)");
pane.add(button, BorderLayout.PAGE_END);

use

button = new JButton("5 (LINE_END)");


pane.add(button, BorderLayout.LINE_END);

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("BorderLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Use the content pane's default BorderLayout. No need for
//setLayout(new BorderLayout());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.window
s.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLook
AndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

import java.awt.BorderLayout;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class DemoBorderLayout {


//variables y comtenedores
private JLabel etiquetaSu;
private JPanel panelIzquierdo, panelDerecho, panelInferior;
private JButton botonIz1, botonIz2, botonIz3;
private JButton botonDe1, botonDe2, botonDe3;
private JButton

botonIn1, botonIn2;

private JScrollPane scroll;

public void contruyePanelIzquierdo(){


panelIzquierdo = new JPanel();
botonIz1=new JButton("Izq1");
botonIz2=new JButton("Izq2");
botonIz3=new JButton("Izq3");

panelIzquierdo.setLayout(new BoxLayout(panelIzquierdo,BoxLayout.Y_AXIS));
panelIzquierdo.setBackground(Color.red);
panelIzquierdo.add(botonIz1);
panelIzquierdo.add(botonIz2);
panelIzquierdo.add(botonIz3);
}

public void contruyePanelDerecho(){


panelDerecho = new JPanel();
botonDe1=new JButton("Der1");
botonDe2=new JButton("Der2");
botonDe3=new JButton("Der3");
panelDerecho.setLayout(new BoxLayout(panelDerecho,BoxLayout.Y_AXIS));
panelDerecho.setBackground(Color.blue);
panelDerecho.add(botonDe1);
panelDerecho.add(botonDe2);
panelDerecho.add(botonDe3);
}

public void contruyePanelInferior(){


panelInferior = new JPanel();
botonIn1=new JButton("Aceptar");
botonIn2=new JButton("Cancelar");
panelInferior.setLayout(new FlowLayout());
panelInferior.setBackground(Color.green);
panelInferior.add(botonIn1);
panelInferior.add(botonIn2);
}

public void contruyeVentana(){


JFrame frame = new JFrame();
scroll = new JScrollPane(new JTextArea("JTextArea",10,15));
etiquetaSu = new JLabel("Demostracion por INFORUX ");
Font aux=etiquetaSu.getFont();
etiquetaSu.setFont(new Font(aux.getFontName(), aux.getStyle(), 20));
frame.setLayout(new BorderLayout());

//agregamos los paneles al frame principal


frame.add(etiquetaSu,BorderLayout.NORTH);
frame.add(scroll, BorderLayout.CENTER);
frame.add(panelIzquierdo,BorderLayout.WEST);
frame.add(panelDerecho,BorderLayout.EAST);
frame.add(panelInferior,BorderLayout.SOUTH);
//Configuramos el frame
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}

public DemoBorderLayout(){
contruyePanelInferior();
contruyePanelIzquierdo();
contruyePanelDerecho();
contruyeVentana();
}

public static void main (String [] inforux){


new DemoBorderLayout();
}
}

Los mtodos de clase S. N. Mtodo y Descripcin


1 addLayoutComponent vaco (los componentes, de objetos restricciones)
Aade el componente especificado para el diseo, utilizando el objeto de
restriccin especificada.
2 vaco addLayoutComponent (String nombre, los componentes)
Si el controlador de distribucin utiliza una cadena por componente, aade el
borrador componente para el diseo, asocindolo con la cadena especificada
por su nombre.
3 int getHgap ()
Devuelve el espacio horizontal entre los componentes.
4 flotador getLayoutAlignmentX (contenedor primario)
Devuelve la alineacin a lo largo del eje x.
5 de flotacin getLayoutAlignmentY (contenedor primario)
Devuelve la alineacin a lo largo del eje y.
6 int getVgap ()
Devuelve la distancia vertical entre los componentes.
7 nula invalidateLayout (objetivo de contenedores)
Invalida la disposicin, lo que indica que si el controlador de distribucin ha
almacenado en cach la informacin que debe ser desechada.
8 layoutContainer vaco (objetivo de contenedores)
Expone el argumento contenedor utilizando este diseo frontera.
9 Dimensin maximumLayoutSize (objetivo de contenedores)
Devuelve las dimensiones mximas para este diseo teniendo en cuenta los
componentes en el contenedor de destino especificado.
10 Dimensin minimumLayoutSize (objetivo de contenedores)
Determina el tamao mnimo del contenedor de destino que utiliza este
controlador de distribucin.

11 Dimensin preferredLayoutSize (objetivo de contenedores)


Determina el tamao preferido del recipiente de destino con este controlador de
distribucin, en base a los componentes en el recipiente.
12 removeLayoutComponent vaco (los componentes)
Elimina el componente especificado de este diseo frontero.
13 setHgap vaco (int hgap)
Establece la distancia horizontal entre los componentes.
14 setVgap vaco (int Vgap)
Establece la distancia vertical entre los componentes.
15 Cadena toString ()
Devuelve una cadena que representa el estado de este diseo frontera.

Vous aimerez peut-être aussi