Mouse Listeners and Mouse details



GUI IV

This set of notes needs a lot of work

Advanced ActionListeners

|ActionListener | |actionPerformed(ActionEvent e) |

|FocusListener |check if component has gained or lost focus |focusGained(FocusEvent e) |

| | |focusLost(FocusEvent e) |

|ItemListener | |itemStateChange(ItemEvent e) |

|KeyListener |listens for keys to be pressed on the keyboard |keyPressed(KeyEvent e) |

| | |keyReleased(KeyEvent e) |

| | |keyTyped(KeyEvent e) |

|MouseListener |listens for mouse button events and clicks |mouseClicked(MouseEvent e) |

| | |mouseEntered(MouseEvent e) |

| | |mouseExited(MouseEvent e) |

| | |mousePressed(MouseEvent e) |

| | |mouseReleased(MouseEvent e) |

|MouseMotionListener |listens for mouse movement and dragging | |

|MouseWheelListener |track movement of the mouse wheel | |

|TextListener | |textValueChanged(TextEvent e) |

|WindowListener |listen for changes in the state of the window such as|windowActivated(WindowEvent e) |

| |closing, opening, minimizing, and maximizing | |

| | |windowClosed(WindowEvent e) |

| | |windowClosing(WindowEvent e) |

| | |windowDeactivated(WindowEvent e) |

| | |windowDeactivated(WindowEvent e) |

| | |windowDeiconified(WindowEvent e) |

| | |windowIconified(WindowEvent e) |

| | |windowOpened(WindowEvent e) |

MouseListener and Details

|Full MouseListener Example |

|private class LupersMouseListener implements MouseListener |

|{ |

|public void mouseClicked(MouseEvent e){ button.setText("V");}// { DialogBox } |

|public void mouseEntered(MouseEvent e) |

|{ setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); } |

|public void mouseExited(MouseEvent e) |

|{ setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } |

|public void mousePressed(MouseEvent e){ button.setText("pressed"); } |

|public void mouseReleased(MouseEvent e){ button.setText("released"); } |

|} |

• A single component can be added to SEVERAL listeners!!

Button1.addActionListener(this);

Button1.addMouseListener(this);

Cursor Types Mouse

• You can change how the cursor looks

o in general

o or OVER an object (in listener)

setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));

setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

|Cursor Types |

|CROSSHAIR_CURSOR |

|DEFAULT_CURSOR |

|HAND_CURSOR |

|MOVE_CURSOR |

|TEXT_CURSOR |

|WAIT_CURSOR |

Mouse Coordinates

| | |

|public void mousePressed(MouseEvent m) | |

|{ | |

| | |

|int x = m.getX(); | |

|int y = m.getY(); | |

| | |

|OR | |

| | |

|int x = m.getPoint().x; | |

|int y = m.getPoint().y; | |

|} |// Where would 0,0 be on a Panel? Do below to find out. |

In the GUI IV Example code, add in the actionListener add a message box to display where the mouse was click within the frame.

KeyListener and Details

• Listens for a key pressed on the keyboard when the cursor IS IN A TEXTBOX or TEXTAREA!!!

• Not for listening for keys to be pressed!! (linked to textbox!!)

o Some will want to be able to use hot keys for this feature

o This is not it!!

• added to a JTEXTFIELD or JTEXTAREA

textBox1.addKeyListener(new KeyListenerTester());

|Example KeyListener Class |

|import java.awt.event.KeyEvent; |

|import java.awt.event.KeyListener; |

|import javax.swing.JLabel; |

|import javax.swing.JPanel; |

|import javax.swing.JTextField; |

| |

|public class KeyListenerExample extends JPanel |

|{ |

|JLabel l1 = new JLabel("Key Listener!"); |

|JTextField t1 = new JTextField(5); // or TextArea |

| |

|KeyListenerExample() |

|{ |

|this.setSize ( 200,100 ); |

|JPanel p =new JPanel(); |

|p.add(l1); |

|p.add(t1); // had to add text field to JPanel in order to work |

|this.add(p); |

| |

|t1.addKeyListener (new KeyListenerTester()) ; |

|// adding the keyListener to the textFIeld |

|} |

| |

|private class KeyListenerTester implements KeyListener |

|{ |

|// had to import java.awt.event.KeyListener; for THIS CLASS |

|// had to import java.awt.event.KeyEvent; for the functions below |

|public void keyTyped ( KeyEvent e ){ l1.setText("Key Typed"); } |

|public void keyPressed ( KeyEvent e) |

|{ |

|l1.setText ( "Key Pressed" ) ; |

| |

|String locationString = "key location: "; |

|int location = e.getKeyLocation(); |

| |

|if (location == KeyEvent.KEY_LOCATION_STANDARD) |

|{ locationString += "standard"; } |

|else if (location == KeyEvent.KEY_LOCATION_LEFT) |

|{ locationString += "left"; } |

|else if (location == KeyEvent.KEY_LOCATION_RIGHT) |

|{ locationString += "right"; } |

|else if (location == KeyEvent.KEY_LOCATION_NUMPAD) |

|{ locationString += "numpad"; } |

|else // (location == KeyEvent.KEY_LOCATION_UNKNOWN) |

|{ locationString += "unknown"; } |

| |

|System.out.println(locationString); |

| |

|} |

|public void keyReleased ( KeyEvent e ){ l1.setText( "Key Released" ) ; } |

|} |

|} |

Menus

• Creating a Menu for a window can be done using Swing

• Please DESIGN your menu first before creating the code

• much like a JPanel

• CAN ONLY BE ADDED TO A JFRAME!

o this part REALLY stinks

• There are three datatypes that are associated with Menus

o JMenuBar

▪ like a JPanel added to JFrame

▪ JMENU added to this (And only JMenu)

o JMenu -> “Menu Option”

▪ top menu option/heading

▪ viewable at all times, like “File” above

▪ can have several JMenus’ IN A JMenuBar

▪ ALL other options are ADDED to JMenu

▪ CAN HAVE AN ICON as well

o JMenuItem

▪ Options added to JMenu heading

▪ added to a specific JMenu

• Add items together like JPanels and JButtons

|Initial variable creation of the Menu IN ORDER |

|private JMenuBar MenuBar = new JMenuBar(); |// create JMenuBar |

|private JMenu file = new JMenu("File"); |// create all headers |

|private JMenuItem NewItem = new JMenuItem("New"); |// create OPTION for that header |

|private JMenuItem SaveItem = new JMenuItem("Save As New"); | |

|private JMenuItem ExitItem = new JMenuItem("Exit"); | |

| | |

|//in class constructor | |

|{ | |

| | |

|file.add(NewItem); |// adding menuitems to menu |

|file.add(SaveItem); | |

|file.add(ExitItem); | |

|// MUST BE COMPLETED IN ORDER | |

|MenuBar.add(file); |// add the menu to the MenuBar |

| | |

|setJMenuBar(MenuBar); // adds menu to the frame |// add MenuBar to JFrame |

|// DRAW WHAT THIS MENU WOULD LOOK LIKE | |

• since it can only be added to a JFrame we have to change what we have been doing slighty

Menu’s new Setup

• little simpler here

|Menu’s Driver |

|import javax.swing.*; |

|public class ListenerDriver |

|{ |

| |

|public static void main(String[] args) |

|{ |

|Listener window = new Listener(“Lupoli’s Listener Example”); |

|window.pack(); // has to be there, otherwise all you see is the titlebar of the GUI |

|window.setVisible(true); |

|} |

|} |

• the JFrame’s class has A LOT of listenerers

o Mouse

o Key

o Menu

|Menu’s JFrame Class and Creatation |

|import java.awt.Dimension; |

|import java.awt.event.*; |

|import java.awt.*; |

|import javax.swing.*; |

| |

|public class Listener extends JFrame implements ActionListener |

|{ |

|private JButton button = new JButton("Hit me"); |

|private JTextField text = new JTextField("Hit me"); |

|// Menu items |

|private JMenuBar MenuBar = new JMenuBar(); |

|private JMenu file = new JMenu("File"); |

|private JMenuItem NewItem = new JMenuItem("New"); |

|private JMenuItem SaveItem = new JMenuItem("Save As New"); |

|private JMenuItem ExitItem = new JMenuItem("Exit"); |

| |

|Listener(String title) |

|{ |

|setTitle(title); // sets the title |

|setLayout(new FlowLayout()); // a must!! |

|add(button); |

|add(text); |

|setPreferredSize(new Dimension(300,300)); |

|button.addMouseListener(new LupersMouseListener()); |

|text.addKeyListener(new LupersKeyListener()); |

|// Menu |

|file.add(NewItem); NewItem.addActionListener(this); |

|file.add(SaveItem); SaveItem.addActionListener(this); |

|file.add(ExitItem); ExitItem.addActionListener(this); |

| |

|MenuBar.add(file); |

| |

|setJMenuBar(MenuBar); |

|} |

| |

|private class LupersMouseListener implements MouseListener |

|{ |

|public void mouseClicked(MouseEvent e){ button.setText("V");} |

|public void mouseEntered(MouseEvent e) |

|{ setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); } |

|public void mouseExited(MouseEvent e) |

|{ setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } |

| |

|public void mousePressed(MouseEvent e){ button.setText("pressed"); } |

|public void mouseReleased(MouseEvent e){ button.setText("released"); } |

|} |

| |

|private class LupersKeyListener implements KeyListener |

|{ |

|public void keyTyped(KeyEvent e) |

|{ |

|char c = e.getKeyChar(); |

|System.out.println(c); |

|} |

| |

|public void keyPressed(KeyEvent e) { } |

|public void keyReleased(KeyEvent e) { } |

|} |

| |

|public void actionPerformed(ActionEvent e) // ActionListener for the Menu |

|{ |

|String action = e.getActionCommand(); |

|if(action.equals("Exit")) |

|{ text.setText("Exiting");} |

|} |

|} |

|[pic] |

1. Add to the Menu (under File) that will contain the option “RESET”, where the textbox AND button will show “Hit me”

2. Have the EXIT menu shut down the application using System.exit(0);

3. Add a new “menu” Flow Rates (will be beside File).

4. UNDER “Flow Rates” have SET WEST RATE, SET EAST RATE, SET SOUTH RATE, SET NORTH RATE.

Other Menu details

• There are other neat items you can add to menus

• Separators

o horizontal bar that can separate options within a menu

o must be added IN ORDER like the other menu items

o can ONLY be added to a JMenu

|file.add(NewItem); NewItem.addActionListener(this); |

|file.addSeparator(); |

|file.add(SaveItem); SaveItem.addActionListener(this); |

|file.addSeparator(); |

|file.add(ExitItem); ExitItem.addActionListener(this); |

• Hot Keys!!

o have to hit and some letter

o SHOULD MATCH A LETTER WITHIN THE OPTION

o Underlines option automatically

o can be used for BOTH

▪ JMenu

▪ JMenuItem

|file = new JMenu("File"); |

|file.setMnemonic(KeyEvent.VK_F); // F matches “file” |

|ExitItem.setMnemonic(KeyEvent.VK_E); // F matches ExitItem (under File) |

// Add a few Separators and a Hot Key for EXIT to your code

Sound in GUI Application

• thank you Lewis Brant UMBC F12

| |

|import java.awt.Color; |

|import java.awt.Dimension; |

|import java.awt.FlowLayout; |

|import java.awt.Font; |

|import java.awt.GridLayout; |

|import java.awt.event.ActionEvent; |

|import java.awt.event.ActionListener; |

| |

|import javax.sound.sampled.AudioFormat; |

|import javax.sound.sampled.AudioInputStream; |

|import javax.sound.sampled.AudioSystem; |

|import javax.sound.sampled.Clip; |

|import javax.sound.sampled.DataLine; |

| |

|import javax.swing.BorderFactory; |

|import javax.swing.ImageIcon; |

|import javax.swing.JLabel; |

|import javax.swing.JPanel; |

| |

|//import com.sun.java.util.jar.pack.Package.File; |

|import java.io.*; |

|/** |

|* GUIIII |

|* @version 10/16/12 |

|* @author Lewis Brant |

|* @class CMSC331 - Lupoli |

|* @homework - Event Programming Week 2 |

|* NOTE FOR TA: Some buttons and formatted output not implemented |

|* they were not required for this assignment. |

|* has full functionality for * + - / = ON/C and CE operations |

|* also this calculator simulates windows calculator-like |

|* this was also not required... |

|* also note that my layout was approved by Lupoli |

|*/ |

|public class GUIIII extends JPanel{ |

|private CalcButton CBMatrix[][]; |

|private boolean hasDecimal = false; |

|private boolean hasOperation = false; |

|private boolean isClear = true; |

|private boolean lastEquals = false; |

|private boolean inputFlag; |

|private char operation; |

|private String calcDisp = "0"; |

|//image for right of Calculator |

|private final ImageIcon awesome = new ImageIcon("awesomeocal.jpg"); |

|//image for the JLabel of Calc Display |

|private final ImageIcon JLCalcDispBkrd = new ImageIcon("JCDBkrd.jpg"); |

|private final static int finalRowLength = 3; |

|private final static int finalColLength = 8; |

|private final static int maxDisplayLength = 8; |

|private JPanel gridPanel = new JPanel(); |

|private JPanel textPanel = new JPanel(); |

|private JPanel graphicPanel = new JPanel(); |

|private JLabel JLGraphic = new JLabel(); |

|private JLabel JLCalcDisp = new JLabel(strToDisp(calcDisp)); |

|private double firstInput; |

|private double secondInput; |

|//private double memory; //to be implemented later for memory |

|//not required for this project |

| |

| |

| |

|/** |

|* GUIIII Constructor |

|* @Precondition none |

|* @Postcondition: a new GUI calculator constructed |

|* @param none |

|*/ |

|GUIIII(){ |

|setCBMatrix(); |

|this.setBackground(Color.green); |

|hasDecimal = false; |

|gridPanel.setLayout(new GridLayout(3, 8, 10, 10)); |

|gridPanel.setBackground(Color.green); |

|JLGraphic.setIcon(awesome); |

|JLCalcDisp.setFont(new Font("sansserif", Font.BOLD, 40)); |

|JLCalcDisp.setIcon(JLCalcDispBkrd); |

|JLCalcDisp.setPreferredSize(new Dimension(320,80)); |

|JLCalcDisp.setHorizontalTextPosition(JLabel.CENTER); |

|this.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 10)); |

|this.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); |

|graphicPanel.setPreferredSize(new Dimension(160,270)); |

|graphicPanel.add(JLGraphic); |

|graphicPanel.setBackground(Color.green); |

|this.add(graphicPanel); |

|textPanel.setPreferredSize(new Dimension(320,270)); |

|textPanel.add(JLCalcDisp); |

|textPanel.setBackground(Color.green); |

|this.add(textPanel); |

|for (int x = 0; x < finalRowLength; x++){ |

|for (int y = 0; y < finalColLength; y++){ |

|gridPanel.add(CBMatrix[x][y]); } |

|} |

|this.add(gridPanel); |

| |

|for (int x = 0; x < finalRowLength; x++){ |

|for (int y = 0; y < finalColLength; y++){ |

|CBMatrix[x][y].addActionListener(new ButtonListener()); } |

|} |

| |

|//audioplay courtesy of |

|/* |

|how-to-play-wav-files-with-java */ |

|try { |

|File awesomeGreeting = new File("greetings.wav"); |

|AudioInputStream stream; |

|AudioFormat format; |

| info; |

|Clip clip; |

| |

|stream = AudioSystem.getAudioInputStream(awesomeGreeting); |

|format = stream.getFormat(); |

|info = new (Clip.class, format); |

|clip = (Clip) AudioSystem.getLine(info); |

|clip.open(stream); |

|clip.start(); |

|} |

|catch (Exception e) { |

|//whatever exception... |

|} |

|} |

Simple Sound in GUI Applications

• Not much out there that is concrete

• no volume control as of yet found

• easy setup

• music stops automatically after started unless looped

• there are two main methods for playing sound

o single play

o looped or continuous

• code MUST be placed in a try/catch block

• must import

o java.io.*;

o sun.audio.*;

|Coded Example for Single Play |

|InputStream in; // Open an input stream to the audio file. |

|AudioStream as; // Create an AudioStream object from the input stream. |

| |

|try |

|{ |

|in = new FileInputStream("spacemusic.au"); // file goes here |

|as = new AudioStream(in); |

|// Use the static class member "player" from class AudioPlayer to play clip. |

|AudioPlayer.player.start(as); |

|} catch (IOException e) { |

|System.out.println("error"); |

|e.printStackTrace(); |

|} |

|Coded Example for Continuous Play |

|InputStream in; // Open an input stream to the audio file. |

|AudioStream as; // Create an AudioStream object from the input stream. |

|AudioData data; // Create AudioData source. |

| |

|try { |

|in = new FileInputStream("spacemusic.au"); // file goes here |

|as = new AudioStream(in); |

| |

|data = as.getData(); |

|// Create ContinuousAudioDataStream. |

|ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data); |

|AudioPlayer.player.start(cas); |

|} catch (IOException e) { |

|e.printStackTrace(); |

|} |

AudioPlayer.player.stop(cas); // stops the music!! (thank goodness)

Citations: Sound







The “Timer”

• Thanks go to:

o George Woods and Lee Reynolds

• Timer is a DATATYPE within the javax.swing libraries

• WARNING!!

o There are two timers!!!

▪ javax.swing.Timer

▪ java.util.Timer

o IF YOU ARE USING BOTH (Which you probably will be) you will need to add which one WHEN INITIALIZING!!!

|No Conflict |Conflict |

|private Timer timer; |private javax.swing.Timer timer; |

|timer = new Timer(1000, new TimeListener()); |timer = new javax.swing.Timer(1000, new TimeListener()); |

|timer.setDelay(2000); // normal ONCE initialized |

• Timer DOES NOT MEASURE TIME, it sets an INTERVAL for when specified events should happen REPEATEDLY

• There are a few items that need to be completed for a working Timer

|Timer Setup |

|Creation of Timer Variable |

|private Timer timer; |

|Initialization of interval setting |

|// inside constructor OR a “starting” method |

|timer = new javax.swing.Timer(1000, new TimeListener()); // first parameter is IN MILLISECONDS!!! |

|Start of set intervals |

|timer.start(); // done usually in constructor |

|Stop of intervals |

|timer.stop(); // done usually in an actionListener for a stop or exit button |

|TimeListener setup |

|// within the SAME class that the TIMER is declared |

|public class TimeListener implements ActionListener |

|{ |

|public void actionPerformed(ActionEvent e) |

|{ |

|// WHATEVER NEEDS TO HAPPEN AFTER AN INTERVAL IS PLACED HERE |

|if(count % 6 == 0) { westqueue.add(“X”); } |

|label1.setIcon(“RedOff.png”); |

|… |

|} |

|} |

|Constructor Summary |

|Timer(int delay, ActionListener listener) |

|          Creates a Timer that will notify its listeners every delay milliseconds. |

 

|Method Summary |

| void |addActionListener(ActionListener listener) |

| |          Adds an action listener to the Timer. |

|protected  void |fireActionPerformed(ActionEvent e) |

| |          Notifies all listeners that have registered interest for notification on this event type. |

| ActionListener[] |getActionListeners() |

| |          Returns an array of all the action listeners registered on this timer. |

| int |getDelay() |

| |          Returns the delay, in milliseconds, between firings of action events. |

| int |getInitialDelay() |

| |          Returns the Timer's initial delay. |

| |getListeners(Class listenerType) |

|T[] |          Returns an array of all the objects currently registered as FooListeners upon this Timer. |

| | |

|static boolean |getLogTimers() |

| |          Returns true if logging is enabled. |

| boolean |isCoalesce() |

| |          Returns true if the Timer coalesces multiple pending action events. |

| boolean |isRepeats() |

| |          Returns true (the default) if the Timer will send an action event to its listeners multiple |

| |times. |

| boolean |isRunning() |

| |          Returns true if the Timer is running. |

| void |removeActionListener(ActionListener listener) |

| |          Removes the specified action listener from the Timer. |

| void |restart() |

| |          Restarts the Timer, canceling any pending firings and causing it to fire with its initial delay. |

| void |setCoalesce(boolean flag) |

| |          Sets whether the Timer coalesces multiple pending ActionEvent firings. |

| void |setDelay(int delay) |

| |          Sets the Timer's delay, the number of milliseconds between successive action events. |

| void |setInitialDelay(int initialDelay) |

| |          Sets the Timer's initial delay, which by default is the same as the between-event delay. |

|static void |setLogTimers(boolean flag) |

| |          Enables or disables the timer log. |

| void |setRepeats(boolean flag) |

| |          If flag is false, instructs the Timer to send only one action event to its listeners. |

| void |start() |

| |          Starts the Timer, causing it to start sending action events to its listeners. |

| void |stop() |

| |          Stops the Timer, causing it to stop sending action events to its listeners. |

|Timer Example 1 |

|/** |

|* |

|*/ |

|package labB; |

| |

|import java.awt.*; |

|import java.awt.event.*; |

| |

|import javax.swing.*; |

|/** |

|* @author Philip |

|* yy91815 |

|* key events: |

|* signal 1: |

|* red - 1 |

|* yellow - 2 |

|* green - 3 |

|* signal 2: |

|* red - 4 |

|* yellow - 5 |

|* green - 6 |

|* |

|* timmer - T |

|*/ |

|public class LabB extends JPanel{ |

| |

|private JLabel menu = new JLabel("MENU"); |

|private JPanel label = new JPanel(); |

|private JPanel primary = new JPanel(); |

|private JPanel secondary1 = new JPanel(); |

|private JPanel secondary2 = new JPanel(); |

|private SignalWindow signal1 = new SignalWindow("Signal 1"); |

|private SignalWindow signal2 = new SignalWindow("Signal 2"); |

|private OptionsWindow options1 = new OptionsWindow(); |

|private OptionsWindow options2 = new OptionsWindow(); |

|private JTextField keys = new JTextField(); |

| |

|//private Timer theTimer = new javax.swing.Timer(300, new TimeListener()); |

|private Timer theTimer = new javax.swing.Timer(60000, new TimeListener()); |

| |

|public LabB(){ |

| |

|this.setLayout(new BorderLayout()); |

|add(label, BorderLayout.NORTH); |

| |

| |

|//keys.requestFocus(); |

|label.add(menu); |

|label.setLayout(new FlowLayout()); |

|add(primary, BorderLayout.CENTER); |

|menu.setAlignmentX(CENTER_ALIGNMENT); |

|primary.setLayout(new BoxLayout(primary, BoxLayout.X_AXIS)); |

|primary.add(secondary1); |

|primary.add(secondary2); |

|secondary1.setLayout(new BoxLayout(secondary1, BoxLayout.Y_AXIS)); |

|secondary2.setLayout(new BoxLayout(secondary2, BoxLayout.Y_AXIS)); |

|secondary1.add(signal1); |

|secondary1.add(options1); |

|options1.red.setActionCommand("red1"); |

|options1.red.addActionListener(new ButtonListener()); |

|options1.yellow.setActionCommand("yellow1"); |

|options1.yellow.addActionListener(new ButtonListener()); |

|options1.green.setActionCommand("green1"); |

|options1.green.addActionListener(new ButtonListener()); |

|options1.timer.setActionCommand("timer1"); |

|options1.timer.addActionListener(new ButtonListener()); |

|options1.timer.addKeyListener(new MyKeyListener()); |

|secondary2.add(signal2); |

|secondary2.add(options2); |

|options2.red.setActionCommand("red2"); |

|options2.red.addActionListener(new ButtonListener()); |

|options2.yellow.setActionCommand("yellow2"); |

|options2.yellow.addActionListener(new ButtonListener()); |

|options2.green.setActionCommand("green2"); |

|options2.green.addActionListener(new ButtonListener()); |

|options2.timer.setActionCommand("timer2"); |

|options2.timer.addActionListener(new ButtonListener()); |

|options2.timer.addKeyListener(new MyKeyListener()); |

|add(keys, BorderLayout.SOUTH); |

|keys.setFocusable(true); |

|keys.setEditable(false); |

|keys.requestFocusInWindow(); |

|keys.addKeyListener(new MyKeyListener()); |

|keys.requestFocus(); |

| |

|} |

| |

|private class ButtonListener implements ActionListener |

|{ |

|public void actionPerformed(ActionEvent event) |

|{ |

|String actionCommand = event.getActionCommand(); |

| |

|if(actionCommand.equals("red1")){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("yellow1")){ |

|signal1.icon.setIcon(new ImageIcon("yellow.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("green1")){ |

|signal1.icon.setIcon(new ImageIcon("green.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("timer1")){ |

|theTimer.restart(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("red2")){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("yellow2")){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("yellow.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("green2")){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("green.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(actionCommand.equals("timer2")){ |

|theTimer.restart(); |

|keys.requestFocus(); |

|} |

| |

| |

| |

| |

|} |

|} |

| |

|public class TimeListener implements ActionListener |

|{ |

|public void actionPerformed(ActionEvent e) |

|{ |

|// WHATEVER NEEDS TO HAPPEN AFTER AN INTERVAL IS PLACED HERE |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|theTimer.stop(); |

|} |

|} |

| |

|private class MyKeyListener implements KeyListener{ |

| |

|public void keyTyped(KeyEvent e) |

|{ |

| |

|} |

| |

|@Override |

|public void keyPressed(KeyEvent e) { |

|// TODO Auto-generated method stub |

| |

|} |

| |

|@Override |

|public void keyReleased(KeyEvent e) { |

|char c = e.getKeyChar(); |

|System.out.println(c); |

|if(e.getKeyCode() == KeyEvent.VK_T){ |

|theTimer.restart(); |

|keys.requestFocus(); |

|} |

|if(e.getKeyCode() == KeyEvent.VK_1){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(e.getKeyCode() == KeyEvent.VK_2){ |

|signal1.icon.setIcon(new ImageIcon("yellow.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(e.getKeyCode() == KeyEvent.VK_3){ |

|signal1.icon.setIcon(new ImageIcon("green.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(e.getKeyCode() == KeyEvent.VK_4){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("red.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(e.getKeyCode() == KeyEvent.VK_5){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("yellow.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|if(e.getKeyCode() == KeyEvent.VK_6){ |

|signal1.icon.setIcon(new ImageIcon("red.png")); |

|signal2.icon.setIcon(new ImageIcon("green.png")); |

|signal1.updateUI(); |

|signal2.updateUI(); |

|keys.requestFocus(); |

|} |

|} |

| |

|} |

| |

| |

|private class SignalWindow extends JPanel{ |

|private JLabel signal = new JLabel(); |

|private JPanel label = new JPanel(); |

|private JLabel icon = new JLabel(new ImageIcon("red.png")); |

|public SignalWindow(String s){ |

|this.signal = new JLabel(s); |

|this.setLayout(new BorderLayout()); |

|add(label, BorderLayout.NORTH); |

|label.add(signal); |

|add(icon, BorderLayout.CENTER); |

|} |

|} |

| |

|private class OptionsWindow extends JPanel{ |

|private JPanel buttonPanel1 = new JPanel(); |

|private JPanel buttonPanel2 = new JPanel(); |

|private JPanel buttonPanel3 = new JPanel(); |

|private JPanel buttonPanel4 = new JPanel(); |

|//private JPanel buttonPanelMain = new JPanel(); |

| |

|private JButton red = new JButton("R"); |

|private JButton yellow = new JButton("Y"); |

|private JButton green = new JButton("G"); |

|private JButton timer = new JButton("TIMER"); |

|public OptionsWindow(){ |

| |

|this.setLayout(new BorderLayout()); |

| |

|add(buttonPanel1, BorderLayout.WEST); |

|//buttonPanel1.setLayout(new BorderLayout()); |

|add(buttonPanel2, BorderLayout.CENTER); |

|//buttonPanel2.setLayout(new BorderLayout()); |

|add(buttonPanel3, BorderLayout.EAST); |

|//buttonPanel3.setLayout(new BorderLayout()); |

|add(buttonPanel4, BorderLayout.SOUTH); |

|//buttonPanel4.setLayout(new BorderLayout()); |

| |

|buttonPanel1.add(red); |

|red.setBackground(Color.RED); |

|red.setPreferredSize(new Dimension(60, 60)); |

|buttonPanel2.add(yellow); |

|yellow.setBackground(Color.YELLOW); |

|yellow.setPreferredSize(new Dimension(60, 60)); |

|buttonPanel3.add(green); |

|green.setBackground(Color.GREEN); |

|green.setPreferredSize(new Dimension(60, 60)); |

|buttonPanel4.add(timer); |

|timer.setBackground(Color.GRAY); |

|timer.setPreferredSize(new Dimension(120, 60)); |

|} |

|} |

| |

| |

| |

| |

|/** |

|* @param args |

|*/ |

|public static void main(String[] args) { |

|// TODO Auto-generated method stub |

| |

|} |

| |

|} |

| |

|Timer Example 2 |

|import java.awt.*; |

|import java.awt.event.*; |

| |

|import javax.swing.*; |

| |

|@SuppressWarnings("serial") |

|public class JavaHW2GUI extends JPanel{ |

| |

|//Creates all menu objects |

|JMenuBar menuBar = new JMenuBar(); |

|JMenu menu1 = new JMenu("Light1"); |

|JMenuItem menuRed1 = new JMenuItem("Change to Red"); |

|JMenuItem menuYellow1 = new JMenuItem("Change to Yellow"); |

|JMenuItem menuGreen1 = new JMenuItem("Change to Green"); |

|JMenuItem menuTimer1 = new JMenuItem("Set Timer"); |

|JMenu menu2 = new JMenu("Light2"); |

|JMenuItem menuRed2 = new JMenuItem("Change to Red"); |

|JMenuItem menuYellow2 = new JMenuItem("Change to Yellow"); |

|JMenuItem menuGreen2 = new JMenuItem("Change to Green"); |

|JMenuItem menuTimer2 = new JMenuItem("Set Timer"); |

| |

|//the images for the lights |

|JLabel image1 = new JLabel(new ImageIcon("./green.JPG")); |

|JLabel image2 = new JLabel(new ImageIcon("./red.JPG")); |

| |

|//The buttons for the first light signals |

|JButton red1 = new JButton("RED"); |

|JButton yellow1 = new JButton("YELLOW"); |

|JButton green1 = new JButton("GREEN"); |

| |

|//The buttons for the second light signals |

|JButton red2 = new JButton("RED"); |

|JButton yellow2 = new JButton("YELLOW"); |

|JButton green2 = new JButton("GREEN"); |

| |

|//These are the buttons that control the timers |

|JButton timer1 = new JButton("TIMER"); |

|JButton timer2 = new JButton("TIMER"); |

| |

|//These are the timers that wait 60 seconds then change the lights |

|Timer time1 = new Timer(1000, new TimeListener()); |

|Timer time2 = new Timer(1000, new TimeListener()); |

| |

|JavaHW2GUI() { |

|//Set up MenuBar |

|this.add(menuBar); |

|menuBar.add(menu1); |

|menu1.add(menuRed1); |

|menu1.add(menuYellow1); |

|menu1.add(menuGreen1); |

|menu1.add(menuTimer1); |

|menuBar.add(menu2); |

|menu2.add(menuRed2); |

|menu2.add(menuYellow2); |

|menu2.add(menuGreen2); |

|menu2.add(menuTimer2); |

|menuRed1.setMnemonic(KeyEvent.VK_R); |

|menuYellow1.setMnemonic(KeyEvent.VK_Y); |

|menuGreen1.setMnemonic(KeyEvent.VK_G); |

|menuTimer1.setMnemonic(KeyEvent.VK_1); |

|menuRed2.setMnemonic(KeyEvent.VK_D); |

|menuYellow2.setMnemonic(KeyEvent.VK_W); |

|menuGreen2.setMnemonic(KeyEvent.VK_N); |

|menuTimer2.setMnemonic(KeyEvent.VK_2); |

| |

|//Sets up the background of the Buttons |

|red1.setBackground(Color.RED); |

|yellow1.setBackground(Color.YELLOW); |

|green1.setBackground(Color.GREEN); |

|red2.setBackground(Color.RED); |

|yellow2.setBackground(Color.YELLOW); |

|green2.setBackground(Color.GREEN); |

|red1.setOpaque(true); |

|yellow1.setOpaque(true); |

|green1.setOpaque(true); |

|red2.setOpaque(true); |

|yellow2.setOpaque(true); |

|green2.setOpaque(true); |

|red1.setBorderPainted(false); |

|yellow1.setBorderPainted(false); |

|green1.setBorderPainted(false); |

|red2.setBorderPainted(false); |

|yellow2.setBorderPainted(false); |

|green2.setBorderPainted(false); |

| |

|//Set up base Panel's layout |

|this.setLayout(new BorderLayout()); |

|this.add(menuBar, BorderLayout.NORTH); |

| |

|//Sets up the main panel's layout |

|JPanel main = new JPanel(); |

|main.setLayout(new GridLayout(1, 2)); |

|this.add(main, BorderLayout.CENTER); |

| |

|//Sets up the left signal's data |

|JPanel light1 = new JPanel(); |

|light1.add(image1); |

|JPanel light1Center = new JPanel(); |

|light1Center.setLayout(new GridLayout(1,3)); |

|light1Center.add(red1); |

|light1Center.add(yellow1); |

|light1Center.add(green1); |

|light1.add(light1Center); |

|light1.add(timer1); |

| |

|//Sets up the right signal's data |

|JPanel light2 = new JPanel(); |

|light2.add(image2); |

|JPanel light2Center = new JPanel(); |

|light2Center.setLayout(new GridLayout(1,3)); |

|light2Center.add(red2); |

|light2Center.add(yellow2); |

|light2Center.add(green2); |

|light2.add(light2Center); |

|light2.add(timer2); |

| |

|//Adds the lights to the JPanel |

|main.add(light1); |

|main.add(light2); |

| |

|//Sets up the layout of the lights |

|light1.setLayout(new BoxLayout(light1, BoxLayout.Y_AXIS)); |

|light2.setLayout(new BoxLayout(light2, BoxLayout.Y_AXIS)); |

| |

|//Sets up all of the ActionListeners |

|red1.addActionListener(new ButtonListener()); |

|yellow1.addActionListener(new ButtonListener()); |

|green1.addActionListener(new ButtonListener()); |

|red2.addActionListener(new ButtonListener()); |

|yellow2.addActionListener(new ButtonListener()); |

|green2.addActionListener(new ButtonListener()); |

|timer1.addActionListener(new ButtonListener()); |

|timer2.addActionListener(new ButtonListener()); |

|menuRed1.addActionListener(new MenuListener()); |

|menuYellow1.addActionListener(new MenuListener()); |

|menuGreen1.addActionListener(new MenuListener()); |

|menuTimer1.addActionListener(new MenuListener()); |

|menuRed2.addActionListener(new MenuListener()); |

|menuYellow2.addActionListener(new MenuListener()); |

|menuGreen2.addActionListener(new MenuListener()); |

|menuTimer2.addActionListener(new MenuListener()); |

|menuRed1.addKeyListener(new MenuKeyListener()); |

|menuYellow1.addKeyListener(new MenuKeyListener()); |

|menuGreen1.addKeyListener(new MenuKeyListener()); |

|menuTimer1.addKeyListener(new MenuKeyListener()); |

|menuRed2.addKeyListener(new MenuKeyListener()); |

|menuYellow2.addKeyListener(new MenuKeyListener()); |

|menuGreen2.addKeyListener(new MenuKeyListener()); |

|menuTimer2.addKeyListener(new MenuKeyListener()); |

|this.addKeyListener(new MenuKeyListener()); |

|} |

| |

|private class ButtonListener implements ActionListener { |

| |

|@Override |

|public void actionPerformed(ActionEvent e) { |

|//do the action associated with the button |

|if (e.getSource().equals(red1)) ; |

|image1.setIcon(new ImageIcon("./red.JPG")); |

|image2.setIcon(new ImageIcon("./green.JPG")); |

|} |

|else if (e.getSource().equals(red2)) { |

|image1.setIcon(new ImageIcon("./green.JPG")); |

|image2.setIcon(new ImageIcon("./red.JPG")); |

|} |

|else if (e.getSource().equals(yellow1)) { |

|image1.setIcon(new ImageIcon("./yellow.JPG")); |

|image2.setIcon(new ImageIcon("./red.JPG")); |

|} |

|else if (e.getSource().equals(yellow2)) { |

|image1.setIcon(new ImageIcon("./red.JPG")); |

|image2.setIcon(new ImageIcon("./yellow.JPG")); |

|} |

|else if (e.getSource().equals(green1)) { |

|image1.setIcon(new ImageIcon("./green.JPG")); |

|image2.setIcon(new ImageIcon("./red.JPG")); |

|} |

|else if (e.getSource().equals(green2)) { |

|image1.setIcon(new ImageIcon("./red.JPG")); |

|image2.setIcon(new ImageIcon("./green.JPG")); |

|} |

|else if (e.getSource().equals(timer1)) { |

|time1.start(); |

|} |

|else if (e.getSource().equals(timer2)) { |

|time2.start(); |

|} |

| |

| |

|} |

| |

|} |

|private class TimeListener implements ActionListener { |

| |

|@Override |

|public void actionPerformed(ActionEvent e) { |

|//Does the associated action with each Timer |

|if(e.getSource().equals(time1)) { |

|time1.stop(); |

|image1.setIcon(new ImageIcon("./red.JPG")); |

|image2.setIcon(new ImageIcon("./green.JPG")); |

|} |

|else if(e.getSource().equals(time2)) { |

|time2.stop(); |

|image1.setIcon(new ImageIcon("./green.JPG")); |

|image2.setIcon(new ImageIcon("./red.JPG")); |

|} |

| |

|} |

| |

|} |

|private class MenuListener implements ActionListener { |

| |

|@Override |

|public void actionPerformed(ActionEvent e) { |

|if(e.getSource().equals(menuRed1)) { |

|red1.doClick(); |

|} |

|else if(e.getSource().equals(menuYellow1)) { |

|yellow1.doClick(); |

|} |

|else if(e.getSource().equals(menuGreen1)) { |

|green1.doClick(); |

|} |

|else if(e.getSource().equals(menuTimer1)) { |

|timer1.doClick(); |

|} |

|else if(e.getSource().equals(menuRed2)) { |

|red2.doClick(); |

|} |

|else if(e.getSource().equals(menuYellow2)) { |

|yellow2.doClick(); |

|} |

|else if(e.getSource().equals(menuGreen2)) { |

|green2.doClick(); |

|} |

|else if(e.getSource().equals(menuTimer2)) { |

|timer2.doClick(); |

|} |

| |

|} |

| |

|} |

|private class MenuKeyListener implements KeyListener { |

| |

|@Override |

|public void keyPressed(KeyEvent e) {return;} |

| |

|@Override |

|public void keyReleased(KeyEvent e) {return;} |

| |

|@Override |

|public void keyTyped(KeyEvent e) { |

|if (e.getSource().equals(menuRed1)) { |

|red1.doClick(); |

|} |

|else if (e.getSource().equals(menuYellow1)) { |

|yellow1.doClick(); |

|} |

|else if (e.getSource().equals(menuGreen1)) { |

|green1.doClick(); |

|} |

|else if (e.getSource().equals(menuTimer1)) { |

|timer1.doClick(); |

|} |

|else if (e.getSource().equals(menuRed2)) { |

|red2.doClick(); |

|} |

|else if (e.getSource().equals(menuYellow2)) { |

|yellow2.doClick(); |

|} |

|else if (e.getSource().equals(menuGreen2)) { |

|green2.doClick(); |

|} |

|else if (e.getSource().equals(menuTimer2)) { |

|timer2.doClick(); |

|} |

| |

|} |

| |

|} |

|} |

| |

JDialogs

• Can be used just like a JFrame.

• Many different Options, can be found on API

• JButtons, JLabels, JPanels, etc… can be added

• Can run in the main, even if Gui not set up.

• Can Add ActionListeners, a bit tricky.

• import javax.swing.JDialog;

• To Close use .dispose();

|JDialogs in action |

|import java.awt.*; |

|import javax.swing.*; |

| |

|public class DialogEx { |

| |

|public static void main(String[] args) { |

| |

|JDialog dialog = new JDialog(); |

|dialog.setSize(400, 650); |

|dialog.setLocation(700,200); |

|dialog.setModal(true); //sets dialog so that input to other windows is blocked |

|dialog.setTitle("A JDIALOG!!!"); |

|JPanel Pane = new JPanel(new BorderLayout()); |

|ImageIcon icon = new ImageIcon("C:/Documents and Settings/All Users/Documents/My Pictures/Sample Pictures/Blue hills.jpg"); |

|JLabel image = new JLabel(); |

|image.setIcon(icon); |

|JLabel label = new JLabel("A Label"); |

|JButton button = new JButton("A Button"); |

|Pane.add(image, BorderLayout.NORTH); |

|Pane.add(label, BorderLayout.CENTER); |

|Pane.add(button, BorderLayout.EAST); |

|dialog.setContentPane(Pane); //add JPanel to JDialog |

|dialog.setVisible(true); |

|} |

|} |

Getting Beeps!!

• need to import java.awt.Toolkit;

• place code below in the ACtionLIstener

code is simple:

Toolkit.getDefaultToolkit().beep();

Moving a GUI Component

• Many people make this HARD!!

• You only need to use:

o specify a Layout

▪ FlowLayout used in this example

o object.setLocation(x,y)

▪ not setBounds, although that will work too, but is used to enlarge, reduce…

o get X and Y position (at that time, then use setLocation with New (X,Y)

▪ (int) object.getX()

▪ (int) object.getY()

The code below is INCOMPLETE with Driver and GUI!!

(need to find a picture, name it “eclipse48.png”, and copy it to the SAME directory as the .java files)

|Driver |

|import java.awt.Dimension; |

|import javax.swing.JFrame; |

| |

|public class MoveCardDemo |

|{ |

|public static void main(String[] args) |

|{ |

|JFrame window = new JFrame("Moving the Card (GUI)"); |

|window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |

|window.setPreferredSize(new Dimension(400,700)); // width, height |

|window.getContentPane().add(new MoveCardGUI()); |

|window.pack(); |

|window.setVisible(true); |

|} |

|} |

|JPanel Class |

|… |

|private JLabel movingball = new JLabel(new ImageIcon("eclipse48.png")); |

|… |

| |

|// ActionListener inside the class |

|private class ButtonListener implements ActionListener |

|{ |

|public void actionPerformed(ActionEvent e) |

|{ |

|String command = e.getActionCommand(); |

| |

|if(command == "Top Left Corner") |

|{ movingball.setLocation(0 , 0); }// moving ball |

|if(command == "Top Right Corner") |

|{ movingball.setLocation(300 , 0); } |

|if(command == "Bottom Left Corner") |

|{ movingball.setLocation(0 , 300); } |

|if(command == "Bottom Right Corner") |

|{ movingball.setLocation(300 , 300); } |

|if(command == "Middle") |

|{ movingball.setLocation(150 , 150); } |

| |

| |

|if(command == "Up") |

|{ movingball.setLocation(movingball.getX(), movingball.getY() - 20); } |

|if(command == "Left") |

|{ movingball.setLocation(movingball.getX() -20 , movingball.getY()); } |

|if(command == "Right") |

|{ movingball.setLocation(movingball.getX()+20 , movingball.getY()); } |

|if(command == "Down") |

|{ movingball.setLocation(movingball.getX(), movingball.getY() + 20); } |

|} |

|} |

-----------------------

|Moving Example |Example Make-Up |

|[pic] | |

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download