Title: More on GUI
1More on GUI
- We continue our examination of GUI features by
first revisiting JLabels and JButtons - As we saw last time, we can place a String into a
JLabel or JButton - We can also insert pictures instead of or in
addition to Strings - JLabel label1 new JLabel(image)
- JButton button1 new JButton(image)
- image must be an ImageIcon which you can create
by specifying the images location on disk (such
as ImageIcon image new ImageIcon(flag.gif) ) - You can include both text and image in a JButton
or JLabel by specifying both a String and then an
ImageIcon - JLabel label2 new JLabel(Left, new
ImageIcon(leftarrow.gif)) - You can change the item in the JButton or JLabel
using setText( ) or setIcon( ) as in
label1.setText() - You can also alter what appears in the JButton
based on whether the mouse is pointing at it
(called Rollover) or if the button is currently
being pressed - JButton button2 new JButton(icon1)
- button2.setPressedIcon(icon2)
- button2.setRolloverIcon(icon3)
2More Details
- For JButtons, JCheckBoxes and JRadioButtons, you
can also specify a key mnemonic or a tool tip
(pop-up box that instructs the user what the
JButton does) - For details, see the examples in sections
13.3-13.5 - You can align or position your text or image
inside a button or label - Horizontal alignments are LEADING, LEFT, CENTER,
RIGHT, TRAILING, vertical alignments are TOP,
CENTER, BOTTOM, use them like this - button.setHorizontalAlignment(SwingConstants.RIGHT
) - Text positions can be set the same way (they use
the same constants as the horizontal and vertical
alignments) - see pages 452-453 for examples
3Mouse Listeners
- We continue our examination of GUIs by looking at
how to interact with the mouse - Just as Java creates Events when the user
interacts with GUI components, similarly mouse
movements generate Events - To have your program respond, you must implement
MouseListeners and MouseMotionListeners - this is a bit more involved than the previous
listeners because there are 7 methods that must
be implemented between the two Listeners - Fortunately, we can implement most as empty
methods - public void mouseMoved(MouseEvent e) // does
nothing - We will often keep track of where the mouse is or
where it was and now where it has been moved to - Example When the mouse button is pressed,
remember its x and y coordinates, when the mouse
button is released, remember the new x and y
coordinates, now draw a line from (old x, old y)
to (new x, new y) - In such a way, we can build a paint type program
4Mouse Listeners and Methods
- We divide the Mouse listeners into
- MouseListener
- this Listener deals with mouse button operations
and must implement the following methods - mousePressed
- mouseReleased
- mouseClicked
- mouseEntered
- mouseExited
- when you hold down the mouse button or click the
mouse button, both mousePressed and mouseClicked
are called, when you release the mouse button or
click the mouse button, both mouseReleased and
mouseClicked are called - we wont be using mouseEntered or mouseExited
here - MouseMotionListener
- this listener deals with moving the mouse
- mouseMoved
- mouseDragged
- To specify that your program should listen for
mouse events, you will add a mouse listener or
motion listener as in - addMouseListener(this)
- addMouseMotionListener(this)
5Example Drawing a line
- Here, we see how to use the MouseListener to draw
a line on a JPanel when the mouse is dragged - As usual, we have created a JFrame which itself
adds the JPanel below (MouseExample) to its
contents
public class MouseExample extends
JPanel implements MouseListener
private int x1, x2, y1, y2 public
MouseExample( ) x1 x2 y1 y2
0 addMouseListener(this) public void
mousePressed(MouseEvent e) x1 e.getX(
) y1 e.getY( )
public void mouseReleased(MouseEvent e) x2
e.getX( ) y2 e.getY( ) repaint( )
public void paintComponent(Graphics g)
g.setColor(Color.black) g.drawLine(x1, y1, x2,
y2) // end class
We would also implement mouseEntered,
mouseExited and mouseClicked as
6Example 2 Drawing dots
- Here, we place a dot every time you drag the mouse
public class DotDrawer extends JPanel implements
MouseMotionListener private static int x,
y public DotDrawer( ) x y
0 addMouseMotionListener(this)
public void mouseDragged(MouseEvent e)
x e.getX( ) y e.getY( ) repaint( )
public void mouseMoved(MouseEvent e)
public void paintComponent(Graphics g)
super.paintComponent(g) g.setColor(Color.blue)
g.fillOval(x-1, y-1, 2, 2) // end class
7KeyListener and Keyboard Events
- Just as we can implement listeners to handle
mouse events, we can do the same for keyboard
events (keypresses) - To implement KeyListener, you must implement
three methods keyPressed, keyReleased and
keyTyped - all three methods receive a KeyEvent
- to determine which key was pressed you can pass
the event the message getKeyChar( ) - In order for your Java program to watch for key
presses, you also have to get your container
(probably a JPanel) to watch the keyboard, this
is done by saying - panel.setFocusable(true)
- We will look at code that uses KeyListener to
implement a typewriter and an etch-a-sketch
type program - you might also use KeyListener for a computer
game where the user uses the keyboard to control
movement in the game
8Multiple Listeners
- So far we have concentrated on implementing a
single Listener in our GUI program - several GUI items are handled by the one Listener
- We can implement multiple listeners instead if
desired - consider implementing different Listeners for two
JButtons - now we cant just do b1.addActionListener(this)
and b2.addActionListener(this) - this would require that b1 and b2 both implement
their listeners in this class by having the
actionPerformed method implemented here, but we
cant have 2 of these in the same class, so
instead - we create new inner classes that will implement
our action Listeners - b1.addActionListener(new ListenerClass1( ))
- b2.addActionListener(new ListenerClass2( ))
- Just as earlier we implemented an inner class to
extend a JPanel, we will implement an inner class
which implements ActionListener - this inner class will only contain one method,
actionPerformed
9Handling CheckBox/RadioButtons
- These GUI components when changed will generate
both ActionEvents and ItemEvents - You can handle this through an ActionListener or
an ItemListener - If your GUI already has JButtons though, since
they cause ActionEvents, it might be better to
have CheckBox and RadioButton components handled
by an ItemListener - This requires adding implements ItemListener to
the class header, adding the listener to each GUI
object such as checkBox1.addItemListener(this)
and implementing the ItemListener class - if you implement the ItemListener in this class,
then you merely have to add a itemStateChanged
method - you can also determine what state one of these
items is in by using isSelected( ) which returns
true or false, you can also change the setting by
using setSelected(true) or setSelected(false)
10Example Multiple Handlers
private JCheckBox j1, j2, j3 private
JRadioButton r1, r2, r3 private JLabel lab new
JLabel( ) public
GUIExample( ) // instantiate the 6 GUI
items j1.addItemListener(new ItemListener1(
)) j2.addItemListener(new ItemListener1(
)) j3.addItemListener(new ItemListener1(
)) r1.addItemListener(new ItemListener2(
)) r2.addItemListener(new ItemListener2(
)) r3.addItemListener(new ItemListener2(
)) // add items and lab to
JPanel private class ItemListener1 implements
ItemListener public void
itemStateChanged(ItemEvent e) if(e.getItem(
) j1) lab.setText(j1.getText( )) else
if(e.getItem( ) j2) lab.setText(j2.getText(
)) else if(e.getItem( ) j3)
lab.setText(j3.getText( ))
private class ItemListener2 implements
ItemListener public void
itemStateChanged( ItemEvent e)
if(e.getItem( ) r1) lab.setText(r1.getText(
)) else if(e.getItem( ) r2)
lab.setText(r2.getText( )) else
if(e.getItem( ) r3) lab.setText(r3.getText(
))
11Lists
- There are three GUI components that allow you to
create lists for the user to select from - JList a list of items is presented, the user
can select any combination (0 or more items) - JComboBox a list of items is made available
through a drop box, the user selects exactly one
item - JMenu same as the JComboBox except that the
menu is attached to the title bar - we wont be using JMenus here
- To set up a list, you have to specify the items
to appear in the list as an array of Strings - once set up, you can determine what item(s)
has(have) been selected (what String) or what
position(s) was(were) selected, or change the
selection(s) - the JList is a little trickier because multiple
items can be selected, so you have to be able to
check to see if a given item was selected rather
than find the item selected or obtain the entire
list of selected items as an array
12JComboBox Example
- Here we have code that creates a JFrame that
consists of a JComboBox and a JLabel - when an item is selected in the JComboBox, the
item selected is output in the JLabel
public void itemStateChanged(ItemEvent
e) if(jcb.getSelectedIndex( )!0)
lab.setText("Selection "
(String)jcb.getSelectedItem( )) else
lab.setText("Selection")
private JComboBox jcb private JLabel lab public
ListExample() String list Select an
Item, , , jcb new
JComboBox(list) lab new JLabel("Selection
") jcb.addItemLis
tener(this) JPanel panel new JPanel(new
GridLayout(1, 2)) panel.add(jcb) panel.add(
lab) getContentPane( ).add(panel)
Notice the extra space here, why do you suppose
it is needed?
getSelectedItem( ) does not return a String, but
instead returns an Object, since the items are
Strings, we have to cast it as a String
before using it in the setText operation