Java Tutorial/Swing/Swing Introduction

Материал из Java эксперт
Перейти к: навигация, поиск

Get position of component

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
  JComponent comp = new JLabel("Test label");
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    comp.setToolTipText("Some tooltip text for component");
    comp.setBorder(new TitledBorder("Button"));
    System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
        + comp.getWidth() + " height:" + comp.getHeight());
    getContentPane().add(comp);
    pack();
    System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
        + comp.getWidth() + " height:" + comp.getHeight());
    setVisible(true);
  }
  public static void main(String arg[]) {
    new Main();
  }
}





Small Swing Application

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonSample {
  public static void main(String args[]) {
    Runnable runner = new Runnable() {
      public void run() {
        JFrame frame = new JFrame("Button Sample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton("Select Me");
        // Define ActionListener
        ActionListener actionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("I was selected.");
          }
        };
        // Attach listeners
        button.addActionListener(actionListener);
        frame.add(button, BorderLayout.SOUTH);
        frame.setSize(300, 100);
        frame.setVisible(true);
      }
    };
    EventQueue.invokeLater(runner);
  }
}





Swing components

JPasswordFielda specialized text field for password entryJEditorPane and JTextPaneprovide support for displaying and editing multiple-attributed content, such as an HTML and RTF.JSpinnerprovides selection from an ordered set of predefined valuesJToggleButtonoffers a button that stays depressed when selected.JSliderlike the Scrollbar component, offers various clues to help the user choose a value.JProgressBarallows the user to visually see the progress of an activity.JFormattedTextFieldprovides help for the input of formatted text, like numeric values, phone numbersJTabledisplays two-dimensional row and column informationJTreesupports the display of hierarchical data.JToolTipoffers useful tips.JToolBaroffers a draggable toolbarJRadioButtonMenuItema radio button menu component.JSeparatorThe menu"s separator barJDesktopPane and JInternalFrameThis pair of components are for Windows Multiple Document Interface (MDI).JOptionPanecreates pop-up windows with varied content,JColorChooserfor choosing a colorJSplitPaneplaces multiple components in a window with draggable divider.JTabbedPanetabbed panel


Swing Constants

Box-orientation Constants:

  1. static int TOP
  2. static int LEFT
  3. static int BOTTOM
  4. static int RIGHT

Geographical-direction Constants:

  1. static int NORTH
  2. static int NORTH_EAST
  3. static int EAST
  4. static int SOUTH_EAST
  5. static int SOUTH
  6. static int SOUTH_WEST
  7. static int SOUTH
  8. static int NORTH_WEST
  9. static int CENTER

The orientation of a component:

  1. static int HORIZONTAL
  2. static int VERTICAL


Swing MVC

The design of the Swing component classes is loosely based on the Model-View-Controller architecture, or MVC.

  1. The model stores the data.
  2. The view creates the visual representation from the data in the model.
  3. The controller deals with user interaction and modifies the model and/or the view.


Swing Worker from JDK 6 SE

import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
public class SwingWorkerDemo {
  public static void main(String[] args) {
    JTextArea textArea = new JTextArea(10, 20);
    final JProgressBar progressBar = new JProgressBar(0, 10);
    final CounterTask task = new CounterTask();
    task.addPropertyChangeListener(new PropertyChangeListener() {
      public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
          progressBar.setValue((Integer) evt.getNewValue());
        }
      }
    });
    JButton startButton = new JButton("Start");
    startButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        task.execute();
      }
    });
    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        task.cancel(true);
      }
    });
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(startButton);
    buttonPanel.add(cancelButton);
    JPanel cp = new JPanel();
    LayoutManager layout = new BoxLayout(cp, BoxLayout.Y_AXIS);
    cp.setLayout(layout);
    cp.add(buttonPanel);
    cp.add(new JScrollPane(textArea));
    cp.add(progressBar);
    JFrame frame = new JFrame("SwingWorker Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(cp);
    frame.pack();
    frame.setVisible(true);
  }
}
class CounterTask extends SwingWorker<Integer, Integer> {
  private static final int DELAY = 1000;
  public CounterTask() {
  }
  @Override
  protected Integer doInBackground() throws Exception {
    int i = 0;
    int count = 10;
    while (!isCancelled() && i < count) {
      i++;
      publish(new Integer[] { i });
      setProgress(count * i / count);
      Thread.sleep(DELAY);
    }
    return count;
  }
   
  protected void process(List<Integer> chunks) {
    for (int i : chunks)
      System.out.println(i);
  }
  @Override
  protected void done() {
    if (isCancelled())
      System.out.println("Cancelled !");
    else
      System.out.println("Done !");
  }
}





Understanding the Predefined Data Models: Swing Component Models

Component         Data Model(Interface)                Implementations
   AbstractButton    ButtonModel                          DefaultButtonModel
   JColorChooser     ColorSelectionModel                  DefaultColorSelectionModel
   JComboBox         ComboBoxModel                        N/A
                     MutableComboBoxModel                 DefaultComboBoxModel
   JFileChooser      ListModel                            BasicDirectoryModel
   JList             ListModel                            AbstractListModel
                                                          DefaultListModel  
                     ListSelectionModel                   DefaultListSelectionModel
   JMenuBar          SingleSelectionModel                 DefaultSingleSelectionModel
   JPopupMenu        SingleSelectionModel                 DefaultSingleSelectionModel
   JProgressBar      BoundedRangeModel                    DefaultBoundedRangeModel
   JScrollBar        BoundedRangeModel                    DefaultBoundedRangeModel
   JSlider           BoundedRangeModel                    DefaultBoundedRangeModel
   JSpinner          SpinnerModel                         AbstractSpinnerModel
                                                          SpinnerDateModel  
                                                          SpinnerListModel                     
                                                          SpinnerNumberModel
   JTabbedPane       SingleSelectionModel                 DefaultSingleSelectionModel
   JTable            TableModel                           AbstractTableModel
                                                          DefaultTableModel
                     TableColumnModel                     DefaultTableColumnModel
                     ListSelectionModel                   DefaultListSelectionModel
   JTextComponent    Document                             AbstractDocument
                                                          PlainDocument
                                                          StyledDocument
                                                          DefaultStyleDocument
                                                          HTMLDocument
   JToggleButton     ButtonModel                          ToggleButtonModel
   JTree             TreeModel                            DefaultTreeModel
                     TreeSelectionModel                    DefaultTreeSelectionModel
                                                          JTree.EmptySelectionModel