Java/Swing/Widgets

Origem: Wikilivros, livros abertos por um mundo aberto.

O conceito de widget está explicado em Programação em GUI/Widgets.

Exemplo[editar | editar código-fonte]

Este programa tem o objetivo de mostrar como é simples exibir vários widgets em um aplicativo. O widget raiz é um Box, que foi criado de forma a empilhar seus widgets filhos verticalmente. Um destes filhos é outro Box, que empilha seus filhos horizontalmente.

Estes widgets não fazem nada: os botões podem ser pressionados, pode-se entrar com texto nos campos de texto, pode-se mover o slider, mas não acontece nada de prático com estas modificações (a imagem que aparece à direita é um screenshot do programa, que foi chamado de swing_demo_1 - esta imagem, obviamente, é totalmente estática).

O programa também carece de estética: o objetivo é mostrar que se pode empilhar widgets.

import javax.swing.*;  //All swing components live
		       //in the javax.swing package
 
// many widgets under a box
public class swing_demo_1 {
 
	public static void main(String[] args) {

		// creates the Frame
 		JFrame frame = new JFrame("swing_demo_1");

		// defines frame
 		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
 
		// creates the (vertical) box
		Box vbox = new Box(BoxLayout.Y_AXIS);

		// places the box inside the frame
		frame.add(vbox);
 
		// creates the elements of the vbox
		// creates the label
		JLabel label = new JLabel("label");
		// creates the pushbutton
		JButton button = new JButton("Click here");
		// creates the horizontal slider
		JSlider slider = new JSlider(JSlider.HORIZONTAL);
		// creates the text editor 
		JTextArea textarea = new JTextArea();
		// creates the horizontal box
		Box hbox = new Box(BoxLayout.X_AXIS);

		// creates the elements of the hbox
		JLabel label1 = new JLabel("x =");
		JTextField textfield = new JTextField("100");

		// add label, button, slider, TODO and hbox inside the vbox
		vbox.add(label);
		vbox.add(button);
		vbox.add(slider);
		vbox.add(textarea);
		vbox.add(hbox);

		// add label1 and textfield inside the hbox
		hbox.add(label1);
		hbox.add(textfield);

		// set frame to a decent size (default is a small frame)
		frame.setSize(212, 258);
 
		// makes frame (and everything in it) visible 
		frame.setVisible(true);
	}
}

Ligações externas[editar | editar código-fonte]