DOC PREVIEW
UNC-Chapel Hill COMP 401 - Java_Swing_Components_and_Layout_Managers__Ravikiran_Janardhana

This preview shows page 1-2-16-17-18-34-35 out of 35 pages.

Save
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Java Swing Components and Layout Managers Ravikiran Janardhana COMP 401 Foundations of Programming UNC Chapel Hill 1 Source http dilbert com strips comic 2010 05 14 2 Demo Code Download the zipped demo code java swingui zip in Piazza under Recitation section Alternative http bit ly 17g106Q Create a new Java Project in Eclipse Extract the zipped demo code Place all the 3 folders demo tictactoe widgets in your Project src source folder and refresh the project in Eclipse 3 Java Swing Java Swing is a set of classes that provide powerful and flexible GUI components Built on top of Abstract Window Toolkit AWT Swing Components are lightweight Supports a pluggable look and feel 4 Aspects of a UI Component View The way that the component looks when rendered on the screen Controller The way that the component reacts to the user Model The state information associated with the component 5 Example Check Box Model whether the box is checked or not View how the check box is displayed on the screen Controller what to do when a user click s a check box Java Swing combines View and Controller into a single entity called UI delegate So it uses Model Delegate architecture 6 MVC Source http www codeproject com Articles 17068 A Practical Use of the MVC Pattern 7 Components Swing Components are derived from the JComponent class JComponent inherits the AWT classes Container and Component All of Swing components are represented by classes defined within the package javax swing 8 Top Level Containers Source http docs oracle com javase tutorial uiswing components toplevel html 9 Swing Components all Source Java The Complete Reference Seventh Edition 10 An Honest Confession I cannot remember every component s syntax I always refer to Oracle previously Sun documentation and examples while working with Swing I usually have a framework and I fill the blanks based on the type of UI 11 Let s build something Tic Tac Toe 3 x 3 grid Players alternate in choosing a slot on the grid Player wins if he has three slots in a row or column or diagonally Game is a draw if all slots are filled and we have no winner 12 Design What does the end product look like Always draw first on the paper UI design program Most programmers are good at programming and not UI design it s an art 13 UI Mockup The last point in the previous slide is true in my case 14 What Components to use JFrame drawing sheet JPanel container of Components JButton to represent 3x3 grid JLabel to indicate player turn How to put everything together Use Layout Managers 15 Visual guide to Layout Managers BorderLayout BoxLayout Source http docs oracle com javase tutorial uiswing layout visual html 16 Visual guide to Layout Managers FlowLayout GridLayout Source http docs oracle com javase tutorial uiswing layout visual html 17 GridBagLayout Flexible and Complex Components are placed in grid of row and columns allowing specified components to span multiple rows or columns 3x3 Grid Single label at 0 3 will span 3 columns 18 GridBagLayout Mockup and Layout match 0 0 1 0 2 0 0 1 1 1 2 1 0 2 1 2 2 2 0 3 19 Steps to build Java Swing UI Initialize a JFrame Initialize a JPanel and add it to the JFrame Add JComponent s JButton JLabel to the JPanel Add event handlers to the components and logic to update state 20 Initialize a Jframe Demo1 java package demo import java awt Dimension import javax swing JFrame public class UIDemo JFrame f public static void main String args UIDemo ui new UIDemo ui initUI public void initUI Initialize a new JFrame f new JFrame Set the size f setSize new Dimension 460 460 Set title f setTitle Tic Tac Toe Set visibility f setVisible true Set default operation on close f setDefaultCloseOperation JFrame EXIT ON CLOSE 21 Initialize a JPanel Demo2 java public class UIDemo JFrame f JPanel p public void initUI Initialize a new JFrame f new JFrame Set the size f setSize new Dimension 600 600 Set frame layout not required here f setLayout new FlowLayout Initialize a JPanel p new JPanel Set panel layout p setLayout new GridBagLayout Set panel size not required here p setPreferredSize new Dimension 460 460 Add the JPanel to the JFrame f add p Rest of the code as in previous slide Nothing changed but there is a JPanel added to the JFrame 22 Add JButton grid Demo3 java b new JButton 9 int k 0 GridBagLayout constraints GridBagConstraints c new GridBagConstraints for int i 0 i 3 i for int j 0 j 3 j Used when the component s display area is larger than the component s requested size to determine whether and how to resize the component c fill GridBagConstraints BOTH Internal X and Y padding c ipadx 10 c ipady 10 Grid position i j c gridx i c gridy j Weights 0 0 to 1 0 are used to determine how to distribute space among columns weightx and among rows weighty this is important for specifying resizing behavior c weightx 0 5 c weighty 0 5 Set button properties b k new JButton Add button to panel p add b k c 23 Source http docs oracle com javase tutorial uiswing layout gridbag html Add JButton Icon and JLabel Demo4 java ImageIcon defaultIcon new ImageIcon getClass getResource default png for int i 0 i 3 i for int j 0 j 3 j Rest of the code Set button properties b k new JButton Set background color b k setBackground Color WHITE Set default icon b k setIcon defaultIcon Rest of the code Add the JLabel pStatus new JLabel Player 1 O turn pStatus setHorizontalAlignment JLabel CENTER pStatus setFont new Font SansSerif Font BOLD 20 Constraints c fill GridBagConstraints BOTH c gridwidth 3 c gridheight 1 c ipadx 10 c ipady 10 c gridx 0 c gridy 3 c weightx 0 5 c weighty 0 5 p add pStatus c At 0 3 JLabel the gridWidth and gridHeight is 3 columns 1 row 24 Add JButton Event Handler Demo5 java Start initUI function Inside for loop Add action listener click handler b k addActionListener new ButtonHandler this Close for loop Close initUI function class ButtonHandler implements ActionListener private Demo5 t private ImageIcon p1Icon p2Icon public ButtonHandler Demo5 demo5 t demo5 p1Icon new ImageIcon getClass getResource O png p2Icon new ImageIcon getClass getResource X png 25 Add JButton Event Handler Demo5 java Override public void actionPerformed ActionEvent e JButton b b JButton e getSource if t currentPlayer equals P1 b setIcon p1Icon else b setIcon p2Icon find which button was click and update data int state t updateState b Disable button and setDisabledButtonIcon b setEnabled false b setDisabledIcon b getIcon Increment moves t totalMoves Check if there is a winner t


View Full Document

UNC-Chapel Hill COMP 401 - Java_Swing_Components_and_Layout_Managers__Ravikiran_Janardhana

Documents in this Course
Objects

Objects

36 pages

Recursion

Recursion

45 pages

Load more
Loading Unlocking...
Login

Join to view Java_Swing_Components_and_Layout_Managers__Ravikiran_Janardhana and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java_Swing_Components_and_Layout_Managers__Ravikiran_Janardhana and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?