JFC
(Swing)
Doskonalsze i nowe komponenty GUI
Kontenery najwyŜszego poziomu
• Aby pojawić się na ekranie kaŜdy komponent musi być częścią pewnej hierarchii zawierania (containment hierarchy).
• Hierarchia zawierania ma strukturę drzewiastą, której korzeniem jest jeden z kontenerów najwyŜszego poziomu:
JFrame, JDialog, lub JApplet
JFrame
Creating and Showing Frames
import javax.swing.*;
public class TopLevelDemo {
/*** Create the GUI and show it. */
private static void createAndShowGUI() { //Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
Alternatywnie
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(someBorder);
contentPane.add(someComponent, BorderLayout.CENTER);
contentPane.add(anotherComponent, BorderLayout.PAGE_END);
topLevelContainer.setContentPane(conten tPane);
Look and feel
Java look and feel CDE/Motif look and feel
Windows look and feel
Import pakietu & look
import javax.swing.*;
...
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLook AndFeelClassName());
} catch (Exception e) { } ...//Create and show the GUI...
JComponent
•Wyłączjąc kontenery najwyŜszego poziomu wszystkie komponenty Swing'u (J...)
dziedziczą funkconalność po klasie Jcomponent, która z kolei po klasach Container i Component, stąd przydatna jest znajomość wielu uŜytecznych metod oferowanych w tej klasie:
setToolTip
• b1.setToolTipText("Click this button to disable the middle button.");
Painting and Borders
• JPanel pane = new JPanel();
• pane.setBorder(BorderFactory.createLineBorder(
Color.black));
The Swing Painting Methods
• paintComponent — The main method for painting. By default, it first paints the background if the
component is opaque. Then it performs any custom painting.
• paintBorder— Tells the component's border (if any) to paint. Do not invoke or override this method.
• paintChildren— Tells any components contained by this component to paint themselves. Do not invoke or override this method.
System współrzędnych
• protected void
paintComponent(Graphics g) {
• ...
• Insets insets = getInsets();
• int currentWidth = getWidth()
- insets.left –
insets.right;
• int currentHeight = getHeight() - insets.top – insets.bottom;
• ...
• .../* First painting occurs at (x,y), where x is at least insets.left, and y is at least insets.top. */
• ...
• }
Graphics2D
• if (isOpaque()) {
• //paint background
• g.setColor(getBackground());
• g.fillRect(0, 0, getWidth(), getHeight()); }
• //Example of copying the Graphics object
• Graphics2D g2d = (Graphics2D)g.create(); //copy g
• g2d.translate(x, y);
• ...
• g2d.dispose(); //release the copy's resources
Swing i wątki
• Initial threads, the threads that execute initial application code.
• The event dispatch thread, where all event- handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
• Worker threads, also known as background threads, where time-consuming background tasks are executed.
Tworzenie GUI z EDT
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {
createAndShowGUI();
} });
}
} // of TopLevelDemo
SwingUtilities.invokeLater
• Zasadniczo dopuszcza się tworzenie
komponentów GUI z innych wątków, jednak z chwilą ich realizacji (metody pack() i
setVisible(true)) dalsze operowanie na nich jest dopuszczalne jedynie z EDT.
• Obecnie zaleca się nawet takŜe tworzenie GUI z wątku EDT via:
• SwingUtilities.invokeLater( Runnable ) or SwingUtilities.invokeAndWait( Runnable ).
EventDispatchThread
• EDT
• The Swing Thread
• AWT-EventQueue-0
• One of the most common errors is to tie up the AWT/Swing event thread with some long running computation or even a sleep.
Everything freezes up. The GUI can't respond to mouse clicks and no repainting happens.
Krótka obsługa zdarzeń
• Wygodnie jest traktować kod wykonywany w wątku Swing jako szereg krótkich zadań, z których większość to wywołanie procedur obsługi zdarzeń (event-handling methods) jak ActionListener.actionPerformed.
• Jeśli te procedury nie kończą się szybko interfejs uŜytkownika przestaje reagować
Podsumowanie
• Time-consuming tasks should not be run on the Event Dispatch Thread.
• Swing components should be accessed on the Event Dispatch Thread only.
• SwingWorker is designed for situations where you need to have a long running task run in a background thread and provide updates to the UI either when done, or while processing. (dopiero w 1.6)
Model Komponentowy Javy
Java Beans (Fasolki)
Komponenty programowe
• Components are self-contained, reusable software units that can be visually assembled into composite components, applets, applications, and servlets using visual application builder tools. JavaBean components are known as beans.
• Builder tools discover a bean's features (that is, its properties, methods, and events) by a process known as introspection.
Charakterystyki fasolek
• Properties are the appearance and behavior characteristics of a bean that can be changed at design time.
• Beans expose properties so they can be customized at design time.
• Beans use events to communicate with other beans.
• Persistence enables beans to save and restore their state.