User Controls.stepInto()

The components we discuss in this section are commonly used controls that users need in applications. This is by no means an exhaustive look at the controls Swing makes available. It's just what you need to get started. Anyway, after you are used to working with a few of the controls, it is an easy step to read the API for what other kinds of components you get for free.

JLabel

This is an area. Just a plain area, corresponding to a label in Visual Basic. You can put text on it, which is its usual purpose. Or an image, which is probably a good idea to put there. Labels are just regular folk. Create them like this:

JLabel label = new JLabel("You must conform.");

The text passed to the constructor will show up on the label, and will be left-justified and centered vertically.

To create a label containing an image and text, you can follow this example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class LabelTest {
    public static void main(String[] args) {
        new LabelTest();
    }

    public LabelTest(){
        JFrame frame = new JFrame("Label Test");
      Container mainPanel = frame.getContentPane();

      mainPanel.add(getTitlePanel("My Label test
                text.", "/images/some.gif"));

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

  private JPanel getTitlePanel(String title,
                String imagePath){
      JPanel titlePanel = new JPanel(new
BorderLayout());

          //use the Dimension class to make a 2-D
          //size of width, height
      titlePanel.setPreferredSize(
                new Dimension(300, 100));

          //make it white instead of default gray
      titlePanel.setBackground(Color.WHITE);

          //the image
      JLabel lblImage = new JLabel();
          //get an image from the path specified
      ImageIcon ico = new ImageIcon(imagePath);
          //add the image to the label
      lblImage.setIcon(ico);

          //the text
      JLabel lblTitle = new JLabel();
          //set the font for the text
      lblTitle.setFont(new Font("SansSerif",
                 Font.BOLD, 18));
          //add the text to the label
      lblTitle.setText(title);

      //add the image to the panel
      titlePanel.add(lblImage, BorderLayout.WEST);
        //add the text to the panel
        titlePanel.add(lblTitle, BorderLayout.CENTER);

        return titlePanel;
    }
}

We will cover layouts, which are used above, later in this chapter. Otherwise, the code should be self explanatory. If the image is not found, then it simply won't appear.

JTextField

This control corresponds to an input control in HTML. Users enter text here, or you can cause it to have a default value when it is displayed by calling its setText(String s) method. Then, you can call the getText() method to retrieve its String value.

JButton

The JButton represents a clickable button that can have a text label, an image label, or both. The constructors follow:

  • JButton() Creates a button with no set text or icon.

  • JButton(String text) Creates a button with text label

  • JButton(Icon icon) Creates a button with an icon label.

  • JButton(String text, Icon icon) Creates a button with both text and icon.

  • JButton(Action a) Creates a button where properties are taken from the Action supplied.

Check out the following ButtonDemo class to see a JButton with a text label that has several properties set, and which performs an action when you click it.

ButtonDemo.java
package net.javagarage.demo.ui;
/**<p>
 * Demonstrates how to use a text field, a button,
 * and a label. When you enter text and click the
 * button, the label's text changes to your value.
 *
 * This example uses the default layout, which
 * is FlowLayout. We don't have to do anything
 * to make that work, and components will just
 * stack up after each other.
 * @author Eben Hewitt
 **/
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextField;

import java.awt.Color;

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

public class ButtonDemo extends JPanel
implements ActionListener {

protected JButton button;
protected JTextField txtField;
protected JLabel label;

public ButtonDemo() {
//creates the field to enter text
txtField = new JTextField();
//make the background yellow
txtField.setBackground(Color.YELLOW);
//will disappear if we don't do this
txtField.setColumns(25);
//creates the button object
button = new JButton("Change text");

//places text in the button
button.setVerticalTextPosition(AbstractButton.CENTER);

//this is left for locales that read left to right
button.setHorizontalTextPosition(AbstractButton.LEADING);

//change some frivolous things just to show
button.setBackground(new Color(80,80,80));
button.setForeground(Color.WHITE);
/*
 * it is sometimes desirable to allow the user to
 * type with the keyboard to fire an event, as
 * opposed to only allowing clicking. to do this, set
 * the mnemonic using the setMnemonic method.
 *
 * The arg to this method is a char, indicating the
 * character that will fire the event, often in
 * combination with the ALT key.
 *
 * it should be one of the characters in the label,
 * in which case it will appear underlined.
 *
 * See the KeyEvent API for pre-defined keys.
 * IE, we could use VirtualKey C,
 * which means ALT + C character.
 */

button.setMnemonic(KeyEvent.VK_C);
//inherited from AbstractButton
//this is what the event listener will pick up
button.setActionCommand("changeText");

//this is what makes the button do something
//when you click it. without registering
//and action listener, nothing will happen.
button.addActionListener(this);

//create the label whose text we'll change
label = new JLabel();
label.setText("This is the default text");


//Add the components to the container in order.
//since we're using FlowLayout, we don't need
//to do anything else
add(txtField);
add(button);
add(label);
}

//this is what happens when the button is
//clicked (or when ALT C is keyed)
public void actionPerformed(ActionEvent e) {
//we set the button's ActionCommand to this
if ("changeText".equals(e.getActionCommand())) {
//make the label value be whatever
//the user typed
label.setText(txtField.getText());
}
}

public static void main(String[] args) {
//the event-dispatching thread will show the app
//This method of running Swing apps is recommended
//by Sun
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
launch();
}
});
}

//sets up the look and feel, creates the frame,
//lines up the objects, and shows them.
private static void launch() {
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.
JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
ButtonDemo newContentPane = new ButtonDemo();
newContentPane.setOpaque(true);
              //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.
frame.pack();
frame.setVisible(true);
}
}
//end ButtonDemo

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.208.117