PART 23. Java GUI Advanced JList Component. more items.

Similar documents
Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

PART 22. Java GUI Library SWT GUI Library SWING GUI Library Swing First Program

DAFTAR LAMPIRAN. Source Code Java Aplikasi Keyword to Image Renamer Split

Based on slides by Prof. Burton Ma

Java: Graphical User Interfaces (GUI)

Chapter 12 GUI Basics

A Simple Text Editor Application

Graphical User Interface

Event Driven Programming

Introduction to the JAVA UI classes Advanced HCI IAT351

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Window Interfaces Using Swing Objects

More Swing. CS180 Recitation 12/(04,05)/08

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

COMP16121 Sample Code Lecture 1

Answer on question #61311, Programming & Computer Science / Java

1.00 Lecture 14. Lecture Preview

JAVA NOTES GRAPHICAL USER INTERFACES

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

JLayeredPane. Depth Constants in JLayeredPane

AP CS Unit 11: Graphics and Events

Java Help Files. by Peter Lavin. May 22, 2004

Graphical User Interfaces in Java - SWING

Swing Programming Example Number 2

Part 3: Graphical User Interface (GUI) & Java Applets

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Window Interfaces Using Swing Objects

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

SampleApp.java. Page 1

Chapter 13 Lab Advanced GUI Applications

C: THE PROGRAM Devin Kwok: Dossier 2008

Building Graphical User Interfaces. GUI Principles

Basics of programming 3. Java GUI and SWING

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Class 14: Introduction to the Swing Toolkit

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Building Graphical User Interfaces. Overview

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

CSCI 201L Midterm Written Summer % of course grade

PIC 20A GUI with swing

Chapter 9 Designing Graphical User Interfaces (GUIs)

Object-Oriented Software Engineering Re-exam, 2012 (Also Object-Oriented Analysis, Design and Programming, Re-exam, 2012)

Object-Oriented Programming Design. Topic : User Interface Components with Swing GUI Part III

Today. cisc3120-fall2012-parsons-lectiii.3 2

COMPSCI 230. Software Design and Construction. Swing

Java IDE Programming-I

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Inheritance (cont) Abstract Classes

Attempt FOUR questions Marking Scheme Time: 120 mins

Example: Building a Java GUI

Example: Building a Java GUI

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Introduction p. 1 JFC Architecture p. 5 Introduction to JFC p. 7 The JFC 1.2 Extension p. 8 Swing p. 9 Drag and Drop p. 16 Accessibility p.

Graphical interfaces & event-driven programming

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

APPENDIX. public void cekroot() { System.out.println("nilai root : "+root.data); }

JAVA NOTES GRAPHICAL USER INTERFACES

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

Chapter 6: Graphical User Interfaces

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Is image everything?

Lampiran A. SOURCE CODE PROGRAM

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

JFrame & JLabel. By Iqtidar Ali

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

CompSci 230 S Programming Techniques. Basic GUI Components

CSCI 201L Midterm Written SOLUTION Summer % of course grade

import java.applet.applet; import java.applet.audioclip; import java.net.url; public class Vjesala2 {

Swing. By Iqtidar Ali

Packages: Putting Classes Together

CSCI 201L Midterm Written SOLUTION Fall % of course grade

Graphical User Interfaces 2

1.1 GUI. JFrame. import java.awt.*; import javax.swing.*; public class XXX extends JFrame { public XXX() { // XXX. init() main() public static

Part I: Learn Common Graphics Components

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

Chapter 14. More Swing

Chapter 12 GUI Basics. Motivations. The design of the API for Java GUI programming

INSTITUTO POLITÉCNICO NACIONAL ESCUELA SUPERIOR DE CÓMPUTO

More Swing. Chapter 14. Chapter 14 1

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

TTTK Program Design and Problem Solving Tutorial 3 (GUI & Event Handlings)

Java Programming Lecture 6

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Swing. Component overview. Java UI, summer semester 2017/2018 1

Summary Chapter 25 GUI Components: Part 2

Transcription:

PART 23 Java GUI Advanced 23.1 JList Component JList is a component that displays a list of objects. It allows the user to select one or more items. import java.awt.color; import java.awt.eventqueue; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.border.emptyborder; import javax.swing.jlist; import javax.swing.listselectionmodel; import javax.swing.event.listselectionlistener; import javax.swing.event.listselectionevent; public class JListExample extends JFrame { private JPanel contentpane; String[] listcolornames = { "black", "blue", "green", "yellow","white" ; Color[] listcolorvalues = { Color.BLACK, Color.BLUE,Color.GREEN,Color.YELLOW, Color.WHITE; public JListExample() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 450, 300); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); final JList list = new JList(listColorNames); list.addlistselectionlistener(new ListSelectionListener() { public void valuechanged(listselectionevent e) { contentpane.setbackground(listcolorvalues[list.getselectedindex()]); ); list.setselectionmode(listselectionmodel.single_selection); list.setselectedindex(0); list.setbounds(109, 54, 144, 163); contentpane.add(list);

public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JListExample frame = new JListExample(); frame.setvisible(true); ); 23.2 JTextArea component A JTextArea is a multi-line text area that displays plain text. It is lightweight component for working with text. The component does not handle scrolling. For this task, we use JScrollPanecomponent. import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.border.emptyborder; import javax.swing.joptionpane; import javax.swing.jtextarea; import javax.swing.jbutton; import javax.swing.jscrollpane; import javax.swing.swingutilities; import java.awt.event.actionlistener; import java.awt.event.actionevent; public class JTextAreaExample extends JFrame { private JPanel contentpane; public JTextAreaExample() { setdefaultcloseoperation(jframe.exit_on_close); settitle("independence hymn"); setbounds(100, 100, 450, 300); contentpane = new JPanel();

contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); JScrollPane scrollpane = new JScrollPane(); scrollpane.setbounds(56, 11, 300, 177); contentpane.add(scrollpane); final JTextArea textarea = new JTextArea(); textarea.setwrapstyleword(true); textarea.setlinewrap(true); scrollpane.setviewportview(textarea); JButton btnnewbutton = new JButton("Show Me Text"); btnnewbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent arg0) { JOptionPane.showMessageDialog(null, textarea.gettext()); ); btnnewbutton.setbounds(156, 216, 141, 23); contentpane.add(btnnewbutton); public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JTextAreaExample frame = new JTextAreaExample(); frame.setvisible(true); ); The example shows a simple JTextArea component. JTextArea textarea = new JTextArea(); This is the constructor of the JTextArea component. textarea.setlinewrap(true); Make the lines wrapped, if they are too long to fit the width. textarea.setwrapstyleword(true); Here we specify, how is line going to be wrapped. In our case, lines will be wrapped at word boundaries, whitespaces. JScrollPane scrollpane = new JScrollPane(); scrollpane.setbounds(56, 11, 300, 177); contentpane.add(scrollpane); final JTextArea textarea = new JTextArea(); textarea.setwrapstyleword(true); textarea.setlinewrap(true);

scrollpane.setviewportview(textarea); To make the text scrollable, we put the JTextArea component into the JScrollPane component. 23.3 JEditorPane component JEditorPane is a kind of textarea which can display various text formats. By default, JEditorPane supports HTML and RTF (Rich Text Format). In practice, JEditorPane is typically used for displaying HTML only. JEditorPane also supports RTF but very limited. You can set content for JEditorPane in the following ways: Pass URL object or URL string into constructor of JEditorPane. Use setpage() method to set content of JEditorPane at runtime. Pass content as a String to the settext() method. To make JEditorPane read only, you use method seteditable(false). When displaying HTML document, JEditorPane can detect HTML links and which link user clicks. To handle the click event on links, you need to handle HyperlinkListener event.

In this example, we will create a very simple web browser to display any web page by using JEditorPane component. In this example, we are also using JButton and JTextField components. import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.border.emptyborder; import javax.swing.jlabel; import javax.swing.jtextfield; import javax.swing.jbutton; import javax.swing.jeditorpane; import javax.swing.jscrollpane; import javax.swing.swingutilities; import java.awt.event.actionlistener; import java.awt.event.actionevent; public class JEditorPaneExample extends JFrame { private JPanel contentpane; private JTextField textfield; public JEditorPaneExample() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 850, 517); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); JLabel lblurl = new JLabel("URL"); lblurl.setbounds(10, 11, 36, 14); contentpane.add(lblurl); textfield = new JTextField(); textfield.setbounds(56, 8, 688, 20); contentpane.add(textfield); textfield.setcolumns(10); JScrollPane scrollpane = new JScrollPane(); scrollpane.setbounds(10, 39, 800, 416); contentpane.add(scrollpane); final JEditorPane editorpane = new JEditorPane(); scrollpane.setviewportview(editorpane); JButton btnnewbutton = new JButton("GO"); btnnewbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent arg0) { try { editorpane.setpage(textfield.gettext()); catch (Exception ex) { ex.printstacktrace(); ); btnnewbutton.setbounds(754, 7, 56, 23); contentpane.add(btnnewbutton); public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JEditorPaneExample frame = new JEditorPaneExample();

); frame.setvisible(true); 23.4 Swing Dialogs Dialog windows or dialogs are an indispensable part of most modern GUI applications. A dialog is defined as a conversation between two or more persons. In a computer application a dialog is a window which is used to "talk" to the application. A dialog is used to input data, modify data, change the application settings etc. Dialogs are important means of communication between a user and a computer program. In Java Swing toolkit, we can create two kinds of dialogs. Custom dialogs standard dialogs Custom dialogs are created by the programmer. They are based on the JDialog class.

Standard dialogs predefined dialogs available in the Swing toolkit. For example MessageDialog, InputDialog, JColorChooser or JFileChooser. These are dialogs for common programming tasks like showing text, receiving input, loading and saving files etc. They save programmer's time and enhance using some standard behaviour. There are two basic types of dialogs. Modal and modeless. Modal dialogs does not allow input to other top level windows. An open file dialog is a good example of a modal dialog. While choosing a file to open, no other operation should be permitted. Modeless dialogs allow input to other windows. A typical modeless dialog is a find text dialog. 23.5 JFileChooser JFileChooser is a standard dialog for selecting a file from the file system. import java.awt.eventqueue; import javax.swing.jfilechooser; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.border.emptyborder; import javax.swing.filechooser.filefilter; import javax.swing.filechooser.filenameextensionfilter; import javax.swing.jbutton; import java.awt.event.actionlistener; import java.awt.event.actionevent; import java.io.file; import javax.swing.jeditorpane; public class JFileChooserExample extends JFrame { private JPanel contentpane; public JFileChooserExample() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 450, 300); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); final JEditorPane editorpane = new JEditorPane(); editorpane.setbounds(20, 50, 387, 187); contentpane.add(editorpane); JButton btnnewbutton = new JButton("Open File"); btnnewbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) {

JFileChooser fileopen = new JFileChooser(); FileFilter filter = new FileNameExtensionFilter("txt files", "txt"); fileopen.addchoosablefilefilter(filter); int answer = fileopen.showdialog(null, "Open file"); if (answer == JFileChooser.APPROVE_OPTION) { File file = fileopen.getselectedfile(); try { editorpane.setpage("file:///"+ file); catch (Exception e1) { e1.printstacktrace(); ); btnnewbutton.setbounds(10, 11, 89, 23); contentpane.add(btnnewbutton); public static void main(string[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { JFileChooserExample frame = new JFileChooserExample(); frame.setvisible(true); catch (Exception e) { e.printstacktrace(); ); The code example will demonstrate how to use a file chooser dialog in order to load file contents into the text area component. JFileChooser fileopen = new JFileChooser(); This is the constructor of the file chooser dialog. FileFilter filter = new FileNameExtensionFilter("txt files", "txt"); fileopen.addchoosablefilefilter(filter); Here we define the file filter. In our case, we will have txt files with extension.txt. We have also the default All files option. int answer = fileopen.showdialog(null, "Open file"); Here we show the file chooser dialog. Upon clicking on the open file button, the return value is equal to JFileChooser.APPROVE_OPTION. if (ret == JFileChooser.APPROVE_OPTION) {

File file = fileopen.getselectedfile(); try { editorpane.setpage("file:///"+ file); catch (Exception e1) { e1.printstacktrace(); Here we get the name of the selected file. We read the contents of the file and set the text into the editorpane. 23.6 JColorChooser

JColorChooser is a standard dialog for selecting a color. import javax.swing.jcolorchooser; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.swingutilities; import javax.swing.border.emptyborder; import javax.swing.jbutton; import javax.swing.border.lineborder; import java.awt.color; import java.awt.event.actionlistener; import java.awt.event.actionevent; public class JColorChooserExample extends JFrame { private JPanel contentpane; public JColorChooserExample() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 450, 300); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); final JPanel panel = new JPanel(); panel.setborder(new LineBorder(new Color(0, 0, 0))); panel.setbounds(67, 74, 220, 145); contentpane.add(panel); JButton btnnewbutton = new JButton("Choose Color"); btnnewbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { Color color = JColorChooser.showDialog(null, "Choose Color", Color.white); panel.setbackground(color); ); btnnewbutton.setbounds(10, 11, 111, 23); contentpane.add(btnnewbutton); public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JColorChooserExample frame = new JColorChooserExample(); frame.setvisible(true); ); In the example, we have a panel. We will change the background color of the panel by selecting a color from the color chooser dialog. Color color = JColorChooser.showDialog(null, "Choose Color", Color.white); panel.setbackground(color);

This code shows a color chooser dialog. The showdialog() method returns the selected color value. We change the display panel background to the newly selected color. 23.7 Menus in Java Swing A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus. In Java Swing, to implement a menubar, we use three objects. A JMenuBar, a JMenu and ajmenuitem. We begin with a simple menubar example. import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.imageicon; import javax.swing.jframe;

import javax.swing.jmenu; import javax.swing.jmenubar; import javax.swing.jmenuitem; import javax.swing.swingutilities; public class Example extends JFrame { public Example() { JMenuBar menubar = new JMenuBar(); ImageIcon icon = new ImageIcon(getClass().getResource("exit.png")); JMenu filemenu = new JMenu("File"); JMenuItem emenuitem = new JMenuItem("Exit", icon); emenuitem.addactionlistener(new ActionListener() { public void actionperformed(actionevent event) { System.exit(0); ); filemenu.add(emenuitem); menubar.add(filemenu); setjmenubar(menubar); settitle("simple menu"); setsize(300, 200); setlocationrelativeto(null); setdefaultcloseoperation(exit_on_close); public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Example ex = new Example(); ex.setvisible(true); ); Our example will show a menu with one item. Selecting the exit menu item we close the application. JMenuBar menubar = new JMenuBar(); Here we create a menubar. ImageIcon icon = new ImageIcon(getClass().getResource("exit.png")); We will display an icon in the menu.

23.8 JTable JTables are used to display data held in multi-dimensional arrays. This is useful for displaying players, customers, data from various sensor etc. The default model of a table displays the data you put in as a table with all the cells editable, as if it were in Microsoft Excel. Each cell is of the same size. To fill the table, we need arrays of data. The headings for the table is a simple String array, and the data in the table is a 2D Object Array. import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.swingutilities; import javax.swing.border.emptyborder; import javax.swing.jtable; import javax.swing.jscrollpane; public class JTableExample extends JFrame { private JPanel contentpane; private JTable table; // The data used as the titles for the table. String[] title = {"No.", "Country", "Player", "Position"; // The data used in the table, placed as a multi-dimensional array. Object[][] playerdata = { {4, "United States", "Sterling Davis", "Forward", {6, "Germany", "Moritz Wohlers", "Forward/Centre", {7, "United Kingdom", "Ross Hutton", "Centre", {8, "Belgium", "Hugo Sterk", "Guard", {10, "United Kingdom", "Andy Pearson", "Forward", {11, "United States", "Robert Yanders", "Guard", {12, "United Kingdom", "Graham Hunter", "Guard", {14, "United Kingdom", "Julius Joseph", "Guard/Forward", {15, "United Kingdom", "Gareth Murray", "Forward", {21, "United States", "Maurice Hampton", "Guard";

public JTableExample() { setdefaultcloseoperation(jframe.exit_on_close); setbounds(100, 100, 450, 300); contentpane = new JPanel(); contentpane.setborder(new EmptyBorder(5, 5, 5, 5)); setcontentpane(contentpane); contentpane.setlayout(null); JScrollPane scrollpane = new JScrollPane(); scrollpane.setbounds(35, 45, 344, 119); contentpane.add(scrollpane); table = new JTable(playerdata, title); scrollpane.setviewportview(table); public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { JTableExample frame = new JTableExample(); frame.setvisible(true); catch (Exception e) { e.printstacktrace(); ); The JTable itself is instantiated really easily. We pass the 2D array in, then the headings for the table. JTable table = new JTable(playerdata, title); We add the table to a scroll pane for two reasons: One reason is for scrolling, the other is: without scroll pane the headings aren't shown.