A Visual Guide to Swing Components

23
A Visual Guide to Swing Components (Java Look and Feel) This page shows Swing components in the Java look and feel. The following page shows the same components in the Windows look and feel . Basic Controls Simple components that are used primarily to get input from the user; they may also show simple state. JButton JCheckBox JComboBox JList JMenu JRadioButton JSlider JSpinner JTextField JPasswordField

description

Introduction to Jave swing components

Transcript of A Visual Guide to Swing Components

Page 2: A Visual Guide to Swing Components

JBUTTON:

import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.SwingUtilities;

public class MainClass{    public static void main(String[] a){    JFrame f = new JFrame();    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    f.add(new ButtonDemo());    f.setSize(500,500);    f.setVisible(true);  }}

class ButtonDemo extends JPanel implements ActionListener {  JTextField jtf;

  public ButtonDemo() {    try {      SwingUtilities.invokeAndWait(new Runnable() {        public void run() {          makeGUI();        }      });    } catch (Exception exc) {      System.out.println("Can't create because of " + exc);    }  }

  private void makeGUI() {    setLayout(new FlowLayout());

    ImageIcon france = new ImageIcon("france.gif");    JButton jb = new JButton(france);    jb.setActionCommand("France");    jb.addActionListener(this);    add(jb);

    ImageIcon germany = new ImageIcon("germany.gif");    jb = new JButton(germany);    jb.setActionCommand("Germany");    jb.addActionListener(this);    add(jb);

    ImageIcon italy = new ImageIcon("italy.gif");    jb = new JButton(italy);

Page 3: A Visual Guide to Swing Components

    jb.setActionCommand("Italy");    jb.addActionListener(this);    add(jb);

    ImageIcon japan = new ImageIcon("japan.gif");    jb = new JButton(japan);    jb.setActionCommand("Japan");    jb.addActionListener(this);    add(jb);

    jtf = new JTextField(15);    add(jtf);  }

  public void actionPerformed(ActionEvent ae) {    jtf.setText(ae.getActionCommand());  }}

JLabel

1. e text.

The javax.swing.JLabel class has the following constructors.

.

1.

If you want to use multifonts or multicolors in a JLabel, you can pass HTML tags,

A JLabel subclass is used as the default renderer for each of the JList, JComboBox, JTable, and JTree components.

Alignments have an effect only if there's extra space for the layout manager to position the component.

import java.awt.Color;import java.awt.Dimension;import java.awt.FlowLayout;

import javax.swing.BorderFactory;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.border.Border;

Page 4: A Visual Guide to Swing Components

public class MyLabel { public static void main(String args[]) { JFrame f = new JFrame("Label Demo"); f.setLayout(new FlowLayout()); f.setSize(200, 360); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label= new JLabel("asdf"); Border border = BorderFactory.createLineBorder(Color.BLACK); label.setBorder(border); label.setPreferredSize(new Dimension(150, 100)); label.setText("Centered"); label.setHorizontalAlignment(JLabel.LEFT); label.setVerticalAlignment(JLabel.TOP);

f.add(label);

f.setVisible(true); }}

TEXT FIELD:

import javax.swing.BoxLayout;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.text.Document;public class ShareModel { public static void main(String args[]) { JFrame frame = new JFrame("Sharing Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea textarea1 = new JTextArea(); Document document = textarea1.getDocument(); JTextArea textarea2 = new JTextArea(document); JTextArea textarea3 = new JTextArea(document); frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); frame.add(new JScrollPane(textarea1)); frame.add(new JScrollPane(textarea2)); frame.add(new JScrollPane(textarea3)); frame.setSize(300, 400); frame.setVisible(true); }}

JTextArea: for multiple-line input.

Page 5: A Visual Guide to Swing Components

Put JTextArea within a JScrollPane to allow a user to properly scroll through the contents of a JTextArea.JTextArea textArea = new JTextArea();JScrollPane scrollPane = new JScrollPane(textArea);content.add(scrollPane);

import java.awt.Dimension;import java.awt.FlowLayout;

import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;

public class JTextAreaTest { public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("JTextArea Test"); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String text = "A JTextArea object represents a multiline area for displaying text. " + "You can change the number of lines that can be displayed at a time, " + "as well as the number of columns. You can wrap lines and words too. " + "You can also put your JTextArea in a JScrollPane to make it scrollable."; JTextArea textAreal = new JTextArea(text, 5, 10); textAreal.setPreferredSize(new Dimension(100, 100)); JTextArea textArea2 = new JTextArea(text, 5, 10); textArea2.setPreferredSize(new Dimension(100, 100)); JScrollPane scrollPane = new JScrollPane(textArea2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); textAreal.setLineWrap(true); textArea2.setLineWrap(true); frame.add(textAreal); frame.add(scrollPane); frame.pack(); frame.setVisible(true); }}

PASSWORD FIELD:

import java.awt.GridLayout;

import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPasswordField;import javax.swing.JTextField;import javax.swing.SwingConstants;

public class JPasswordFieldTest extends JFrame {

Page 6: A Visual Guide to Swing Components

public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("JTextField Test"); frame.setLayout(new GridLayout(2, 2)); JLabel label = new JLabel("User Name:", SwingConstants.RIGHT); JLabel label2 = new JLabel("Password:", SwingConstants.RIGHT); JTextField userNameField = new JTextField(20); JPasswordField passwordField = new JPasswordField(); frame.add(label); frame.add(userNameField); frame.add(label2); frame.add(passwordField); frame.setSize(200, 70); frame.setVisible(true); }}

JCHECKBOX:

Creating JCheckBox Components

public JCheckBox()JCheckBox aCheckBox = new JCheckBox();

public JCheckBox(Icon icon)JCheckBox aCheckBox = new JCheckBox(new DiamondIcon(Color.RED, false));aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));

public JCheckBox(Icon icon, boolean selected)JCheckBox aCheckBox = new JCheckBox(new DiamondIcon(Color.RED, false), true);aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));

public JCheckBox(String text)JCheckBox aCheckBox = new JCheckBox("Spinach");

public JCheckBox(String text, boolean selected)JCheckBox aCheckBox = new JCheckBox("Onions", true);

public JCheckBox(String text, Icon icon)JCheckBox aCheckBox = new JCheckBox("Garlic", new DiamondIcon(Color.RED, false));aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));

public JCheckBox(String text, Icon icon, boolean selected)JCheckBox aCheckBox = new JCheckBox("Anchovies", new DiamondIcon(Color.RED,  false), trueaCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));

public JCheckBox(Action action)Action action = ...;JCheckBox aCheckBox = new JCheckBox(action);

Page 7: A Visual Guide to Swing Components

Using JCheckBox

import java.awt.FlowLayout;

import javax.swing.JCheckBox;import javax.swing.JFrame;import javax.swing.JLabel;

public class JCheckBoxTest {

  public static void main(String[] args) {    JFrame.setDefaultLookAndFeelDecorated(true);    JFrame frame = new JFrame("JCheckBox Test");    frame.setLayout(new FlowLayout());    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    JCheckBox ac = new JCheckBox("A/C");    ac.setSelected(true);    JCheckBox cdPlayer = new JCheckBox("A");    JCheckBox cruiseControl = new JCheckBox("B");    JCheckBox keylessEntry = new JCheckBox("C");    JCheckBox antiTheft = new JCheckBox("D");    JCheckBox centralLock = new JCheckBox("E");

    frame.add(new JLabel("Car Features"));    frame.add(ac);    frame.add(cdPlayer);    frame.add(cruiseControl);    frame.add(keylessEntry);    frame.add(antiTheft);    frame.add(centralLock);    frame.pack();    frame.setVisible(true);  }}

// JCheckBoxItemListenerimport java.awt.Color;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;

import javax.swing.AbstractButton;import javax.swing.JCheckBox;import javax.swing.JFrame;

public class JCheckBoxItemListener { public static void main(String args[]) { JFrame frame = new JFrame("Iconizing CheckBox"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Page 8: A Visual Guide to Swing Components

JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust");

ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { AbstractButton abstractButton = (AbstractButton)itemEvent.getSource(); Color foreground = abstractButton.getForeground(); Color background = abstractButton.getBackground(); int state = itemEvent.getStateChange(); if (state == ItemEvent.SELECTED) { abstractButton.setForeground(background); abstractButton.setBackground(foreground); } } }; aCheckBox4.addItemListener(itemListener); frame.add(aCheckBox4); frame.setSize(300, 200); frame.setVisible(true); }}

//COMBO BOX:

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;

import javax.swing.JComboBox;import javax.swing.JFrame;

public class Main extends JFrame {  JComboBox combo = new JComboBox();

  public Main() {    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    combo.addItem("A");    combo.addItem("H");    combo.addItem("P");    combo.setEditable(true);    System.out.println("#items=" + combo.getItemCount());

    combo.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {        System.out.println("Selected index=" + combo.getSelectedIndex()            + " Selected item=" + combo.getSelectedItem());      }    });

    getContentPane().add(combo);    pack();    setVisible(true);

Page 9: A Visual Guide to Swing Components

  }

  public static void main(String arg[]) {    new Main();  }}

Creating JRadioButton Components

1. A JRadioButton represents a radio button. 2. You can use multiple JRadioButtons to represents a selection from which only one item can be selected. 3. To indicate a logical grouping of radio buttons, you use a javax.swing.ButtonGroup object.

4. To programmatically select a JRadioButton, you pass true to its setSelected method.public JRadioButton()JRadioButton aRadioButton = new JRadioButton();

public JRadioButton(Icon icon)JRadioButton aRadioButton = new JRadioButton(new DiamondIcon(Color.CYAN, false));aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));

public JRadioButton(Icon icon, boolean selected)JRadioButton aRadioButton = new JRadioButton(new DiamondIcon(Color.CYAN, false),  true);aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));

public JRadioButton(String text)JRadioButton aRadioButton = new JRadioButton("4 slices");

public JRadioButton(String text, boolean selected)JRadioButton aRadioButton = new JRadioButton("8 slices", true);

public JRadioButton(String text, Icon icon)JRadioButton aRadioButton = new JRadioButton("12 slices",  new DiamondIcon(Color.CYAN, aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));

public JRadioButton(String text, Icon icon, boolean selected)JRadioButton aRadioButton = new JRadioButton("16 slices",  new DiamondIcon(Color.CYAN, aRadioButton.setSelectedIcon(new DiamondIcon(Color.BLUE, true));

public JRadioButton(Action action)Action action = ...;JRadioButton aRadioButton = new JRadioButton(action);

import java.awt.FlowLayout;

import javax.swing.ButtonGroup;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JRadioButton;

public class Main {

Page 10: A Visual Guide to Swing Components

public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("JRadioButton Test"); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JRadioButton button1 = new JRadioButton("Red"); JRadioButton button2 = new JRadioButton("Green"); JRadioButton button3 = new JRadioButton("Blue"); ButtonGroup colorButtonGroup = new ButtonGroup(); colorButtonGroup.add(button1); colorButtonGroup.add(button2); colorButtonGroup.add(button3); button1.setSelected(true); frame.add(new JLabel("Color:")); frame.add(button1); frame.add(button2);

frame.add(button3); frame.pack(); frame.setVisible(true); }}

Listening to JRadioButton Events with an ActionListener

import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.AbstractButton;import javax.swing.ButtonGroup;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JRadioButton;

public class JRadioButtonActionListener {  public static void main(String args[]) {    JFrame frame = new JFrame("Grouping Example");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel(new GridLayout(0, 1));

Page 11: A Visual Guide to Swing Components

    ButtonGroup group = new ButtonGroup();    JRadioButton aRadioButton = new JRadioButton("A");    JRadioButton bRadioButton = new JRadioButton("B");

    ActionListener sliceActionListener = new ActionListener() {      public void actionPerformed(ActionEvent actionEvent) {        AbstractButton aButton = (AbstractButton) actionEvent.getSource();        System.out.println("Selected: " + aButton.getText());      }    };

    panel.add(aRadioButton);    group.add(aRadioButton);    panel.add(bRadioButton);    group.add(bRadioButton);

    aRadioButton.addActionListener(sliceActionListener);    bRadioButton.addActionListener(sliceActionListener);

    frame.add(panel);    frame.setSize(300, 200);    frame.setVisible(true);  }}

JList

The JList component is the basic Swing component for selecting one or more items from a set of choices. Three key elements and their implementations define the JList structure:

1. A data model for holding the JList data, as defined by the ListModel interface 2. A cell renderer for drawing the elements of the JList, as described by the ListCellRenderer interface

3. A selection model for selecting elements of the JList, as described by the ListSelectionModel interfacepublic JList()JList jlist = new JList();

public JList(Object listData[])String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H"};JList jlist = new JList(labels);

public JList(Vector listData)Vector vector = aBufferedImage.getSources();JList jlist = new JList(vector);

public JList(ListModel model)ResultSet results = aJDBCStatement.executeQuery("SELECT colName FROM tableName");DefaultListModel model = new DefaultListModel();while (result.next()){  model.addElement(result.getString(1));

Page 12: A Visual Guide to Swing Components

}  JList jlist = new JList(model);

//JlistTEst

import java.awt.FlowLayout;

import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JScrollPane;

public class JListTest {  public static void main(String[] args) {    JFrame.setDefaultLookAndFeelDecorated(true);    JFrame frame = new JFrame("JList Test");    frame.setLayout(new FlowLayout());    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    String[] selections = { "green", "red", "orange", "dark blue" };    JList list = new JList(selections);    list.setSelectedIndex(1);    System.out.println(list.getSelectedValue());    frame.add(new JScrollPane(list));    frame.pack();

    frame.setVisible(true);  }}

The JMenu component is the basic menu item container that is placed on a JMenuBar

1. In various places within the different menus, menu separators divide the options into logical sets. 2. Each of the menu options has a mnemonic associated with it to help with keyboard navigation and

selection. 3. The mnemonic allows users to make menu selections via the keyboard, for instance, by pressing Alt-F on

a Windows platform to open the File menu. 4. A keystroke associated with several options acts as a keyboard accelerator. Unlike the mnemonic, the

accelerator can directly activate a menu option, even when the menu option isn't visible.

5. The Options submenu has an icon associated with it.JMenu fileMenu = new JMenu("File");

JMenuItem newMenuItem = new JMenuItem("New");fileMenu.add(newMenuItem);

JMenuItem openMenuItem = new JMenuItem("Open");fileMenu.add(openMenuItem);

JMenuItem closeMenuItem = new JMenuItem("Close");fileMenu.add(closeMenuItem);fileMenu.addSeparator();

Page 13: A Visual Guide to Swing Components

JMenuItem saveMenuItem = new JMenuItem("Save");fileMenu.add(saveMenuItem);fileMenu.addSeparator();

JMenuItem exitMenuItem = new JMenuItem("Exit");fileMenu.add(exitMenuItem);

Insert them at specific positions or insert a separator at a specific positionpublic JMenuItem insert(JMenuItem menuItem, int pos);public JMenuItem insert(Action a, int pos);public void insertSeparator(int pos);

Adding a Menu to a Window

import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;

public class AddMenuBarToFrame extends JFrame {  private JMenuBar menuBar = new JMenuBar(); // Window menu bar  public AddMenuBarToFrame(String title) {    setTitle(title);    setDefaultCloseOperation(EXIT_ON_CLOSE);    setJMenuBar(menuBar); // Add the menu bar to the window    JMenu fileMenu = new JMenu("File"); // Create File menu    JMenu elementMenu = new JMenu("Elements"); // Create Elements menu    menuBar.add(fileMenu); // Add the file menu    menuBar.add(elementMenu); // Add the element menu  }  public static void main(String[] args) {    AddMenuBarToFrame window = new AddMenuBarToFrame("Sketcher");     window.setBounds(30, 30, 300, 300);

Page 14: A Visual Guide to Swing Components

    window.setVisible(true);  }}

/import java.awt.event.KeyEvent;

import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;

public class ContructMenuWithAction { public static void main(final String args[]) { JFrame frame = new JFrame("MenuSample Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar();

// File Menu, F - Mnemonic JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenu saveMenu = new JMenu("SAVE"); menuBar.add(saveMenu); fileMenu.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent e) { System.out.println("File Menu Changed");

} }); saveMenu.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent e) { System.out.println("SaveMenu Changed");

} }); // File->New, N - Mnemonic JMenuItem newMenuItem = new JMenuItem("New"); fileMenu.add(newMenuItem);

newMenuItem.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent e) { System.out.println("new menu item changed");

} });

frame.setJMenuBar(menuBar); frame.setSize(350, 250); frame.setVisible(true);

Page 15: A Visual Guide to Swing Components

}}

Using MenuListener to listen to: menu canceled, selected and deselected events

With a registered MenuListener, you're notified when a JMenu is selected before the pop-up menu is opened with the menu's choices.public interface MenuListener extends EventListener {  public void menuCanceled(MenuEvent e);  public void menuDeselected(MenuEvent e);  public void menuSelected(MenuEvent e);}

import java.awt.event.KeyEvent;

import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.event.MenuEvent;import javax.swing.event.MenuListener;

public class ContructMenuWithAction {  public static void main(final String args[]) {    JFrame frame = new JFrame("MenuSample Example");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    JMenuBar menuBar = new JMenuBar();

    // File Menu, F - Mnemonic    JMenu fileMenu = new JMenu("File");    fileMenu.setMnemonic(KeyEvent.VK_F);    menuBar.add(fileMenu);

    fileMenu.addMenuListener(new MenuListener() {

      public void menuSelected(MenuEvent e) {        System.out.println("menuSelected");

Page 16: A Visual Guide to Swing Components

      }

      public void menuDeselected(MenuEvent e) {        System.out.println("menuDeselected");

      }

      public void menuCanceled(MenuEvent e) {        System.out.println("menuCanceled");

      }    });

    // File->New, N - Mnemonic    JMenuItem newMenuItem = new JMenuItem("New");    fileMenu.add(newMenuItem);

    frame.setJMenuBar(menuBar);    frame.setSize(350, 250);    frame.setVisible(true);  }}

///SCROLL BAR

import java.awt.BorderLayout;

import javax.swing.BoundedRangeModel;import javax.swing.JFrame;import javax.swing.JScrollBar;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;

class BoundedChangeListener implements ChangeListener { public void stateChanged(ChangeEvent changeEvent) { Object source = changeEvent.getSource(); if (source instanceof BoundedRangeModel) { BoundedRangeModel aModel = (BoundedRangeModel) source; if (!aModel.getValueIsAdjusting()) { System.out.println("Changed: " + aModel.getValue()); } } else { System.out.println("Something changed: " + source); } }}

public class ScrollBarSample { public static void main(String args[]) { ChangeListener changeListener = new BoundedChangeListener(); JScrollBar aJScrollBar = new JScrollBar(JScrollBar.HORIZONTAL);

Page 17: A Visual Guide to Swing Components

BoundedRangeModel model = aJScrollBar.getModel(); model.addChangeListener(changeListener);

JFrame frame = new JFrame("ScrollBars R Us"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(aJScrollBar, BorderLayout.NORTH); frame.setSize(300, 200); frame.setVisible(true); }}

public JProgressBar()JProgressBar aJProgressBar = new JProgressBar();

public JProgressBar(int orientation)JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL);JProgressBar bJProgressBar = new JProgressBar(JProgressBar.HORIZONTAL);

public JProgressBar(int minimum, int maximum)JProgressBar aJProgressBar = new JProgressBar(0, 500);

public JProgressBar(int orientation, int minimum, int maximum)JProgressBar aJProgressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 1000);

public JProgressBar(BoundedRangeModel model)// Data model, initial value 0, range 0-250, and extent of 0DefaultBoundedRangeModel model = new DefaultBoundedRangeModel(0, 0, 0, 250);JProgressBar aJProgressBar = new JProgressBar(model);

import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JProgressBar;

public class JProgressBarSetValue extends JFrame { JProgressBar bar = new JProgressBar(); JButton step = new JButton("Step");

public JProgressBarSetValue() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); step.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int value = bar.getValue() + 7;

Page 18: A Visual Guide to Swing Components

if (value > bar.getMaximum()) { value = bar.getMaximum(); } bar.setValue(value); } });

getContentPane().add(bar, BorderLayout.NORTH); getContentPane().add(step, BorderLayout.EAST); pack(); setVisible(true); }

public static void main(String arg[]) { new JProgressBarSetValue(); }}

1.

// COLOR CHOOSER

import java.awt.BorderLayout;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.JButton;import javax.swing.JColorChooser;import javax.swing.JFrame;

public class ColorSample {  public static void main(String args[]) {    JFrame f = new JFrame("JColorChooser Sample");    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    final JButton button = new JButton("Pick to Change Background");

    ActionListener actionListener = new ActionListener() {      public void actionPerformed(ActionEvent actionEvent) {        Color initialBackground = button.getBackground();        Color background = JColorChooser.showDialog(null, "JColorChooser Sample", initialBackground);        if (background != null) {          button.setBackground(background);        }      }    };    button.addActionListener(actionListener);    f.add(button, BorderLayout.CENTER);    f.setSize(300, 200);    f.setVisible(true);

Page 19: A Visual Guide to Swing Components

  }}

JFileChooser

A JFileChooser is a dialog to select a file or files.The return value of the three methods is one of the following:

1. JFileChooser.CANCEL_OPTION, if the user clicks Cancel. 2. JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button.

3. JFileChooser.ERROR_OPTION, if the user closes the dialogA return value of JFileChooser.APPROVE_OPTION, indicates that you can call its getSelectedFile or getSelectedFiles methods:public java.io.File getSelectedFile ()public java.io.File[] getSelectedFiles ()

JFileChooser has supporting classes: FileFilter class, FileSystemView class, FileView.FileFilter class is for restricting files and directories to be listed in the FileView of the JFileChooser. The FileView controls how the directories and files are listed within the JFileChooser. The FileSystemView is an abstract class that tries to hide file system-related operating system specifics from the file chooser.import javax.swing.JFileChooser;import javax.swing.JFrame;

public class MainClass extends JFrame {  public MainClass() {    JFileChooser fileChooser = new JFileChooser();    fileChooser.setDialogTitle("Choose a file");    this.getContentPane().add(fileChooser);    fileChooser.setVisible(true);  }

  public static void main(String[] args) {    JFrame frame = new MainClass();    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.pack();    frame.setVisible(true);  }}