Designing User Interfaces with Swing Designing User Interfaces
Download
Report
Transcript Designing User Interfaces with Swing Designing User Interfaces
Java Programming Language
Designing User Interfaces
with Swing
Designing User Interfaces with Swing
Designing User Interfaces with Swing
Introduction
Layout Management
Panels
Text Input
Text Area
Labels
Making Choices
Lists
Advanced Layout Management
Menu
Scroll Bars
Dialog Boxes
Java Programming Language
2
Designing User Interfaces with Swing
Designing User Interfaces with Swing
Java Swing provides various building block called
components such as button,list box,check box, etc.
for designing GUI.
The same user interface components are used to
build both stand-alone programs and applets
– every graphics application uses a class derived from the
JFrame class to describe top-level window
– every applet uses a class derived form theJApplet class to
describe top-level window
Steps to design/code GUI.
1. make the components in the user interface look
2. position(layout) the user interface components
3. handle user input(events)
Java Programming Language
3
Designing User Interfaces with Swing
Swing Component Inheritance
Hierarchy
JButton
Object
Component
JComponent
Abstract
Button
JMenuItem
JComboBox
JToggleButton
JLabel
JCheckBox
JList
JRadioButton
JMenuBar
JOptionPane
Container
JPanel
JScrollBar
JTextComponent
JTextField
JTextArea
Window
Java Programming Language
Frame
JFrame
Dialog
JDialog
4
Designing User Interfaces with Swing
Model-View-Controller Pattern
A good design pattern to design an application
using graphical user interfaces
A basic architecture of swing components
Model-view-controller pattern
– the model, which stores the contents
– the view, which displays the contents
– the controller, which handles user input
1:user input 2:update
(visual only)
:Controller
4: get
data
:View
3:notifies to update
2:update
:Model
Java Programming Language
5
Designing User Interfaces with Swing
Applying MVC Pattern
Example: Bank Application
1.user input
Deposit
2.notify
event
BalanceView1
5a.update
3.get data
Controller
for Deposit
Text Field
BalanceView2
5b.update
6a.
get
data
6b. get data
4. update
balance
Balance Data
Java Programming Language
6
Designing User Interfaces with Swing
Layout Management
Layout Manager help arrange the various
components you wish to add to a container
Types of Layout Managers
–
–
–
–
FlowLayout(default at JPanel and Applet)
BorderLayout(default at the contentPane of JFrame)
GridLayout
etc
Instead you do not specify absolute position for
interface components, you specify a general rule
for the layout (Platform independent)
Java Programming Language
7
Designing User Interfaces with Swing
Layout Management
Flow Layouts
– alignment options and horizontal and vertical gaps
FlowLayout.LEFT
FlowLayout.CENTER (default)
FlowLayout.RIGHT
new FlowLayout(FlowLayout.LEFT)
new FlowLayout(FlowLayout.LEFT, 10,10)
Border Layout
– five areas
North
West
Center
East
South
If none of the layout schemes fit your needs,
break the surface of your window into separate
panels, and lay out each panel separately.
Java Programming Language
8
Designing User Interfaces with Swing
Layout Management
Example
public class BorderLayoutTest extends JFrame
{ public BorderLayoutTest()
{ setTitle("BorderLayoutTest");
JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.LEFT));
p.add(new JButton("Left"));
p.add(new JButton("Right"));
p.add(new JButton("Up"));
p.add(new JButton("Down"));
p.add(new JButton("Close"));
Container contentPane = getContentPane();
contentPane.add("North", p);
contentPane.add("East", new JScrollbar(Adjustable.VERTICAL));
contentPane.add("South", new JScrollbar(Adjustable.HORIZONTAL));
}
Java Programming Language
9
Designing User Interfaces with Swing
Panels
Panels act as(smaller) containers for interface
elements and can themselves be arranged inside
the window.
Panel allows more precise method of locating
element(hierarchical layers)
Steps to use a Panel
– build up a panel the way you want it to look
– then add the panel to the window
Example
Java Programming Language
10
Designing User Interfaces with Swing
Panels
Code fragment for the example
public class PanelTest extends JFrame implements ActionListner
{ public PanelTest()
{ setTitle("PanelTest");
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
tick = new JButton(“Tick”);
tick.addActionListner(this);
p.add(new JButton("Tick"));
reset = new JButton(“Reset”);
reset.addActionListner(this);
p.add(new JButton("Reset"));
close = new JButton(“Close”);
close.addActionListner(this);
p.add(new JButton("Close"));
clock = new ClockPanel();
Container contentPane = getContentPane();
contentPane.add("South", p);
contentPane.add(“Center”, clock);
// rest of constructor code
}
//rest of the panel test code goes here
private JButton tick, reset, close;
private ClockPanel clock;
}
Java Programming Language
11
Designing User Interfaces with Swing
Event Handling
Class Diagram
JFrame
JPanel
Panel
Test
contentPane:
Container
1
Clock
Panel
3
JButton
1
JPanel
listner
Collaboration Diagram(event handling)
1.click
button
Button:tick
2. actionPerformed
Action
Listener
aPanelTest 3. tick
Java Programming Language
Clock
Panel:
clock
12
Designing User Interfaces with Swing
Event Handling
import java.awt.*;
import java.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class PanelTest extends JFrame implements ActionListner
{ public PanelTest()
{ setTitle("PanelTest");
// ...
}
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
if(source==tick)
clock.tick();
else if(source==reset)
clock.reset();
else if(source==close)
System.exit(0);
}
}
Java Programming Language
13
Designing User Interfaces with Swing
Clock
class ClockPanel extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
g.drawOval(0, 0, 100, 100);
double hourAngle
= 2 * Math.PI * (minutes - 3 * 60) / (12 * 60);
double minuteAngle
= 2 * Math.PI * (minutes - 15) / 60;
g.drawLine(50, 50,
50 + (int)(30 * Math.cos(hourAngle)),
50 + (int)(30 * Math.sin(hourAngle)));
g.drawLine(50, 50,
50 + (int)(45 * Math.cos(minuteAngle)),
50 + (int)(45 * Math.sin(minuteAngle)));
}
public void tick()
{ minutes++;
repaint();
}
public void reset()
{ minutes=0;
repaint();
}
private int minutes = 0;
}
Java Programming Language
14
Designing User Interfaces with Swing
Text Input
Text input components
– text field – single line input
– text area – multiple lines of text
Text Component Classes
– A text component has a document as model (MVC)
– the document fires an document event (DocumentEvent)
when the document changes
– you can listen the document event using document
listener(DocumentListener)
Java Programming Language
15
Designing User Interfaces with Swing
Text Fields
Text Fields
– A text field is a basic text control that lets the user enter a
small amount of text.
– When the user indicates that text entry is complete
(usually by pressing Return), the text field fires an action
event (ActionEveent)
Example(JTextField) : Clock
Java Programming Language
16
Designing User Interfaces with Swing
Text Fields
Event Handling (using document listener)
TextField
:hourField
1. update
2. insertUpdate or removeUpdate
Document
Listener
Clock
Panel:
clock
Document and DocumentListener
–
–
:aClockField
3. setTime
Listener
Document : the model of all text components
textField.getDocument().addDocumentListener(listener);
Implementing DocumentListener
// in the frame class
private class ClockFieldListener implements DocumentListener
{
public void insertUpdate(DocumentEvent e) { setClock(); }
public void removeUpdate(DocumentEvent e) { setClock(); }
public void changedUpdate(DocumentEvent e) {}
}
Java Programming Language
17
Designing User Interfaces with Swing
Text Fields
Creating Text Fields
class TextTestFrame extends JFrame
{
public TextTestFrame()
{
setTitle("TextTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
Container contentPane = getContentPane();
DocumentListener listener = new ClockFieldListener();
// add a panel with text fields
JPanel panel = new JPanel();
hourField = new JTextField("12", 3);
panel.add(hourField);
hourField.getDocument().addDocumentListener(listener);
minuteField = new JTextField("00", 3);
panel.add(minuteField);
minuteField.getDocument().addDocumentListener(listener);
contentPane.add(panel, BorderLayout.SOUTH);
// add the clock
clock = new ClockPanel();
contentPane.add(clock, BorderLayout.CENTER);
}
Java Programming Language
18
Designing User Interfaces with Swing
Text Fields
// within the class TextTestFrame
public void setClock()
{
try
{
int hours
= Integer.parseInt(hourField.getText().trim());
int minutes
= Integer.parseInt(minuteField.getText().trim());
clock.setTime(hours, minutes);
}
catch (NumberFormatException e) {}
// don't set the clock if the input can't be parsed
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
private JTextField hourField;
private JTextField minuteField;
private ClockPanel clock;
Java Programming Language
19
Designing User Interfaces with Swing
Text Fields
class ClockPanel extends JPanel
{
public void paintComponent(Graphics g)
{
// draw the circular boundary
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Ellipse2D circle
= new Ellipse2D.Double(0, 0, 2 * RADIUS, 2 * RADIUS);
g2.draw(circle);
// draw the hour hand
double hourAngle = Math.toRadians(90 - 360 * minutes / (12 * 60));
drawHand(g2, hourAngle, HOUR_HAND_LENGTH);
// draw the minute hand
double minuteAngle = Math.toRadians(90 - 360 * minutes / 60);
drawHand(g2, minuteAngle, MINUTE_HAND_LENGTH);
}
public void drawHand(Graphics2D g2, double angle, double handLength)
{
Point2D end = new Point2D.Double(RADIUS + handLength * Math.cos(angle),
RADIUS - handLength * Math.sin(angle));
Point2D center = new Point2D.Double(RADIUS, RADIUS);
g2.draw(new Line2D.Double(center, end));
}
public void setTime(int h, int m)
{
minutes = h * 60 + m;
repaint();
}
private
private
private
private
double
double
double
double
minutes = 0;
RADIUS = 100;
MINUTE_HAND_LENGTH = 0.8 * RADIUS;
HOUR_HAND_LENGTH = 0.6 * RADIUS;
}
Java Programming Language
20
Designing User Interfaces with Swing
Text Areas
Text area displays multiple lines of text and allows
the user to edit the text with the keyboard and
mouse.
JTextArea textArea = new JTextArea( "This is an editable
JTextArea " + "that has been initialized with the setText
method. "
+ "A text area is a \"plain\" text component, "
+ "which means that although it can display text "
+ "in any font, all of the text is in the same font." );
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
A text area is typically managed by a scroll pane
– If you put a text area in a scroll pane, be sure to set the
scroll pane's preferred size or use a text area constructor
that sets the number of rows and columns for the text area
JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setPreferredSize(new Dimension(250, 250));
In the JTextArea, changes are broadcasted from
the model via a DocumentEvent to
DocumentListeners
Java Programming Language
21
Designing User Interfaces with Swing
Text Areas
Example : TextEditTest
– creating text area with scroll pane
textArea = new JTextArea(8, 40);
textArea.setText ("The quick brown fox jumps over
the lazy dog.");
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane, BorderLayout.CENTER);
Java Programming Language
22
Designing User Interfaces with Swing
Text Areas
Event Handling
JButton replaceButton = new JButton("Replace");
panel.add(replaceButton);
eplaceButton.addActionListener(new ReplaceAction());
...
private class ReplaceAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String f = from.getText();
int n = textArea.getText().indexOf(f);
if (n >= 0 && f.length() > 0)
textArea.replaceRange(to.getText(), n,
n + f.length());
}
}
Java Programming Language
23