1 ASSOSA UNIVERSITY FACULTY OF ENGINEERING & TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE Advanced Programming Compiled by: Melkamu A. Email: malmawu@gmail.com 1 2/20/2023 Chapter 1 Java GUIs using Swing 2/20/2023 Objective Introducing the different techniques necessary to build graphical user interfaces (GUIs) for your applications. Learning Swing basic concepts: components Containers colors layout. Constructing Swing interfaces Using the Swing Event Model. Overview of Event Handling Mechanism 3 How to create and manage fonts, output Text, and Utilize Graphics Questions Define Programming Paradigm and List out types of Programming 4 Paradigm and discuses in details about them? What Is Java programming? Types of Java Programming What are the characteristics of Java programming? Types Of Java Application? Introduction So far, our user interfaces have only been textual, meaning the user sees text and writes text at the command prompt. But it is also possible to make our interfaces graphical, so we can use our programs through windows, click on buttons, etc, using Java GUIs. A graphical user interface presents a user-friendly mechanisms for interacting with an application. There are actually two sets of GUI components in Java: AWT(Abstract Window Toolkit) Swing 5 Swing Vs AWT AWT is Java’s original set of classes for building GUIs which: The AWT components are 'heavyweight', rely on local platform's windowing system for look and feel. Not truly portable: looks different and lays out inconsistently on different Oss Due to OS’s underlying display management system Swing is designed to solve AWT’s problems Most Swing components are 'lightweight', in the sense that they are coded in Java and do not correspond to OS things. Swing components allow programmer to specify look and feel Can change depending on platform Can be same across all platforms Uses some of AWT components like Window, frame, dialog 6 Uses AWT event handling Component defines methods used in its subclasses (for example, paint and repaint) Container - collection of related components When using (a Container) JFrame, add components JComponent - superclass to most Swing components 7 to content pane Contd. When building a GUI you must create your components, create the containers that will hold the components and then add the components to the containers. Top level containers Jframe, Jdialog, Jwindow do not inherit from Jcomponent. 8 Swing Components 1. JFrame is Swing’s version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. 2. JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from Jcomponent. 3. FlowLayout when used arranges swing components from left to right until there’s no more space available. Then it begins a new row below it and moves from left to right again. 4. GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The 9 container is divided into and one component is placed in each rectangle. equal-sized rectangles, Contd. 5. JLabel descended from JComponent, is used to create text labels. 6. JButton The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including Jbutton. 7. JTextField allows editing of a single line of text with new text editing features. 8. JTextArea allows editing of multiple lines of text. 9. JButton is a component the user clicks to trigger a specific action. 10. JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state. 11. JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ’s that you can select. 10 JFrame JFrame is the application window that encompasses your GUI objects with border, title and buttons. operating system It is special; it draws the window and interacts with the When a JFrame is created, an inner container called the contentPane is automatically created. We don't draw graphics directly on JFrame; we draw on the contentPane Creating a JFrameWindow 1. Construct an object of the JFrame class. 2. Set the size of the Jframe. 3. Set the title of the Jframe to appear in the title bar (title bar will be blank if no title is set). 4. Set the default close operation. When the user clicks the close button, the program stops running. 5. Make the Jframe visible. 11 //Swing sample Program import java.awt.*; import javax.swing.*; public class Main extends JFrame { JLabel myLabel = new JLabel("Hello, World!"); public Main() { super("Wel-Come to Java GUI"); setSize(300, 100); getContentPane().add(myLabel); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main (String args[]) { Main m = new Main(); } } Output 12 title bar minimize maximize close contentPane (A) Anatomy of a JFrame (B)Frames, Panes and Panels 13 Layout Manager Layout management is the process of determining the size and location of a container's components. Java containers do not handle their own layout. They delegate that task to their layout manager, an instance of another class. If you do not like a container's default layout manager, you can change it. Container content = getContentPane(); content.setLayout( new FlowLayout() ); Swing provides 6 Layout manager classes: FlowLayout, GridLayout, 14 BorderLayout,GridBagLayout,BoxLayout and CardLayout FlowLayout FlowLayout, the simplest of the managers, simply adds components left to right until it can fit no more within its container's width. It then starts a second line of components, fills that, starts a third, etc. Each component gets as much space as it needs and no more. FlowLayout is the default layout manager for Jpanel Syntax <nameofcontainer>.setLayout(new FlowLayout()); Example: panel.setLayout(new FlowLayout()); panel.add(button); 15 //FlowLayout import java.awt.*; import javax.swing.*; public class Main extends JFrame{ public static void main (String args[]) { Output JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("FlowLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout()); JButton b1 = new JButton("Hello"); frame.getContentPane().add(b1); JButton b2 = new JButton("Two"); frame.getContentPane().add(b2); JTextField t1 = new JTextField("Text here"); frame.getContentPane().add(t1); frame.pack(); frame.setVisible(true); } 16 } BorderLayout Zones A border layout divides the container into five regions (top, bottom ,left,right and center); each region may contain only one component North West Center East South Components are added to one of these parts, only one component per part. BorderLayout is the default LayoutManager for the contentpane of a Jframe Syntax <nameofcontainer>.setLayout(new BorderLayout()); <nameofcontainer>.add(<nameofcomponent>,BorderLayout.REGION); where REGION is either NORTH, SOUTH, WEST, CENTER OR EAST 17 //BorderLayout import java.awt.*; import javax.swing.*; public class DemoBorderLayout extends JFrame{ public static void main (String args[]){ JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Border"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton b1 = new JButton("At the top"); frame.getContentPane().add(b1,BorderLayout.NORTH ); JButton b2 = new JButton("Bottom"); frame.getContentPane().add(b2,BorderLayout.SOUTH); JTextField t1 = new JTextField("Left"); frame.getContentPane().add(t1,BorderLayout.WEST); JTextField t2 = new JTextField("Right"); frame.getContentPane().add(t2,BorderLayout.EAST); JButton b3 = new JButton("Centre"); frame.getContentPane().add(b3,BorderLayout.CENTER ); frame.setSize(200, 120); frame.setVisible(true); 18 }} Output GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. Items are added (by default) into top-down left-right order. GridLayout(int rows, int cols, int hgap, int vgap); is also a GridLayout constructo which creates a grid layout with the specified number of rows and columns. The third and fourth arguments are gaps between cells. By default they are zero. The first and second are rows and columns. Syntax <nameofcontainer>.setLayout(new GridLayout(int rows, int cols, int hgap, int vgap)); Example: 19 panel.setLayout(new GridLayout(2.3)); //GridLayout import java.awt.*; import javax.swing.*; public class Main extends JFrame{ public static void main (String args[]) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("GridLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new GridLayout(4,3,5,5)); for (int i=0; i<10; i++) frame.getContentPane().add(new JButton(""+i)); frame.pack(); frame.setVisible(true); } 20 } Output JLabels Labels Provide text instructions or information on a GUI. Displays a single linw read-only text, an image or both text and image. Programs rarely change a label's contents Constructors: 1. JLabel() : Creates a JLabel instance with no image and with an empty string for the title. 2. JLabel(Icon image) :Creates a JLabel instance with the specified image. 3. JLabel(String text) : Creates a JLabel instance with the specified text. Methods myLabel.setToolTipText( "Text" ) Displays "Text" in a tool tip when mouse over label myLabel.setText( "Text" ) myLabel.getText() 21 JLabel Display Text, not editable JLabel lblTen=new JLabel("second year computer Science student:"); lblTen.setForeground(Color.RED); Could add Icon for JLabel ImageIcon icon=new ImageIcon(“image.png"); lbl.setIcon(icon); 22 JTextField JTextField allows editing/displaying of a single line of text with new editing features. When the user types data into them and presses the Enter key, an ActionPerformed event is produced. JTextField is an input area where the user can type in characters. If you want to let the user enter multiple lines of text, you can use JTextArea, which enables the user to enter multiple lines of text. JTextField Constructor i. JTextField() Constructs a new TextField. ii. JTextField(String text) 23 the specified text. Constructs a new TextField initialized with …Continued Display data, Input data getContentPane().setLayout(new FlowLayout()); JLabel lblTen=new JLabel(“User:"); JTextField txtTen=new JTextField(15); add(lblTen);add(txtTen); If you don’t allow input data, please call setEditable method and take false value txtTen.setEditable(false); 24 …Continued To set Text in code behind for JTextField: txtTen.setText("Hello student"); To get Text from JTextField: String s=txtTen.getText(); We could convert data: int n=Integer.parseInt(s); double d=Double.parseDouble(s); float f=Float.parseFloat(s); To set focus:txtTen.requestFocus(); 25 JButton The Java class that allows you to define a button Multiple constructors allow you to initialize a button with a predefined label and/or a predefined icon Although the button’s “action” can be defined in the constructor, defining a button’s action can take many lines of code and should be done separately. JButton Constructor JButton() : Creates a button with no set text or icon. JButton(Action a) : Creates a button where properties are taken from the Action supplied. JButton(String text) : Creates a button with text. 26 …Continue It is very important, attach event to do something that you want. JButton btn=new JButton("Watch"); btn.setIcon(new ImageIcon("mywatch.png")); btn.setMnemonic('W'); Alt+W to call btn command btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //do something here coding here } Add event for this button: }); 27 Handling Button’s Click event Implement an ActionListener and Assign it to the button class CopyListener implements ActionListener { public void actionPerformed(ActionEvent event) { //Handle the event here } } //Create the listener and assign it to the button CopyListener listener = new CopyListener(); button.addActionListener(listener); 28 //Swing sample Program import java.awt.*; import java.awt.event.*; import javax.swing.*; public JUIExample1 extends JFrame { private JTextArea text; public JUIExample1 () { super("Wel-Come to Java GUI"); setSize(300, 100); getContentPane().setLayout(new BorderLayout()); text= new JTextArea (30,40); getContentPane().add(text, BorderLayout.CENTER); JButton button= new JButton ("Change to Capital"); getContentPane().add(button,BorderLayout.SOUTH); class ButtonListener implements ActionListener { 29 public void actionPerformed(ActionEvent event) { text.setText(text.getText().toUpperCase()); } } ButtonListener listener = new ButtonListener(); button.addActionListener(listener); setVisible(true); } public static void main (String args[]) { JUIExample1 m = new JUIExample1 (); } } 30 JComboBox JComboBox is like a drop down box, you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists. JComboBox Constructor JComboBox() Creates a JComboBox with a default data model. JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array. JComboBox(Vector items) Creates a JComboBox that contains the elements in the specified Vector. 31 JCheckBox When JCheckBox changes ItemEvent generated Handled by an ItemListener, which must define itemStateChanged Register handlers with with addItemListener private class CheckBoxHandler implements ItemListener { public void itemStateChanged( ItemEvent e ) Class ItemEvent getStateChange Returns ItemEvent.SELECTED or ItemEvent.DESELECTED 32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 33 30 // Fig. 12.12: CheckBoxTest.java // Creating Checkbox buttons. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBoxTest extends JFrame { private JTextField t; private JCheckBox bold, italic; public CheckBoxTest() { super( "JCheckBox Test" ); Container c = getContentPane(); c.setLayout(new FlowLayout()); 1. import t = new JTextField( "Watch the 1.1 font style change", 20 ); Declarations t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) ); c.add( t ); 1.2 Initialize JCheckBoxes // create checkbox objects bold = new JCheckBox( "Bold" ); c.add( bold ); Create JCheckBoxes italic = new JCheckBox( "Italic" ); c.add( italic ); CheckBoxHandler handler = new CheckBoxHandler(); bold.addItemListener( handler ); 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 6134 italic.addItemListener( handler ); addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); setSize( 275, 100 ); show(); } public static void main( String { new CheckBoxTest(); } Because CheckBoxHandler implements ItemListener, it must define method args[] ) itemStateChanged private class CheckBoxHandler implements ItemListener {getStateChange returns private int valBold = Font.PLAIN; ItemEvent.SELECTED or private int valItalic = Font.PLAIN; ItemEvent.DESELECTED public void itemStateChanged( ItemEvent e ) { if ( e.getSource() == bold ) if ( e.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; JRadioButton Radio buttons Have two states: selected and deselected Normally appear as a group Only one radio button in group selected at time Selecting one button forces the other buttons off Mutually exclusive options ButtonGroup - maintains logical relationship between radio buttons Class JRadioButton Constructor JRadioButton( "Label", selected ) If selected true, JRadioButton initially selected 35 RadioButton group border .. JPanel groupPanel = new JPanel(); groupPanel.setBounds(10,10,100,60); groupPanel.setBorder(BorderFactory.createLineBorder(Color.black) ); frame.getContentPane().add(groupPanel); groupPanel.add(new JRadioButton("Black")); groupPanel.add(new JRadioButton(“White")); .. 36 1 // Fig. 12.12: RadioButtonTest.java 2 // Creating radio buttons using ButtonGroup and JRadioButton. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class RadioButtonTest extends JFrame { 8 private JTextField t; 9 private Font plainFont, boldFont, 10 italicFont, boldItalicFont; 11 private JRadioButton plain, bold, italic, boldItalic; 12 private ButtonGroup radioGroup; 13 14 public RadioButtonTest() 15 { 16 super( "RadioButton Test" ); 1. import 17 18 Container c = getContentPane(); 1.1 Declarations 19 c.setLayout( new FlowLayout() ); Initialize radio buttons. 20 1.2 Initialization 21 t = new JTextField( "Watch the font style change", 25 ); selected. one is initially 22 c.add( t ); 23 24 // Create radio buttons 25 plain = new JRadioButton( "Plain", true ); 26 c.add( plain ); 27 bold = new JRadioButton( "Bold", false); 28 c.add( bold ); 29 italic = new JRadioButton( "Italic", false ); 37 30 c.add( italic ); Only 31 boldItalic = new JRadioButton( "Bold/Italic", false ); 32 c.add( boldItalic ); 33 34 // register events 35 RadioButtonHandler handler = new RadioButtonHandler(); 36 plain.addItemListener( handler ); 37 bold.addItemListener( handler ); 38 italic.addItemListener( handler ); 39 boldItalic.addItemListener( handler ); Create a ButtonGroup. Only one radio button in the group may be selected at a time. 40 41 // create logical relationship between JRadioButtons 42 radioGroup = new ButtonGroup(); 43 radioGroup.add( plain ); 44 radioGroup.add( bold ); 45 radioGroup.add( italic ); 46 radioGroup.add( boldItalic ); Method add adds radio buttons to the ButtonGroup 47 48 plainFont = new Font( "TimesRoman", Font.PLAIN, 14 ); 49 boldFont = new Font( "TimesRoman", Font.BOLD, 14 ); 50 italicFont = new Font( "TimesRoman", Font.ITALIC, 14 ); 51 boldItalicFont = 52 new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 ); 53 54 55 56 5738 58 t.setFont( plainFont ); setSize( 300, 100 ); show(); } JList List Displays series of items may select one or more items Class JList Constructor JList( arrayOfNames ) Takes array of Objects (Strings) to display in list setVisibleRowCount( n ) Displays n items at a time Does not provide automatic scrolling 39 COLORS There are 13 predefined colors You can access them using Color.x where x is orange, pink, cyan, magenta, yellow, black, blue, white, gray, lightGray, darkGray, red, green You can define your own colors Color ugly = new Color(30,90,120); //RGB(red-green-blue); values between 0-255; 40 Exercise 2: JPanels with color Set the background of the contentPane to white using <nameofobject>.setBackground(<color>); Create two JPanels in the constructor of Calc Set the background color of one to orange; set the background color of the other to yellow Add the two JPanels to the contentPane using <nameofobject>.add(<objecttobeadded>) add the orange JPanel first; NOTE: the order in which you add your objects determine the way your program looks 41 Exercise 2: Answer package swinglab; import java.awt.*; import javax.swing.*; public class Calc extends JFrame{ private JPanel entryPanel; private JPanel answerPanel; public Calc() { Container cp = getContentPane(); setDefaultCloseOperation(EXIT_ON_CLOSE); cp.setBackground(Color.white); setTitle("My Funky Calculator"); setSize(1000,700); entryPanel = new JPanel(); entryPanel.setBackground(Color.orange); answerPanel = new JPanel(); answerPanel.setBackground(Color.yellow); // . . . 42 Exercise 2: answer continued cp.add(entryPanel); cp.add(answerPanel); } public static void main (String[] args){ Calc trial = new Calc(); trial.setVisible(true); } } 43 Dialogbox JOptionPane JOptionPane.showMessageDialog(null,"Hello Melkamu"); ret=JOptionPane.showConfirmDialog(null,“how old are you?","Question",JOptionPane.YES_NO_OPTION); if(ret==JOptionPane.YES_OPTION) { } String s=JOptionPane.showInputDialog("answer :"); Advanced Control JScrollpane JTable JTree JMenuBar JToolBar 45 JScrollpane Provides a scrollable view of a lightweight component. A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and optional row and column heading viewports. ImageIcon img=new ImageIcon("baby.jpg"); JLabel lblImg=new JLabel(img); JScrollPane scimg=new JScrollPane(lblImg, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scimg.setPreferredSize(new Dimension(600, 500)); add(scimg); 46 JTable The JTable is used to display and edit regular two-dimensional tables of cells. 47 …continued DefaultTableModel dm=new DefaultTableModel(); dm.addColumn(“Firstname"); dm.addColumn(“Last Name"); dm.addColumn(“sex"); final JTable tbl=new JTable(dm); dm.addRow(new String[]{“Melkamu",“Alamwu",“Male"}); dm.addRow(new String[]{“abebe",“kebede",“male"}); dm.addRow(new String[]{“Aster",“ayana",“Female"}); JScrollPane sc=new JScrollPane(tbl); Container con=getContentPane(); con.setLayout(new BorderLayout()); con.add(sc,BorderLayout.CENTER); 48 JTable How to handle event : Mouse, Key from JTable? tbl.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseClicked(MouseEvent e) { int row=tbl.getSelectedRow(); int col=tbl.getSelectedColumn(); String s=(String)tbl.getValueAt(row, col); JOptionPane.showMessageDialog(null, s); }}); 49 JTable How to handle event : Mouse, Key from JTable? tbl.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) {} public void keyReleased(KeyEvent arg0) { int row=tbl.getSelectedRow(); int col=tbl.getSelectedColumn(); String s=(String)tbl.getValueAt(row, col); JOptionPane.showMessageDialog(null, s); } public void keyPressed(KeyEvent arg0) {} }); 50 …Continue dm.setRowCount(0); Clear all data from JTable dm.getRowCount(); Get total row from JTable 2 Ways to add new Row: dm.addRow( new String[]{"ID_002","Võ Tòng","32"}); Vector<String>vec=new Vector<String>(); vec.add("ID_003"); vec.add("Lâm Sung"); vec.add("30"); dm.addRow(vec); 51 JTree A control that displays a set of hierarchical data as an outline. DefaultMutableTreeNode root= new DefaultMutableTreeNode("ĐH Công Nghiệp"); final JTree tree=new JTree(root); DefaultMutableTreeNode cnttNode=new DefaultMutableTreeNode("Công Nghệ TT"); root.add(cnttNode); DefaultMutableTreeNode dhth1Node=new DefaultMutableTreeNode("Lớp ĐHTH1"); cnttNode.add(dhth1Node); 52 JTree-Event Handling tree.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseClicked(MouseEvent e) { Object o=tree.getLastSelectedPathComponent(); DefaultMutableTreeNode node=(DefaultMutableTreeNode)o; JOptionPane.showMessageDialog(null, node); } }); 53 JMenuBar JMenuBar menubar=new JMenuBar(); setJMenuBar(menubar); JMenu mnuFile=new JMenu("File"); JMenu mnuEdit=new JMenu("Edit"); menubar.add(mnuFile); menubar.add(mnuEdit); JMenuItem mnuFileNew=new JMenuItem("New"); JMenuItem mnuFileOpen=new JMenuItem("Open"); JMenuItem mnuFileExit=new JMenuItem("Exit"); mnuFile.add(mnuFileNew); mnuFile.add(mnuFileOpen); mnuFile.addSeparator(); mnuFile.add(mnuFileExit); 54 JMenuBar Handle event as the same JButton mnuFileExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); 55 JToolBar JToolBar toolBar=new JToolBar("MyBar"); JButton btn1=new JButton("New"); JCheckBox chk1=new JCheckBox("Checkme"); toolBar.add(btn1); toolBar.add(chk1); JButton btn2=new JButton("Exit"); toolBar.add(btn2); add(toolBar,BorderLayout.NORTH); 56 Thank You see you next class! 57