Java Swing Основные компоненты

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(нарушало авторские права)
 
Строка 1: Строка 1:
-
Swing components are basic building blocks of an application. Swing toolkit has a wide range of various widgets. Buttons, check boxes,sliders, list boxes etc. Everything a programmer needs for his job. In this section of the tutorial, we will describe several useful components.
 
-
== JLabel Component ==
 
-
 
-
<b> is a simple component for displaying text, images or both. It does not react to input events.
 
-
 
-
<source lang="java">
 
-
import java.awt.BorderLayout;
 
-
import java.awt.Color;
 
-
import java.awt.Dimension;
 
-
import java.awt.Font;
 
-
import java.awt.Toolkit;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JLabel;
 
-
import javax.swing.JPanel;
 
-
 
-
 
-
public class MyLabel extends JFrame {
 
-
 
-
  private Toolkit toolkit;
 
-
 
-
  public MyLabel() {
 
-
 
-
setTitle("No Sleep");
 
-
 
-
      String lyrics =  "&lt;html&gt;It's way too late to think of&lt;br&gt;" +
 
-
      "Someone I would call now&lt;br&gt;" +
 
-
      "And neon signs got tired&lt;br&gt;" +
 
-
      "Red eye flights help the stars out&lt;br&gt;" +
 
-
      "I'm safe in a corner&lt;br&gt;" +
 
-
      "Just hours before me&lt;br&gt;" +
 
-
      "&lt;br&gt;" +
 
-
      "I'm waking with the roaches&lt;br&gt;" +
 
-
      "The world has surrendered&lt;br&gt;" +
 
-
      "I'm dating ancient ghosts&lt;br&gt;" +
 
-
      "The ones I made friends with&lt;br&gt;" +
 
-
      "The comfort of fireflies&lt;br&gt;" +
 
-
      "Long gone before daylight&lt;br&gt;" +
 
-
      "&lt;br&gt;" +
 
-
      "And if I had one wishful field tonight&lt;br&gt;" +
 
-
      "I'd ask for the sun to never rise&lt;br&gt;" +
 
-
      "If God leant his voice for me to speak&lt;br&gt;" +
 
-
      "I'd say go to bed, world&lt;br&gt;" +
 
-
      "&lt;br&gt;" +
 
-
      "I've always been too late&lt;br&gt;" +
 
-
      "To see what's before me&lt;br&gt;" +
 
-
      "And I know nothing sweeter than&lt;br&gt;" +
 
-
      "Champaign from last New Years&lt;br&gt;" +
 
-
      "Sweet music in my ears&lt;br&gt;" +
 
-
      "And a night full of no fears&lt;br&gt;" +
 
-
      "&lt;br&gt;" +
 
-
      "But if I had one wishful field tonight&lt;br&gt;" +
 
-
      "I'd ask for the sun to never rise&lt;br&gt;" +
 
-
      "If God passed a mic to me to speak&lt;br&gt;" +
 
-
      "I'd say stay in bed, world&lt;br&gt;" +
 
-
      "Sleep in peace&lt;/html&gt;";
 
-
 
-
      JPanel panel = new JPanel();
 
-
      panel.setLayout(new BorderLayout(10, 10));
 
-
 
-
      JLabel label = new JLabel(lyrics);
 
-
      label.setFont(new Font("Georgia", Font.PLAIN, 14));
 
-
      label.setForeground(new Color(50, 50, 25));
 
-
 
-
 
-
      panel.add(label, BorderLayout.CENTER);
 
-
      panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
 
-
      add(panel);
 
-
      pack();
 
-
 
-
      toolkit = getToolkit();
 
-
      Dimension screensize = toolkit.getScreenSize();
 
-
      setLocation((screensize.width - getWidth())/2,
 
-
          (screensize.height - getHeight())/2);
 
-
      setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
 
-
      MyLabel mylabel = new MyLabel();
 
-
      mylabel.setVisible(true);
 
-
 
-
  }
 
-
}
 
-
 
-
</source>
 
-
 
-
In our example, we show lyrics of no sleep song from cardigans. We can use html tags in <b> component. We use the &lt;br&gt; tag to separate lines.
 
-
 
-
<source lang="java">
 
-
JPanel panel = new JPanel();
 
-
panel.setLayout(new BorderLayout(10, 10));
 
-
</source>
 
-
 
-
We create a panel and set a <b> manager.
 
-
 
-
<source lang="java">
 
-
JLabel label = new JLabel(lyrics);
 
-
label.setFont(new Font("Georgia", Font.PLAIN, 14));
 
-
label.setForeground(new Color(50, 50, 25));
 
-
</source>
 
-
 
-
Here we create the label component. We set it's font to plain georgia, 14 px tall. We also change the foreground color.
 
-
 
-
<source lang="java">
 
-
panel.add(label, BorderLayout.CENTER);
 
-
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
 
-
</source>
 
-
 
-
We put the label into the center of the panel. We put 10px around the label.
 
-
 
-
<source lang="java">
 
-
add(panel);
 
-
pack();
 
-
</source>
 
-
 
-
The panel is added to the frame component. We call the <b> method, which will resize the window, so that all components are visible.
 
-
 
-
[[image: java_swing_nosleep.jpg | center]]
 
-
 
-
== JCheckBox ==
 
-
 
-
JCheckBox is a widget that has two states. On and Off. It is a box with a label.  If the checkbox is checked, it is represented by a tick in a box. A checkbox can be used to show/hide splashscreen at startup, toggle visibility of a toolbar etc.
 
-
 
-
<source lang="java">
 
-
 
-
import java.awt.Dimension;
 
-
import java.awt.event.ActionEvent;
 
-
import java.awt.event.ActionListener;
 
-
 
-
import javax.swing.Box;
 
-
import javax.swing.BoxLayout;
 
-
import javax.swing.JCheckBox;
 
-
import javax.swing.JFrame;
 
-
 
-
 
-
public class CheckBox extends JFrame implements ActionListener {
 
-
 
-
  public CheckBox() {
 
-
 
-
      setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
 
-
      add(Box.createRigidArea(new Dimension(15, 20)));
 
-
 
-
      JCheckBox checkbox = new JCheckBox("Show Title", true);
 
-
      checkbox.setFocusable(false);
 
-
      checkbox.addActionListener(this);
 
-
      add(checkbox);
 
-
 
-
      setSize(280, 200);
 
-
      setTitle("CheckBox example");
 
-
      setLocationRelativeTo(null);
 
-
      setResizable(false);
 
-
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
-
      setVisible(true);
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
 
-
      new CheckBox();
 
-
 
-
  }
 
-
 
-
 
-
  public void actionPerformed(ActionEvent e) {
 
-
      if (this.getTitle() == "") {
 
-
          this.setTitle("Checkbox example");
 
-
      } else {
 
-
          this.setTitle("");
 
-
      }
 
-
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
Our code example shows or hides the title of the window depending on it's state.
 
-
 
-
<source lang="java">
 
-
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
 
-
add(Box.createRigidArea(new Dimension(15, 20)));
 
-
</source>
 
-
 
-
In this example, we use a <b> layout manager. We put some space there, so that the checkbox is not too close to the corner.
 
-
 
-
<source lang="java">
 
-
JCheckBox checkbox = new JCheckBox("Show Title", true);
 
-
</source>
 
-
 
-
Here we have a constructor for the checkbox. We provide text and state.
 
-
 
-
<source lang="java">
 
-
checkbox.setFocusable(false);
 
-
</source>
 
-
 
-
We have disabled the focus for the checkbox. The rectangle around the text looks ugly, so we go without the focus.
 
-
 
-
<source lang="java">
 
-
if (this.getTitle() == "") {
 
-
    this.setTitle("Checkbox example");
 
-
} else {
 
-
    this.setTitle("");
 
-
}
 
-
</source>
 
-
 
-
Here we toggle the title of the window.
 
-
 
-
 
-
[[image: java_swing_checkbox.jpg | center]]
 
-
 
-
== JSlider ==
 
-
 
-
JSlider is a component that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a volume control.
 
-
 
-
<source lang="java">
 
-
import java.awt.BorderLayout;
 
-
import java.awt.Dimension;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.Box;
 
-
import javax.swing.BoxLayout;
 
-
import javax.swing.ImageIcon;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JLabel;
 
-
import javax.swing.JPanel;
 
-
import javax.swing.JSlider;
 
-
import javax.swing.event.ChangeEvent;
 
-
import javax.swing.event.ChangeListener;
 
-
 
-
 
-
public class Slider extends JFrame {
 
-
 
-
  private JSlider slider;
 
-
  private JLabel label;
 
-
 
-
  ImageIcon mute = new ImageIcon(ClassLoader.getSystemResource("mute.png"));
 
-
  ImageIcon min = new ImageIcon(ClassLoader.getSystemResource("min.png"));
 
-
  ImageIcon med = new ImageIcon(ClassLoader.getSystemResource("med.png"));
 
-
  ImageIcon max = new ImageIcon(ClassLoader.getSystemResource("max.png"));
 
-
 
-
  public Slider() {
 
-
 
-
      setTitle("JSlider");
 
-
      setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
      JPanel panel = new JPanel();
 
-
      panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
 
-
      panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
 
-
      setLayout(new BorderLayout());
 
-
 
-
      panel.add(Box.createHorizontalGlue());
 
-
      slider = new JSlider(0, 150, 0);
 
-
 
-
      slider.setPreferredSize(new Dimension(150, 30));
 
-
 
-
      slider.addChangeListener(new ChangeListener() {
 
-
          public void stateChanged(ChangeEvent event) {
 
-
              int value = slider.getValue();
 
-
              if (value == 0) {
 
-
                  label.setIcon(mute);
 
-
              } else if (value > 0 && value <= 30) {
 
-
                  label.setIcon(min);
 
-
              } else if (value > 30 && value < 80) {
 
-
                  label.setIcon(med);
 
-
              } else {
 
-
                  label.setIcon(max);
 
-
              }
 
-
          }
 
-
      });
 
-
 
-
      panel.add(slider);
 
-
      panel.add(Box.createRigidArea(new Dimension(5, 0)));
 
-
 
-
      label = new JLabel(mute, JLabel.CENTER);
 
-
      panel.add(label);
 
-
      panel.add(Box.createHorizontalGlue());
 
-
      add(panel, BorderLayout.CENTER);
 
-
 
-
      pack();
 
-
      setLocationRelativeTo(null);
 
-
 
-
  }
 
-
 
-
 
-
  public static void main(String[] args) {
 
-
 
-
      Slider button = new Slider();
 
-
      button.setVisible(true);
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
In the code example, we show a <b>. By dragging the slider, we change the icon on the label component.
 
-
 
-
<source lang="java">
 
-
ImageIcon mute = new ImageIcon(ClassLoader.getSystemResource("mute.png"));
 
-
</source>
 
-
 
-
Here we create an image icon.
 
-
 
-
<source lang="java">
 
-
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
 
-
</source>
 
-
 
-
Panel component has a horizontal <b>.
 
-
 
-
<source lang="java">
 
-
panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
 
-
 
-
</source>
 
-
 
-
We creare a 40px border around the panel.
 
-
 
-
<source lang="java">
 
-
panel.add(Box.createHorizontalGlue());
 
-
</source>
 
-
 
-
We put resizable space to bo both sides, left and right. It is to prevent <b> from growing to unnatural sizes.
 
-
 
-
<source lang="java">
 
-
slider = new JSlider(0, 150, 0);
 
-
</source>
 
-
 
-
This is a <b> constructor. The parameters are minimum value, maximum value and current value.
 
-
 
-
<source lang="java">
 
-
slider.addChangeListener(new ChangeListener() {
 
-
...
 
-
});
 
-
</source>
 
-
 
-
We add a <b> to the slider. Inside the listener, we determine the current slider value and update the label accordingly.
 
-
 
-
<source lang="java">
 
-
panel.add(Box.createRigidArea(new Dimension(5, 0)));
 
-
</source>
 
-
 
-
We place a 5px rigid space between the two components. They are too close to each other, when the slider is at the end position.
 
-
 
-
[[image: java_swing_slider.jpg | center]]
 
-
 
-
== JComboBox ==
 
-
 
-
Combobox is a component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.
 
-
 
-
<source lang="java">
 
-
import java.awt.Component;
 
-
import java.awt.Dimension;
 
-
import java.awt.event.ActionEvent;
 
-
import java.awt.event.ActionListener;
 
-
import java.awt.event.ItemEvent;
 
-
import java.awt.event.ItemListener;
 
-
 
-
import javax.swing.Box;
 
-
import javax.swing.BoxLayout;
 
-
import javax.swing.ImageIcon;
 
-
import javax.swing.JButton;
 
-
import javax.swing.JComboBox;
 
-
import javax.swing.JDialog;
 
-
import javax.swing.JLabel;
 
-
import javax.swing.border.LineBorder;
 
-
 
-
 
-
public class ComboBox extends JDialog implements
 
-
ActionListener, ItemListener {
 
-
 
-
  final String[] authors = {
 
-
"Leo Tolstoy", "John Galsworthy",
 
-
      "Honore de Balzac", "Stefan Zweig",
 
-
"Boris Pasternak", "Tom Wolfe"
 
-
  };
 
-
 
-
  final String[] images = {
 
-
"tolstoy.jpg", "galsworthy.jpg", "balzac.jpg",
 
-
      "zweig.jpg", "pasternak.jpg", "wolfe.jpg"
 
-
  };
 
-
 
-
  private JLabel display = null; 
 
-
  private JComboBox combobox = null;
 
-
  private JButton button = null;
 
-
 
-
  ImageIcon icon = new ImageIcon(
 
-
ClassLoader.getSystemResource("balzac.jpg"));
 
-
 
-
  public ComboBox() {
 
-
 
-
      setLayout(new BoxLayout(getContentPane(),
 
-
BoxLayout.Y_AXIS));
 
-
      add(Box.createRigidArea(new Dimension(0, 35)));
 
-
 
-
      display = new JLabel();
 
-
      display.setPreferredSize(new Dimension(100, 127));
 
-
      display.setMaximumSize(new Dimension(100, 127));
 
-
      display.setAlignmentX(Component.CENTER_ALIGNMENT);
 
-
      display.setBorder(LineBorder.createGrayLineBorder());
 
-
      add(display);
 
-
 
-
      add(Box.createRigidArea(new Dimension(0, 15)));
 
-
 
-
      combobox = new JComboBox(authors);
 
-
      combobox.setSelectedIndex(-1);
 
-
      combobox.setPreferredSize(new Dimension(140, 22));
 
-
      combobox.setMaximumSize(new Dimension(140, 22));
 
-
      combobox.addItemListener(this);
 
-
      add(combobox);
 
-
 
-
      add(Box.createRigidArea(new Dimension(0, 15)));
 
-
 
-
      button = new JButton("Close");
 
-
      button.setAlignmentX(Component.CENTER_ALIGNMENT);
 
-
      button.addActionListener(this);
 
-
      add(button);
 
-
 
-
      setTitle("JComboBox");
 
-
      setSize(300, 300);
 
-
      setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
 
-
      setLocationRelativeTo(null);
 
-
      setVisible(true);
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
      new ComboBox();
 
-
  }
 
-
 
-
 
-
  public void actionPerformed(ActionEvent e) {
 
-
      System.exit(0);
 
-
  }
 
-
 
-
  public void itemStateChanged(ItemEvent e) {
 
-
 
-
      if (e.getStateChange() == ItemEvent.SELECTED) {
 
-
          JComboBox combo = (JComboBox) e.getSource();
 
-
          int index = combo.getSelectedIndex();
 
-
          display.setIcon(new ImageIcon(
 
-
              ClassLoader.getSystemResource(images[index])));
 
-
      }
 
-
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
In our example, we have three components. A label, a combobox and a button. The button closes the window. We have six names of famous novelists in our combobox. If we select a name, an image is displayed in the label.
 
-
 
-
<source lang="java">
 
-
public class ComboBox extends JDialog implements
 
-
ActionListener, ItemListener {
 
-
</source>
 
-
 
-
This is a dialog based application example.
 
-
 
-
<source lang="java">
 
-
display = new JLabel();
 
-
</source>
 
-
 
-
The display area is a simple <b>.
 
-
 
-
<source lang="java">
 
-
combobox = new JComboBox(authors);
 
-
combobox.setSelectedIndex(-1);
 
-
</source>
 
-
 
-
The constructor of the <b> method, no item to be selected.
 
-
 
-
<source lang="java">
 
-
combobox.addItemListener(this);
 
-
</source>
 
-
 
-
We add an <b> to our combobox. In the event handler, we get the selected index of the combobox and set an appropriate icon for the label. The selected item is an index to the array of images.
 
-
 
-
<source lang="java">
 
-
 
-
</source>
 
-
 
-
[[image: java_swing_combobox.jpg | center]]
 
-
 
-
== JProgressBar ==
 
-
 
-
A progress bar is a widget that is used, when we process lengthy tasks. It is animated so that the user knows, that our task is progressing. The <b> widget provides a horizontal or vertical progress bar.
 
-
The initial and minimum values are 0, and the maximum is 100.
 
-
 
-
<source lang="java">
 
-
import java.awt.Dimension;
 
-
import java.awt.event.ActionEvent;
 
-
import java.awt.event.ActionListener;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.Box;
 
-
import javax.swing.BoxLayout;
 
-
import javax.swing.JButton;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JPanel;
 
-
import javax.swing.JProgressBar;
 
-
import javax.swing.Timer;
 
-
 
-
 
-
public class ProgressBar extends JFrame {
 
-
 
-
  ActionListener updateProBar;
 
-
  Timer timer;
 
-
  JProgressBar progressBar;
 
-
  JButton button;
 
-
 
-
  public ProgressBar() {
 
-
 
-
      setTitle("JProgressBar");
 
-
 
-
      JPanel panel = new JPanel();
 
-
      panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
 
-
      panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
 
-
 
-
 
-
 
-
      progressBar = new JProgressBar();
 
-
 
-
      progressBar.setMaximumSize(new Dimension(150, 20));
 
-
      progressBar.setMinimumSize(new Dimension(150, 20));
 
-
      progressBar.setPreferredSize(new Dimension(150, 20));
 
-
 
-
      progressBar.setAlignmentX(0f);
 
-
 
-
      panel.add(progressBar);
 
-
      panel.add(Box.createRigidArea(new Dimension(0, 20)));
 
-
 
-
      button = new JButton("Start");
 
-
      button.setFocusable(false);
 
-
      button.setMaximumSize(button.getPreferredSize());
 
-
 
-
      updateProBar = new ActionListener() {
 
-
          public void actionPerformed(ActionEvent actionEvent) {
 
-
              int val = progressBar.getValue();
 
-
              if (val >= 100) {
 
-
                  timer.stop();
 
-
                  button.setText("End");
 
-
                  return;
 
-
              }
 
-
 
-
              progressBar.setValue(++val);
 
-
          }
 
-
      };
 
-
 
-
      timer = new Timer(50, updateProBar);
 
-
 
-
      button.addActionListener(new ActionListener() {
 
-
          public void actionPerformed(ActionEvent e) {
 
-
              if (timer.isRunning()) {
 
-
                  timer.stop();
 
-
                  button.setText("Start");
 
-
 
-
              } else if (button.getText() != "End") {
 
-
                  timer.start();
 
-
                  button.setText("Stop");
 
-
              }
 
-
 
-
          }
 
-
      });
 
-
 
-
 
-
      panel.add(button);
 
-
      add(panel);
 
-
 
-
      pack();
 
-
      setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
      setResizable(false);
 
-
      setLocationRelativeTo(null);
 
-
      setVisible(true);
 
-
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
 
-
      new ProgressBar();
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
The example displays a progress bar and a button. The button starts and stops the progress.
 
-
 
-
<source lang="java">
 
-
progressBar = new JProgressBar();
 
-
</source>
 
-
 
-
Here we create the <b>. The minimum value is 0, maximum 100 and the initial value is 0. These are the default values.
 
-
 
-
<source lang="java">
 
-
progressBar.setMaximumSize(new Dimension(150, 20));
 
-
progressBar.setMinimumSize(new Dimension(150, 20));
 
-
progressBar.setPreferredSize(new Dimension(150, 20));
 
-
 
-
</source>
 
-
 
-
These lines are for design purposes only. I want my examples to look nice. The default height on my box was only 14px which looked bad.
 
-
 
-
<source lang="java">
 
-
progressBar.setAlignmentX(0f);
 
-
</source>
 
-
 
-
This line aligns both progress bar with the button. To the left.
 
-
 
-
<source lang="java">
 
-
 
-
panel.add(Box.createRigidArea(new Dimension(0, 20)));
 
-
</source>
 
-
 
-
Here we put some rigid space between the two components.
 
-
 
-
<source lang="java">
 
-
button.setFocusable(false);
 
-
</source>
 
-
 
-
Focus looks bad, better disable it.
 
-
 
-
<source lang="java">
 
-
timer = new Timer(50, updateProBar);
 
-
</source>
 
-
 
-
The timer object launches updateProBar listener every 50ms. Inside that listener,  we check, if the progress bar reached the value 100 and stop the timer, or update the progress bar.
 
-
 
-
<source lang="java">
 
-
if (timer.isRunning()) {
 
-
    timer.stop();
 
-
    button.setText("Start");
 
-
 
-
} else if (button.getText() != "End") {
 
-
    timer.start();
 
-
    button.setText("Stop");
 
-
}
 
-
</source>
 
-
 
-
Clicking on the button starts or stops the progress. The text of the button is updated dynamically. It can have Start, Stop or End String values.
 
-
 
-
[[image: java_swing_progressbar.jpg | center]]
 
-
 
-
== JToggleButton ==
 
-
 
-
<b> is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well.
 
-
 
-
<source lang="java">
 
-
 
-
import java.awt.Color;
 
-
import java.awt.Dimension;
 
-
import java.awt.event.ActionEvent;
 
-
import java.awt.event.ActionListener;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.Box;
 
-
import javax.swing.BoxLayout;
 
-
import javax.swing.JDialog;
 
-
import javax.swing.JPanel;
 
-
import javax.swing.JToggleButton;
 
-
import javax.swing.border.LineBorder;
 
-
 
-
 
-
public class ToggleButton extends JDialog implements ActionListener {
 
-
 
-
  private JToggleButton red;
 
-
  private JToggleButton green;
 
-
  private JToggleButton blue;
 
-
  private JPanel display;
 
-
 
-
  public ToggleButton() {
 
-
 
-
      setTitle("JToggleButton");
 
-
 
-
      JPanel bottom = new JPanel();
 
-
      bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
 
-
      bottom.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
 
-
 
-
      JPanel leftPanel = new JPanel();
 
-
      leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
 
-
 
-
      red = new JToggleButton("red");
 
-
      red.addActionListener(this);
 
-
 
-
      green = new JToggleButton("green");
 
-
      green.addActionListener(this);
 
-
 
-
      blue = new JToggleButton("blue");
 
-
      blue.addActionListener(this);
 
-
 
-
      blue.setMaximumSize(green.getMaximumSize());
 
-
      red.setMaximumSize(green.getMaximumSize());
 
-
 
-
      leftPanel.add(red);
 
-
      leftPanel.add(Box.createRigidArea(new Dimension(25, 7)));
 
-
      leftPanel.add(green);
 
-
      leftPanel.add(Box.createRigidArea(new Dimension(25, 7)));
 
-
      leftPanel.add(blue);
 
-
 
-
 
-
      bottom.add(leftPanel);
 
-
      bottom.add(Box.createRigidArea(new Dimension(20, 0)));
 
-
 
-
      display = new JPanel();
 
-
      display.setPreferredSize(new Dimension(110, 110));
 
-
      display.setBorder(LineBorder.createGrayLineBorder());
 
-
      display.setBackground(Color.black);   
 
-
 
-
      bottom.add(display);
 
-
      add(bottom);
 
-
 
-
      pack();
 
-
      setResizable(false);
 
-
      setLocationRelativeTo(null);
 
-
      setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
 
-
      setVisible(true);
 
-
  }
 
-
 
-
 
-
 
-
  public static void main(String[] args) {
 
-
      new ToggleButton();   
 
-
  }
 
-
 
-
  public void actionPerformed(ActionEvent e) {
 
-
 
-
      Color color = display.getBackground();
 
-
      int red = color.getRed();
 
-
      int green = color.getGreen();
 
-
      int blue = color.getBlue();
 
-
 
-
      if (e.getActionCommand() == "red") {
 
-
          if (red == 0) {
 
-
              red = 255; 
 
-
          } else {
 
-
              red = 0;
 
-
          }
 
-
      }
 
-
 
-
      if (e.getActionCommand() == "green") {
 
-
          if (green == 0) {
 
-
              green = 255; 
 
-
          } else {
 
-
              green = 0;
 
-
          }
 
-
      }
 
-
 
-
      if (e.getActionCommand() == "blue") {
 
-
          if (blue == 0) {
 
-
              blue = 255; 
 
-
          } else {
 
-
              blue = 0;
 
-
          }
 
-
      }
 
-
 
-
      Color setCol = new Color(red, green, blue);
 
-
      display.setBackground(setCol);
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
The example has three panels and three toggle buttons. Panels are bottom panel, left panel and display panel. The bottom panel is use to organize the left and display panels. For this, we use horizontal <b>BoxLayout</b> manager.
 
-
The left panel will holt three toggle buttons. This time we use vertical <b>BoxLayout</b> manager.
 
-
We set the background color of the display panel to black. The toggle buttons will toggle the red, green and blue parts of the color value. The background color will depend on which togglebuttons we have pressed.
 
-
 
-
<source lang="java">
 
-
red = new JToggleButton("red");
 
-
red.addActionListener(this);
 
-
 
-
</source>
 
-
 
-
Here we create a toggle button and set an action listener to it.
 
-
 
-
<source lang="java">
 
-
blue.setMaximumSize(green.getMaximumSize());
 
-
red.setMaximumSize(green.getMaximumSize());
 
-
</source>
 
-
 
-
We make all three buttons of equal size.
 
-
 
-
 
-
<source lang="java">
 
-
 
-
Color color = display.getBackground();
 
-
int red = color.getRed();
 
-
int green = color.getGreen();
 
-
int blue = color.getBlue();
 
-
</source>
 
-
 
-
In the <b>actionPerformed</b> method, we determine the current red, green, blue parts of the
 
-
display background color.
 
-
 
-
<source lang="java">
 
-
if (e.getActionCommand() == "red") {
 
-
    if (red == 0) {
 
-
        red = 255; 
 
-
    } else {
 
-
      red = 0;
 
-
    }
 
-
}
 
-
</source>
 
-
 
-
We determine, which button was toggled, and update the color part of the RGB value accordingly.
 
-
 
-
<source lang="java">
 
-
Color setCol = new Color(red, green, blue);
 
-
display.setBackground(setCol);
 
-
</source>
 
-
 
-
Here a new color is created and the display panel is updated to a new color.
 
-
 
-
[[image: java_swing_togglebutton.jpg | center]]
 
-
 
-
== JList Component ==
 
-
 
-
<b>JList</b> is a  component that displays a list of objects. It allows the user to select one or more items.
 
-
 
-
<source lang="java">
 
-
import java.awt.BorderLayout;
 
-
import java.awt.Dimension;
 
-
import java.awt.Font;
 
-
import java.awt.GraphicsEnvironment;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JLabel;
 
-
import javax.swing.JList;
 
-
import javax.swing.JPanel;
 
-
import javax.swing.JScrollPane;
 
-
import javax.swing.UIManager;
 
-
import javax.swing.event.ListSelectionEvent;
 
-
import javax.swing.event.ListSelectionListener;
 
-
 
-
 
-
public class List extends JFrame {
 
-
 
-
  private JLabel label;
 
-
  private JList list;
 
-
 
-
 
-
  public List() {
 
-
 
-
      setTitle("List");
 
-
      setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
      JPanel panel = new JPanel();
 
-
      panel.setLayout(new BorderLayout());
 
-
      panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
 
-
 
-
      GraphicsEnvironment ge =
 
-
          GraphicsEnvironment.getLocalGraphicsEnvironment();
 
-
 
-
      String[] fonts = ge.getAvailableFontFamilyNames();
 
-
 
-
      list = new JList(fonts);
 
-
      list.addListSelectionListener(new ListSelectionListener() {
 
-
          public void valueChanged(ListSelectionEvent e) {
 
-
              if (!e.getValueIsAdjusting()) {
 
-
                  String name = (String) list.getSelectedValue();
 
-
                  Font font = new Font(name, Font.PLAIN, 12);
 
-
                  label.setFont(font);
 
-
              }
 
-
          }
 
-
      });
 
-
 
-
      JScrollPane pane = new JScrollPane();
 
-
      pane.getViewport().add(list);
 
-
      pane.setPreferredSize(new Dimension(250, 200));
 
-
      panel.add(pane);
 
-
 
-
      label = new JLabel("Aguirre, der Zorn Gottes");
 
-
      label.setFont(new Font("Serif", Font.PLAIN, 12));
 
-
      add(label, BorderLayout.SOUTH);
 
-
 
-
 
-
      add(panel);
 
-
 
-
      pack();
 
-
      setLocationRelativeTo(null);
 
-
      setVisible(true);
 
-
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
      new List();
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
In our example, we will display a <b>JLabel</b> components. The list component contains a list of all available font family names on our system.
 
-
If we select an item from the list, the label will be displayed in a font, we have chosen.
 
-
 
-
<source lang="java">
 
-
GraphicsEnvironment ge =
 
-
    GraphicsEnvironment.getLocalGraphicsEnvironment();
 
-
 
-
String[] fonts = ge.getAvailableFontFamilyNames();
 
-
</source>
 
-
 
-
Here we obtain all possible font family names on our system.
 
-
 
-
<source lang="java">
 
-
list = new JList(fonts);
 
-
</source>
 
-
 
-
We create a <b>JList</b> component.
 
-
 
-
<source lang="java">
 
-
public void valueChanged(ListSelectionEvent e) {
 
-
    if (!e.getValueIsAdjusting()) {
 
-
</source>
 
-
 
-
This code is quite confusing. Events in list selection are grouped. We receive events for both selecting and deselecting.
 
-
To filter only the selecting events, we use the <b>getValueIsAdjusting()</b> method. Why this weird name? No idea.
 
-
 
-
<source lang="java">
 
-
String name = (String) list.getSelectedValue();
 
-
Font font = new Font(name, Font.PLAIN, 12);
 
-
label.setFont(font);
 
-
</source>
 
-
 
-
We get the selected item and set a new font for the label.
 
-
 
-
<source lang="java">
 
-
JScrollPane pane = new JScrollPane();
 
-
pane.getViewport().add(list);
 
-
</source>
 
-
 
-
Interesingly, JLabel component is not scrollable by default. We must put the list into the JScrollPane to make it scrollable.
 
-
 
-
[[image: java_swing_list.jpg | center]]
 
-
 
-
== JTextArea component ==
 
-
 
-
A <b>JScrollPane</b> component.
 
-
 
-
<source lang="java">
 
-
import java.awt.BorderLayout;
 
-
import java.awt.Dimension;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JPanel;
 
-
import javax.swing.JScrollPane;
 
-
import javax.swing.JTextArea;
 
-
 
-
 
-
public class TextArea extends JFrame {
 
-
 
-
  public TextArea() {
 
-
 
-
      setTitle("JTextArea");
 
-
      setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
      JPanel panel = new JPanel();
 
-
      panel.setLayout(new BorderLayout());
 
-
      panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
 
-
 
-
      JScrollPane pane = new JScrollPane();
 
-
      JTextArea area = new JTextArea();
 
-
 
-
      area.setLineWrap(true);
 
-
      area.setWrapStyleWord(true);
 
-
      area.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
 
-
 
-
      pane.getViewport().add(area);
 
-
      panel.add(pane);
 
-
 
-
      add(panel);
 
-
      setSize(new Dimension(350, 300));
 
-
 
-
      setLocationRelativeTo(null);
 
-
      setVisible(true);
 
-
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
 
-
      new TextArea();
 
-
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
The example shows a simple <b>JTextArea</b> component with an excerpt from Martin Luther King speech.
 
-
 
-
<source lang="java">
 
-
JTextArea area = new JTextArea();
 
-
 
-
</source>
 
-
 
-
This is the constructor of the <b>JTextArea</b> component.
 
-
 
-
<source lang="java">
 
-
area.setLineWrap(true);
 
-
</source>
 
-
 
-
Make the lines wrapped, if they are too long to fit the width.
 
-
 
-
<source lang="java">
 
-
area.setWrapStyleWord(true);
 
-
</source>
 
-
 
-
Here we specify, how is line going to be wrapped. In our case, lines will be wrapped at word boundaries, whitespaces.
 
-
 
-
<source lang="java">
 
-
area.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
 
-
</source>
 
-
 
-
We put some border around the text in the component.
 
-
 
-
<source lang="java">
 
-
pane.getViewport().add(area);
 
-
</source>
 
-
 
-
To make the text scrollable, we put the <b>JScrollPane</b> component.
 
-
 
-
[[image: java_swing_textarea.jpg | center]]
 
-
 
-
== JTextPane component ==
 
-
 
-
<b>JTextPane</b> component is a more advanced component for working with text. The component can do some complex formatting operations over the text. It can display also html documents.
 
-
 
-
<source lang="java">
 
-
 
-
import java.awt.BorderLayout;
 
-
import java.awt.Dimension;
 
-
 
-
import java.io.IOException;
 
-
 
-
import javax.swing.BorderFactory;
 
-
import javax.swing.JFrame;
 
-
import javax.swing.JPanel;
 
-
import javax.swing.JScrollPane;
 
-
import javax.swing.JTextPane;
 
-
 
-
 
-
public class TextPane extends JFrame {
 
-
 
-
  public TextPane() {
 
-
 
-
      setTitle("JTexPane");
 
-
      setDefaultCloseOperation(EXIT_ON_CLOSE);
 
-
 
-
      JPanel panel = new JPanel();
 
-
      panel.setLayout(new BorderLayout());
 
-
      panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
 
-
 
-
      JScrollPane pane = new JScrollPane();
 
-
      JTextPane textpane = new JTextPane();
 
-
 
-
      textpane.setContentType("text/html");
 
-
      textpane.setEditable(false);
 
-
 
-
      String cd = System.getProperty("user.dir") + "/";
 
-
 
-
      try {
 
-
          textpane.setPage("File:///" + cd + "test.html");
 
-
      } catch (IOException e) {
 
-
          System.out.println("Exception: " + e);
 
-
      }
 
-
 
-
      textpane.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
 
-
 
-
      pane.getViewport().add(textpane);
 
-
      panel.add(pane);
 
-
 
-
      add(panel);
 
-
      setSize(new Dimension(380, 320));
 
-
 
-
      setLocationRelativeTo(null);
 
-
      setVisible(true);
 
-
 
-
  }
 
-
 
-
  public static void main(String[] args) {
 
-
 
-
      new TextPane();   
 
-
 
-
  }
 
-
}
 
-
</source>
 
-
 
-
This is the html code, that we are loading into the <b>JTextPane</b> component. The component does not
 
-
handle scrolling.
 
-
 
-
<source lang="java">
 
-
&lt;html&gt;
 
-
&lt;head&gt;
 
-
&lt;title&gt;A simple html document&lt;/title&gt;
 
-
 
-
&lt;/head&gt;
 
-
&lt;body&gt;
 
-
 
-
&lt;h2&gt;A simple html document&lt;/h2&gt;
 
-
 
-
 
-
&lt;p&gt;
 
-
&lt;b&gt;JTextPane&lt;/b&gt; can display html documents.
 
-
 
-
&lt;/p&gt;
 
-
 
-
&lt;br&gt;
 
-
 
-
&lt;pre&gt;
 
-
JScrollPane pane = new JScrollPane();
 
-
JTextPane textpane = new JTextPane();
 
-
 
-
textpane.setContentType("text/html");
 
-
textpane.setEditable(false);
 
-
&lt;/pre&gt;
 
-
 
-
&lt;br&gt;
 
-
&lt;small&gt;The Java Swing tutorial, 2007&lt;/small&gt;
 
-
 
-
&lt;/body&gt;
 
-
 
-
&lt;/html&gt;
 
-
</source>
 
-
 
-
In our example we show a <b>JTextPane</b> component and load a html document. Example shows formatting capabilities of the component.
 
-
 
-
<source lang="java">
 
-
 
-
JTextPane textpane = new JTextPane();
 
-
 
-
textpane.setContentType("text/html");
 
-
textpane.setEditable(false);
 
-
</source>
 
-
 
-
We create a <b>JTextPane</b> component, set the content of the component to be a html document and disable
 
-
editing.
 
-
 
-
<source lang="java">
 
-
String cd = System.getProperty("user.dir") + "/";
 
-
</source>
 
-
 
-
Here we determine the current working directory of the user. The html document is located there.
 
-
 
-
<source lang="java">
 
-
try {
 
-
    textpane.setPage("File:///" + cd + "test.html");
 
-
} catch (IOException e) {
 
-
    System.out.println("Exception: " + e);
 
-
}
 
-
</source>
 
-
 
-
We load a html document into the pane.
 
-
 
-
[[image: java_swing_textpane.jpg | center]]
 
-
 
-
[[Категория:Java]]
 

Текущая версия на 11:27, 7 апреля 2009