Presentation is loading. Please wait.

Presentation is loading. Please wait.

Overview of Java GUIs ….

Similar presentations


Presentation on theme: "Overview of Java GUIs …."— Presentation transcript:

1 Overview of Java GUIs

2 Outline Introduction to AWT and Swing

3 Abstract Window Toolkit (AWT)
Provides basic UI components: Buttons, lists, menus, textfields, etc Event handling mechanism Clipboard and data transfer Image manipulation Font manipulation Graphics Platform independence is achieved through peers, or native GUI components

4 AWT Packages java.awt Basic component functionality
java.awt.accessibility Assistive technologies java.awt.color Colors and color spaces java.awt.datatransfer Clipboard and data transfer support java.awt.dnd Drag and drop java.awt.event Event classes and listeners java.awt.font D API font package java.awt.geom D API geometry package java.awt.im Input methods java.awt.image Fundamental image manipulation classes java.awt.peer Peer interfaces for component peers java.awt.print D API support for printing java.awt.swing Swing components

5 Peers and Platform Independence
The first AWT (Java 1.0) was rolled out in an incredible 6 weeks using peers Thus an AWT menu on the Solaris platform, for example, actually creates a Motif menu object as its peer UI components that have peers are called heavyweight because they are rendered in their own (opaque) windows and thus are expensive to use, they must be rectangular and cannot have transparent backgrounds, and they are not amenable to being subclassed

6 Lightweight Components
AWT 1.1 introduced the notion of lightweight components which: are contained within a heavyweight component's window do not have peers are rendered in their container's window rather than one of their own do not incur performance penalties and can have transparent backgrounds Almost all Swing components are lightweight ones that extend either java.awt.Component or java.awt.Container

7 Some AWT Components Object Component Container List Button Scrollbar
Label Canvas

8 AWT vs. Swing Swing does not replace the AWT; it is built on top of it
All 1.0 AWT components are heavyweight; corresponding Swing components are lightweight Swing component names begin with ``J'': Component (AWT) vs. JComponent (Swing) Button (AWT) vs. JButton (Swing) Always use Swing components; however, since Swing is built on top of AWT, you will need to know some AWT methods

9 AWT vs Swing AWT – Abstract Window Toolkit Swing
Provides platform-specific GUI elements Look and feel define by platform not by java A GUI may look very different platforms Is heavyweight – use native code resources Swing Provides platform-independent GUI elements Look and feel define by Java A GUI looks the same on different platforms Is lightweight – written in Java Is built on top of AWT Uses Model Delegate architecture (rather than classic MVC)

10 Components & Containers javax.swing
Component – independent visual control Jbutton, Jlabel, Jlist, Jscrollbar, Container – holds a group of containers Top-level components (heavyweight) Jframe, Japplet, Jwindow, Jdialog Other components

11 Some Swing Components JComponent AbstractButton JLabel JButton
JMenuItem JList JToggleButton JScrollBar JCheckBox JFileChooser

12 JComponents Note that JComponents are containers
JComponents do not extend their AWT counterparts: For example, the JButton class is not a subclass (direct or indirect) of Button However, some Swing components are not JComponents For example, some Swing containers are direct subclasses of their AWT counterparts

13 Some AWT Containers Container JComponent Panel ScrollPane Window
Applet Dialog Frame

14 Swing Components That Are Not JComponents (in red)
Container JComponent Panel Window ScrollPane Dialog Frame Applet JWindow JDialog JFrame JApplet

15 Some More Swing Components That Are JComponents
JLayeredPane JPanel JDesktopPane JScrollPane JInternalFrame JTable JTree

16 Some AWT Component Methods
void setBackground(Color c) void setForeground(Color c) void setEnabled(boolean b) void setVisible(boolean b) void setFont(Font f) void setSize(Dimension d) void setLocation(int x, int y) All but setSize and setLocation are overridden by the JComponent class.

17 Swing Components

18 Swing Components

19 Example: A Simple Framed Window
import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setVisible(true); } //Code runs on the Event Dispatching thread, not the //main thread.

20 Notes on the Example setSize and setLocation require java.awt.*; the rest require javax.swing.* The JFrame constructor argument is used as a title The Dimension constructor takes an integer width and height, respectively The setLocation method takes a pair of integer coordinates (x,y) where (0,0) is the upper left corner of the display The visibility of a JFrame is set to false by default Clicking the Close button (X) will cause the display to be hidden, but the program will continue since no listeners are set up yet Can use ctl-C to kill the Java Virtual Machine OR frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

21 Adding Color The java.awt.Color class has the following static
fields (data members): Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow

22 Changing Background Color
import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); frame.setBackground(Color.red); frame.setVisible(true); }

23 Content Panes JWindow JFrame JApplet JDialog JInternalFrame
A: In order to be lightweight, Swing's top-level window objects must be built on top of a lightweight AWT Container object introduced in version 1.1 This container is called a content pane Swing top-level window classes: JWindow JFrame JApplet JDialog JInternalFrame Items added to the frame are added to the content pane.

24 Adding a Label and Button – the OLD Way
import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); Container contentPane = frame.getContentPane(); JLabel label = new JLabel("HERE IS A LABEL"); contentPane.add(label, BorderLayout.NORTH); JButton button = new JButton("BUTTON"); contentPane.add(button, BorderLayout.SOUTH); frame.setVisible(true); }

25 Adding a Label and Button – the NEW Way
import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); Container contentPane = frame.getContentPane(); JLabel label = new JLabel("HERE IS A LABEL"); frame.add(label, “North”); JButton button = new JButton("BUTTON"); contentPane.add(button, “South”); frame.setVisible(true); }

26 New Display Resized

27 Notes on the Code The default layout manager for a JFrame is a BorderLayout manager (described later) When adding to a container whose layout manager is BorderLayout, the second parameter should be a location defined in the BorderLayout class

28 Adding a List of Options
import java.awt.*; import javax.swing.*; public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); JLabel label = new JLabel("HERE IS A LABEL"); frame.add(label, BorderLayout.NORTH); JButton button = new JButton("BUTTON"); frame.add(button, BorderLayout.SOUTH); String[] options = {"Option 1", "Option 2", "Option 3"}; JList list = new JList(options); frame.add(list, BorderLayout.CENTER); frame.setVisible(true); }

29 New Display Note that "Option 3" has been selected.

30 Adding a Check Box and Slider
public class SwingTest { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(400,200)); frame.setLocation(100,100); JLabel label = new JLabel("HERE IS A LABEL"); frame.add(label, BorderLayout.NORTH); JButton button = new JButton("BUTTON"); frame.add(button, BorderLayout.SOUTH); String[] options = {"Option 1", "Option 2", "Option 3"}; JList list = new JList(options); contentPane.add(list, BorderLayout.CENTER); JCheckBox cbox = new JCheckBox("Check"); frame.add(cbox, BorderLayout.WEST); JSlider slider = new JSlider(); frame.add(slider, BorderLayout.EAST); frame.setVisible(true); }

31 Layout Management A layout manager determines the location and size of components placed into a container Different layout managers use different algorithms for determining size and location: BorderLayout: places at compass locations and center FlowLayout: places components in rows, left to right GridLayout: places in rectangular grid BoxLayout: places in a single row or column Setting the current layout of a container: void setLayout(LayoutManager lm)

32 Containers - Layout

33 Changing the Layout public class SwingTest {
public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); frame.setLayout(new FlowLayout()); JLabel label = new JLabel("HERE IS A LABEL"); JButton button = new JButton("BUTTON"); String[] options = {"Option 1", "Option 2", "Option 3"}; JList list = new JList(options); JCheckBox cbox = new JCheckBox("Check"); JSlider slider = new JSlider(); frame.add(label); frame.add(button); frame.add(list); frame.add(cbox); frame.add(slider); frame.setVisible(true); }

34 New Display Resized

35 Default Layout Managers
The default layout manager for content panes is BorderLayout. Recall that the following Swing components have content panes: JWindow JFrame JDialog JApplet JInternalFrame The other Swing container is the JPanel, whose default layout manager is FlowLayout.

36 JPanels A JPanel object can be used for grouping components into a container, which can then be added to another container The JPanel constructor with no arguments creates a panel with a FlowLayout manager Another JPanel constructor takes any layout manager as an argument A JPanel can also be used a a blank area for drawing custom graphics

37 JPanel Example public class SwingTest5 { public SwingTest5() {
JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); JLabel label = new JLabel("HERE ARE SOME BUTTONS", SwingConstants.CENTER); JButton button1 = new JButton("BUTTON1"); JButton button2 = new JButton("BUTTON2"); JButton button3 = new JButton("BUTTON3"); JPanel panel = new JPanel(); panel.add(button1); panel.add(button2); panel.add(button3); frame.add(label, BorderLayout.NORTH); frame.add(panel, BorderLayout.CENTER); frame.setVisible(true); } public static void main(String[] args) { SwingTest5 gui = new SwingTest5(); JPanel Example

38 JPanel Example using extends
public class SwingTest6 extends JFrame{ public SwingTest6() { super("Test Frame"); setSize(new Dimension(300,200)); setLocation(100,100); JLabel label = new JLabel("HERE ARE SOME BUTTONS", SwingConstants.CENTER); JButton button1 = new JButton("BUTTON1"); JButton button2 = new JButton("BUTTON2"); JButton button3 = new JButton("BUTTON3"); JPanel panel = new JPanel(); panel.add(button1); panel.add(button2); panel.add(button3); add(label, BorderLayout.NORTH); add(panel, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args) { SwingTest6 gui = new SwingTest6(); JPanel Example using extends

39 JPanel Example Output Note use of SwingConstants.CENTER argument
in JLabel constructor.

40 Changing JPanel Layout
JFrame frame = new JFrame("Test Frame"); frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); JLabel label = new JLabel("HERE ARE SOME BUTTONS", SwingConstants.CENTER); JButton button1 = new JButton("BUTTON1"); JButton button2 = new JButton("BUTTON2"); JButton button3 = new JButton("BUTTON3"); JPanel panel = new JPanel(); panel.setLayout (new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(button1); panel.add(button2); panel.add(button3); frame.add(label, BorderLayout.NORTH); frame.add(panel, BorderLayout.CENTER); frame.setVisible(true);

41 New Output The button panel is to the west because no other component was placed there The BoxLayout constructor requires both the component being laid out and either: BoxLayout.X_AXIS BoxLayout.Y_AXIS

42 Tweaking Layouts Some layout constructors allow hgap and vgap, integers specifying the number of pixels separating components horizontally and vertically FlowLayout allows the specification of whether the line of components should be left-justified, right-justified, or centered new FlowLayout(int align) new FlowLayout(int align, int hgap, int vgap) new BorderLayout(int hgap, int vgap) new GridLayout(int rows, int cols) new GridLayout(int rows, int cols, int hgap, int vgap)

43 Tweaking Example JFrame frame = new JFrame("Test Frame");
frame.setSize(new Dimension(300,200)); frame.setLocation(100,100); LayoutManager lm = frame.getLayout(); ((BorderLayout)lm).setHgap(25); JLabel label = new JLabel("HERE ARE SOME BUTTONS", SwingConstants.CENTER); JButton button1 = new JButton("BUTTON1"); JButton button2 = new JButton("BUTTON2"); JButton button3 = new JButton("BUTTON3"); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(button1); panel.add(button2); panel.add(button3); frame.add(label, BorderLayout.NORTH); frame.add(panel, BorderLayout.CENTER); frame.setVisible(true);

44 Tweaking Example Output
The LayoutManager returned by getLayout() is an interface type that the BorderLayout class implements The setHgap method we want is in the BorderLayout class So we must cast the LayoutManager to BorderLayout in order to use setHgap

45 Sizing Hints Layout managers often need to resize their components to make things fit For example, the widths and heights of components in a BoxLayout are adjusted according to both preferred and maximum heights and widths If you don't like the size of the components a layout manager comes up with, you may have to give sizing hints using the following methods from the JComponent class: void setMinimumSize(Dimension d) void setPreferredSize(Dimension d) void setMaximumSize(Dimension d)

46 Sizing Hints Layout managers often need to resize their components to make things fit For example, the widths and heights of components in a BoxLayout are adjusted according to both preferred and maximum heights and widths If you don't like the size of the components a layout manager comes up with, you may have to give sizing hints using the following methods from the JComponent class: void setMinimumSize(Dimension d) void setPreferredSize(Dimension d) void setMaximumSize(Dimension d)

47 Sizing Hints public class OnOffButton extends JButton{
public OnOffButton(String label) { super(label); } public Dimension getPreferredSize() { return new Dimension(100, 50);// height 100, width 50 pixels public Dimension getMinimumSize() { return this.getPreferredSize();// height 100, width 50 pixels public Dimension getMaximumSize() {

48 Input – Events & Listeners
So we now know how to present widgets on the screen A program also needs to react to the user's actions Examples: When the user presses a button we want to save a file When the user closes the program we want to ask “are you sure?” ... Swing mechanism: Events and Listeners

49 Events, Listeners Event – an action to which the system must respond.
Key event – from keyboard Mouse event Window event High-level events Action event Item event Adjustment event Document event etc.

50 Events, Listeners Listener / event handler – an object that is interested in the occurrence of an event and want to be notified when the event occurs. Swing defines all sorts of Listener interfaces E.g.: ActionListener, MouseMotionListener, WindowListener, ... public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); } public interface MouseMotionListener extends EventListener { public void mouseDragged(MouseEvent e); public void mouseMoved(MouseEvent e); There are default (empty) implementations for many of the listeners E.g.: MouseMotionAdapter, WindowAdapter

51 Adding a listener using an anonymous inner class
JButton alphaB = new JButton("Alpha"); //Add action Listener for Alpha alphaB.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { alphaB.setBackground(Color.RED); alphaB.setForeground(Color.WHITE); } });

52 Adding a listener using a normal inner class
class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent ae){ Component source = (Component)ae.getSource(); Color oldBackground = source.getBackground(); Color oldForeground = source.getForeground(); source.setBackground(oldForeground); source.setForeground(oldBackground); JOptionPane.showMessageDialog(null, source); } //Use the listener JButton alphaB = new JButton("Alpha"); ButtonListener listener = new ButtonListener(); alphaB.addActionListener(listener);

53 The End Qu es ti ons? ______________________ Devon M. Simmonds
Computer Science Department University of North Carolina Wilmington _____________________________________________________________


Download ppt "Overview of Java GUIs …."

Similar presentations


Ads by Google