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
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.getCrossPlatformLoo kandfeelclassname()); catch (Exception e) {...//Create and show the GUI...
JComponent Wyłączjąc kontenery najwyŝszego poziomu wszystkie komponenty Swing'u (J...) dziedziczą funkcjonalność 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 eventhandling 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.
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 ).
Tworzenie GUI z EDT static void createandshowgui(){ new?????appl() ; public static void main(string[] args) { javax.swing.swingutilities.invokelater(new Runnable() { public void run() { createandshowgui(); );
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)
SwingWorker Example Zadanie: Obliczyć N wyrazów ciągu Fibonacciego. F n+1 = F n+1 + F n+1 {F 0 = 0, F 1 = 1 {0,1, 2, 3, 5, 8, 13, 21, 34, 55,... F 100 = 354224848179261915075
Okno aplikacji testowej
z EDT -->interfejs GUI zmroŝony!!! JButton calcinedt = new JButton("Calc in EDT") ; calcinedt.addactionlistener( new ActionListener () { public void actionperformed(actionevent ae) { int N = Integer.parseInt(how.getText().trim()) ; String r = "" + FibonacciNumbersTask.calcFibonacciNumbers(N) ; ); result.settext(r);
The solution is SwingWorker! Długhotrwałe akcje (long running task ): obliczenia, ładowanie obrazów, z pliku lub sieci, wykonanie eksperymentu pomiarowego,... naleŝy wykonywać za pomocą innych wątków (worker threads, background threads) Od wersji 1.6 moŝna skorzystać z klasy SwingWorker
Typy uogólnione (Generics) public abstract class SwingWorker<T,V> implements RunnableFuture<T> T - the result type returned by this SwingWorker's doinbackground and get methods V - the type used for carrying out intermediate results by this SwingWorker's publish and process methods
Wymiana danych class FibonacciNumbersTask extends SwingWorker<List<Integer>, Integer> { FibonacciNumbersTask(JTextArea textarea, int numberstofind) { this.textarea = textarea ; this.numberstofind = numberstofind ; F1 = 0; F2 = 1;...
doinbackground() i publish() public List<Integer> doinbackground() { int numberssofar = 0; while ((numberssofar < numberstofind) &&! iscancelled()) { Integer number = nextfibonaccinumber(); publish(number); numbers.add(number) ; setprogress(100 * numbers.size() / numberstofind); numberssofar ++ ; return numbers;
For each loop (array) For-each loop for (type var : arr) { body-of-loop Equivalent for loop for (int i = 0; i <arr.length; i++) { type var = arr[i]; body-of-loop
For each loop (Itarable) For-each loop for (type var : coll) { body-of-loop Equivalent for loop for (Iterator<type> iter = coll.iterator(); iter.hasnext(); ) { type var = iter.next(); body-of-loop
From Worker --> to EDT Istnieje moŝliwośc przekazywania rezultatów pośrednich w trakcie działania wątku worker Typ przekazywanych danych określony jest przez druki parametr SwingWorker-a Wmetodzie process (wywoływanej z EDT mozliwe jest wykorzystywanie tych danych (prezentacja wyników pośrednich) protected void process(list<integer> chunks) { for (int number : chunks) { textarea.append(number + ", ");
Swing'owy najemnik JButton calculate = new JButton("Let SwingWorker do the job ") ; calculate.addactionlistener( new ActionListener () { public void actionperformed(actionevent ae) { int N = Integer.parseInt(how.getText().trim()) ; task = new FibonacciNumbersTask(textArea, N); task.addpropertychangelistener( new PropertyChangeListener() { public void propertychange(propertychangeevent evt) { if ("progress".equals(evt.getpropertyname())) { progressbar.setvalue((integer)evt.getnewvalue()); ); ) ; textarea.settext("") ; task.execute();
setprogress(int) 0-100 public List<Integer> doinbackground() { int numberssofar = 0; while ((numberssofar < numberstofind) &&! iscancelled()) { Integer number = nextfibonaccinumber(); publish(number); numbers.add(number) ; setprogress(100 * numbers.size() / numberstofind); numberssofar ++ ; return numbers;
Properties state i progress evt) { task.addpropertychangelistener( new PropertyChangeListener() { public void propertychange(propertychangeevent if ("progress".equals(evt.getpropertyname())) { progressbar.setvalue((integer)evt.getnewvalue()); );
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.