ActionListener vs MouseListener

Hi,
Working with Swing, I have noticed that 1 mouse click on a JButton, out of 10 (on average), is lost, i.e. it won't fire MouseEvent. In this case, i use MouseListener and mouseClicked(MouseEvent me) method.
When I use ActionListener (actionPerformed() method), everything goes smooth, and none of the mouse clicks is lost.
However, I'm much more comfortable working with MouseListener than ActionListener. That's why i'm seeking the cause of this problem. Is this a swing problem, or it's me doing something wrong? Just to mention, everything works as expected, with exception of only this problem (lost click occasionally).
Thanks in advance!

However, I'm much more comfortable working with MouseListener than ActionListenerUsing an ActionListener is the correct way to 'do something' when a JButton is clicked.
How can you be more comfortable implementing 5 methods of a MouseListener versus the single method of an ActionListener.
Try it the proper way a couple of times and you will be just as comfortable. Just remember other people may have to maintain your program in the future, or you may have to maintain there programs. Thats why we have programming standards.
(mousePressed, mouse
It also works for JRadioButton, JCheckBox.
You only have to implement actionPerformed(..) with an ActionListener.
With a MouseListener you have to implement

Similar Messages

  • A question about ActionListener and MouseListener

    Hi,
    my question here is when we should implement a MouseListener and when we should use ActionListener instead.
    I know ActionEvent is fired when a action performed, for instance, a button was pressed down, but I think by implementing a MouseListener, we can use its mouseClicked(MouseEvent e) method to do the same job as the actionPerformed method.
    So, what's the difference between a actionevent(button has been pressed down)and a mouse event(click on a button)? And when we should use them?

    Using the ActionListener actionCommand is the normal paradigm for button clicks.
    ActionEvents, ChangeEvents etc are much higher-level than MouseEvents. And you should use the highest level of abstraction that provides sufficient specificity.
    When adding MouseListener to an component you actully let the system do more work then needed.
    ( you have the mouseEntered, mousePressed, mouseClicked, mouseReleased, ..)
    Every button click will "generate" three mouse events... pressed, released and clicked.
    good luck!

  • ActionListener&MouseListener add to Drawing Object in JApplet

    hi,guys
    When I am doing my JApplet, I wanna add the ActionListener and MouseListener to the Drawing Object...
    Like this:
    Graphics2D g11 = (Graphics2D)g;
    g11.setColor(Color.orange);
    g11.fillOval(10,300, 100, 40);
    g11.setColor(Color.darkGray);
    g11.drawString(""+firstpro,30,325); //first protein object
    g11 is the object, and now I wanna add both ActionListener and MouseListener on it.. that means if I click g11 area in my JApplet, it will do certain actions like open another URL page, and send a String from applet to that page also...
    Does is possible to achieve?? If it does, how do I add the source code??
    Hope you guys could kindly help me with some sample code...Thanks a lot!!
    SD

    I don't believe the Graphics derived objects have any support for the Component derived stuff. But you can certainly add these listeners to whichever Component contains your graphics. If you want them to respond only if they are over a drawn part of the component, thats up to you application code as its the only thing that knows where the drawing ends.

  • Implementing ActionListener & MouseListener

    Hello all!!
    I was just wondering, is it possible to implement both an ActionListener and a MouseListener into one class? ex:
    public class NAME extends JFrame implements ActionListener implements MouseListener
    //etc
    I have a program that relies heavily on MouseListener that I want to add a JMenu to, but I need ActionListener to do that... so, is it possible and I only have the wrong code? Or do I have to work around that somehow?
    Thank you so much for your help!
    Blessings,
    Sarah

    public class Name extends JFrame implements ActionListener, MouseListener

  • DO i need some extra hardware interface for receving both Audio and video

    hi i m doing e-learning project. i have to capture video from webcam and voice from headphone and send to client.
    but my code is working fine for either one at a time.
    DO i need some extra hardware interface for receving both Audio and video. im using code AVTransmit and AVReceive found from this site only
    After running TX
    i give Dsound:// & vfw://0 in Media Locater only sound is received and no vedio
    and when i give vfw://0 in Media Locater only live video is transmited.
    im using JMF1.1.2e.
    if any one know the method to run or cause of it plz reply me soon. i will be very thankfull
    transmiter/server side code .first run TX on server
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.media.rtp.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class Tx extends JFrame implements ActionListener, KeyListener,
    MouseListener, WindowListener {
    Vector targets;
    JList list;
    JButton startXmit;
    JButton rtcp;
    JButton update;
    JButton expiration;
    JButton statistics;
    JButton addTarget;
    JButton removeTarget;
    JTextField tf_remote_address;
    JTextField tf_remote_data_port;
    JTextField tf_media_file;
    JTextField tf_data_port;
    TargetListModel listModel;
    AVTransmitter avTransmitter;
    RTCPViewer rtcpViewer;
    JCheckBox cb_loop;
    Config config;
    public Tx() {
    setTitle( "JMF/RTP Transmitter");
         config= new Config();
         GridBagLayout gridBagLayout= new GridBagLayout();
         GridBagConstraints gbc;
         JPanel p= new JPanel();
         p.setLayout( gridBagLayout);
         JPanel localPanel= createLocalPanel();
         gbc= new GridBagConstraints();
         gbc.gridx= 0;
         gbc.gridy= 0;
         gbc.gridwidth= 2;
         gbc.anchor= GridBagConstraints.CENTER;
         gbc.fill= GridBagConstraints.BOTH;
         gbc.insets= new Insets( 10, 5, 0, 0);
         ((GridBagLayout)p.getLayout()).setConstraints( localPanel, gbc);
         p.add( localPanel);
         JPanel targetPanel= createTargetPanel();
         gbc= new GridBagConstraints();
         gbc.gridx= 1;
         gbc.gridy= 1;
         gbc.weightx= 1.0;
         gbc.weighty= 1.0;
         gbc.anchor= GridBagConstraints.CENTER;
         gbc.fill= GridBagConstraints.BOTH;
         gbc.insets= new Insets( 10, 5, 0, 0);
         ((GridBagLayout)p.getLayout()).setConstraints( targetPanel, gbc);
    p.add( targetPanel);
         JPanel mediaPanel= createMediaPanel();
         gbc= new GridBagConstraints();
         gbc.gridx= 1;
         gbc.gridy= 2;
         gbc.weightx= 1.0;
         gbc.weighty= 1.0;
         gbc.anchor= GridBagConstraints.CENTER;
         gbc.fill= GridBagConstraints.BOTH;
         gbc.insets= new Insets( 10, 5, 0, 0);
         ((GridBagLayout)p.getLayout()).setConstraints( mediaPanel, gbc);
    p.add( mediaPanel);
    JPanel buttonPanel= new JPanel();
    rtcp= new JButton( "RTCP Monitor");
    update= new JButton( "Transmission Status");
         update.setEnabled( false);
         rtcp.addActionListener( this);
         update.addActionListener( this);
         buttonPanel.add( rtcp);
         buttonPanel.add( update);
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 3;
    gbc.gridwidth= 2;
         gbc.weightx = 1.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.CENTER;
         gbc.fill = GridBagConstraints.HORIZONTAL;
         gbc.insets = new Insets( 5,5,10,5);
         ((GridBagLayout)p.getLayout()).setConstraints( buttonPanel, gbc);
         p.add( buttonPanel);
    getContentPane().add( p);
         list.addMouseListener( this);
         addWindowListener( this);
    pack();
    setVisible( true);
    private JPanel createMediaPanel() {
    JPanel p= new JPanel();
         GridBagLayout gridBagLayout= new GridBagLayout();
    GridBagConstraints gbc;
         p.setLayout( gridBagLayout);
         JLabel label= new JLabel( "Media Locator:");
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 0;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.EAST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,10,5);
         ((GridBagLayout)p.getLayout()).setConstraints( label, gbc);
         p.add( label);
         tf_media_file= new JTextField( 35);
         gbc= new GridBagConstraints();
         gbc.gridx = 1;
         gbc.gridy = 0;
         gbc.weightx = 1.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.WEST;
         gbc.fill = GridBagConstraints.HORIZONTAL;
         gbc.insets = new Insets( 5,5,10,5);
         ((GridBagLayout)p.getLayout()).setConstraints( tf_media_file, gbc);
         p.add( tf_media_file);
         tf_media_file.setText( config.media_locator);
         cb_loop= new JCheckBox( "loop");
         startXmit= new JButton( "Start Transmission");
         startXmit.setEnabled( true);
         startXmit.addActionListener( this);
         gbc= new GridBagConstraints();
         gbc.gridx = 2;
         gbc.gridy = 0;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.WEST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,10,5);
         ((GridBagLayout)p.getLayout()).setConstraints( cb_loop, gbc);
         p.add( cb_loop);
         cb_loop.setSelected( true);
         cb_loop.addActionListener( this);
         gbc= new GridBagConstraints();
         gbc.gridx = 1;
         gbc.gridy = 1;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.CENTER;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,10,5);
         ((GridBagLayout)p.getLayout()).setConstraints( startXmit, gbc);
         p.add( startXmit);
         TitledBorder titledBorder= new TitledBorder( new EtchedBorder(), "Source");
         p.setBorder( titledBorder);
         return p;
    private JPanel createTargetPanel() {
    JPanel p= new JPanel();
         GridBagLayout gridBagLayout= new GridBagLayout();
    GridBagConstraints gbc;
         p.setLayout( gridBagLayout);
         targets= new Vector();
         for( int i= 0; i < config.targets.size(); i++) {
         targets.addElement( config.targets.elementAt( i));
    listModel= new TargetListModel( targets);
    list= new JList( listModel);
         list.addKeyListener( this);
         list.setPrototypeCellValue( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    JScrollPane scrollPane= new JScrollPane( list,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
         gbc= new GridBagConstraints();
         gbc.gridx= 0;
         gbc.gridy= 0;
         gbc.weightx= 1.0;
         gbc.weighty= 1.0;
         gbc.anchor= GridBagConstraints.CENTER;
         gbc.fill= GridBagConstraints.BOTH;
         gbc.insets= new Insets( 10, 5, 0, 0);
         ((GridBagLayout)p.getLayout()).setConstraints( scrollPane, gbc);
         p.add( scrollPane);
    JPanel p1= new JPanel();
         p1.setLayout( gridBagLayout);
         JLabel label= new JLabel( "IP Address:");
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 0;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.EAST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p1.getLayout()).setConstraints( label, gbc);
         p1.add( label);
         tf_remote_address= new JTextField( 15);
         gbc= new GridBagConstraints();
         gbc.gridx = 1;
         gbc.gridy = 0;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.WEST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p1.getLayout()).setConstraints( tf_remote_address, gbc);
         p1.add( tf_remote_address);
         label= new JLabel( "Data Port:");
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 1;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.EAST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p1.getLayout()).setConstraints( label, gbc);
         p1.add( label);
         tf_remote_data_port= new JTextField( 15);
         gbc= new GridBagConstraints();
         gbc.gridx = 1;
         gbc.gridy = 1;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.WEST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p1.getLayout()).setConstraints( tf_remote_data_port, gbc);
         p1.add( tf_remote_data_port);     
    JPanel p2= new JPanel();
    addTarget= new JButton( "Add Target");     
    removeTarget= new JButton( "Remove Target");
         p2.add( addTarget);
         p2.add( removeTarget);
         addTarget.addActionListener( this);
         removeTarget.addActionListener( this);
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 2;
         gbc.weightx = 1.0;
         gbc.weighty = 0.0;
         gbc.gridwidth= 2;
         gbc.anchor = GridBagConstraints.CENTER;
         gbc.fill = GridBagConstraints.HORIZONTAL;
         gbc.insets = new Insets( 20,5,0,5);
         ((GridBagLayout)p1.getLayout()).setConstraints( p2, gbc);
         p1.add( p2);
         gbc= new GridBagConstraints();
         gbc.gridx= 1;
         gbc.gridy= 0;
         gbc.weightx= 1.0;
         gbc.weighty= 1.0;
         gbc.anchor= GridBagConstraints.CENTER;
         gbc.fill= GridBagConstraints.BOTH;
         gbc.insets= new Insets( 10, 5, 0, 0);
         ((GridBagLayout)p.getLayout()).setConstraints( p1, gbc);
         p.add( p1);
         TitledBorder titledBorder= new TitledBorder( new EtchedBorder(), "Targets");
         p.setBorder( titledBorder);
         return p;
    private JPanel createLocalPanel() {
    JPanel p= new JPanel();
         GridBagLayout gridBagLayout= new GridBagLayout();
    GridBagConstraints gbc;
         p.setLayout( gridBagLayout);
         JLabel label= new JLabel( "IP Address:");
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 0;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.EAST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p.getLayout()).setConstraints( label, gbc);
         p.add( label);
         JTextField tf_local_host= new JTextField( 15);
         gbc= new GridBagConstraints();
         gbc.gridx = 1;
         gbc.gridy = 0;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.WEST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p.getLayout()).setConstraints( tf_local_host, gbc);
         p.add( tf_local_host);
         try {
    String host= InetAddress.getLocalHost().getHostAddress();     
         tf_local_host.setText( host);
         } catch( UnknownHostException e) {
         label= new JLabel( "Data Port:");
         gbc= new GridBagConstraints();
         gbc.gridx = 0;
         gbc.gridy = 1;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.EAST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,0,5);
         ((GridBagLayout)p.getLayout()).setConstraints( label, gbc);
         p.add( label);
         tf_data_port= new JTextField( 15);
         gbc= new GridBagConstraints();
         gbc.gridx = 1;
         gbc.gridy = 1;
         gbc.weightx = 0.0;
         gbc.weighty = 0.0;
         gbc.anchor = GridBagConstraints.WEST;
         gbc.fill = GridBagConstraints.NONE;
         gbc.insets = new Insets( 5,5,10,5);
         ((GridBagLayout)p.getLayout()).setConstraints( tf_data_port, gbc);
         p.add( tf_data_port);
         tf_data_port.setText( config.local_data_port);
         TitledBorder titledBorder= new TitledBorder( new EtchedBorder(), "Local Host");
         p.setBorder( titledBorder);
         return p;
    public void actionPerformed( ActionEvent event) {
    Object source= event.getSource();
         if( source == addTarget) {
         String ip= tf_remote_address.getText().trim();
         String port= tf_remote_data_port.getText().trim();
         String localPort= tf_data_port.getText().trim();
         addTargetToList( localPort, ip, port);
         if( avTransmitter != null) {
         avTransmitter.addTarget( ip, port);
         } else if( source == removeTarget) {
         int index= list.getSelectedIndex();
         if( index != -1) {
              Target target= (Target) targets.elementAt( index);
              if( avTransmitter != null) {
         avTransmitter.removeTarget( target.ip, target.port);
              targets.removeElement( target);
              listModel.setData( targets);          
         } else if( source == startXmit) {
         if( startXmit.getLabel().equals( "Start Transmission")) {          
         int data_port= new Integer( tf_data_port.getText()).intValue();
              avTransmitter= new AVTransmitter( this, data_port);
         avTransmitter.start( tf_media_file.getText().trim(), targets);          
              avTransmitter.setLooping( cb_loop.isSelected());
         startXmit.setLabel( "Stop Transmission");
         } else if( startXmit.getLabel().equals( "Stop Transmission")) {
              avTransmitter.stop();
              avTransmitter= null;
              removeNonBaseTargets();
              listModel.setData( targets);
         startXmit.setLabel( "Start Transmission");          
         } else if( source == rtcp) {
         if( rtcpViewer == null) {
         rtcpViewer= new RTCPViewer();
         } else {
              rtcpViewer.setVisible( true);
              rtcpViewer.toFront();
         } else if( source == cb_loop) {
         if( avTransmitter != null) {
              avTransmitter.setLooping( cb_loop.isSelected());
    private void removeNonBaseTargets() {
         String localPort= tf_data_port.getText().trim();
         for( int i= targets.size(); i > 0;) {
         Target target= (Target) targets.elementAt( i - 1);
         if( !target.localPort.equals( localPort)) {
    targets.removeElement( target);
         i--;
    public void addTargetToList( String localPort,
                             String ip, String port) {     
    ListUpdater listUpdater= new ListUpdater( localPort, ip,
                                  port, listModel, targets);
    SwingUtilities.invokeLater( listUpdater);           
    public void rtcpReport( String report) {
         if( rtcpViewer != null) {
         rtcpViewer.report( report);
    public void windowClosing( WindowEvent event) {
         config.local_data_port= tf_data_port.getText().trim();
         config.targets= new Vector();
         for( int i= 0; i < targets.size(); i++) {
         Target target= (Target) targets.elementAt( i);
         if( target.localPort.equals( config.local_data_port)) {
              config.addTarget( target.ip, target.port);
         config.media_locator= tf_media_file.getText().trim();
         config.write();
    System.exit( 0);
    public void windowClosed( WindowEvent event) {
    public void windowDeiconified( WindowEvent event) {
    public void windowIconified( WindowEvent event) {
    public void windowActivated( WindowEvent event) {
    public void windowDeactivated( WindowEvent event) {
    public void windowOpened( WindowEvent event) {
    public void keyPressed( KeyEvent event) {
    public void keyReleased( KeyEvent event) {
    Object source= event.getSource();
         if( source == list) {
         int index= list.getSelectedIndex();
    public void keyTyped( KeyEvent event) {
    public void mousePressed( MouseEvent e) {
    public void mouseReleased( MouseEvent e) {
    public void mouseEntered( MouseEvent e) {
    public void mouseExited( MouseEvent e) {
    public void mouseClicked( MouseEvent e) {
    Object source= e.getSource();
         if( source == list) {
         int index= list.getSelectedIndex();
         if( index != -1) {
              Target target= (Target) targets.elementAt( index);
              tf_remote_address.setText( target.ip);
              tf_remote_data_port.setText( target.port);
         int index= list.locationToIndex( e.getPoint());
    public static void main( String[] args) {
    new Tx();
    class TargetListModel extends AbstractListModel {
    private Vector options;
    public TargetListModel( Vector options) {
         this.options= options;
    public int getSize() {
         int size;
         if( options == null) {
         size= 0;
         } else {
         size= options.size();
         return size;
    public Object getElementAt( int index) {
    String name;
    if( index < getSize()) {
         Target o= (Target)options.elementAt( index);
    name= o.localPort + " ---> " + o.ip + ":" + o.port;
         } else {
         name= null;
         return name;
    public void setData( Vector data) {
         options= data;
         fireContentsChanged( this, 0, data.size());
    class ListUpdater implements Runnable {
    String localPort, ip, port;
    TargetListModel listModel;
    Vector targets;
    public ListUpdater( String localPort, String ip, String port,
                   TargetListModel listModel, Vector targets) {
         this.localPort= localPort;
         this.ip= ip;
         this.port= port;
         this.listModel= listModel;
         this.targets= targets;
    public void run() {
    Target target= new Target( localPort, ip, port);
         if( !targetExists( localPort, ip, port)) {
         targets.addElement( target);
    listModel.setData( targets);
    public boolean targetExists( String localPort, String ip, String port) {
         boolean exists= false;
         for( int i= 0; i < targets.size(); i++) {
         Target target= (Target) targets.elementAt( i);
         if( target.localPort.equals( localPort)
         && target.ip.equals( ip)
              && target.port.equals( port)) {          
              exists= true;
         break;
         return exists;
    >>>>>>>>>>>>>>>>>
    import java.awt.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.*;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    public class AVTransmitter implements ReceiveStreamListener, RemoteListener,
    ControllerListener {
    // Input MediaLocator
    // Can be a file or http or capture source
    private MediaLocator locator;
    private String ipAddress;
    private int portBase;
    private Processor processor = null;
    private RTPManager rtpMgrs[];
    private int localPorts[];
    private DataSource dataOutput = null;
    private int local_data_port;
    private Tx tx;
    public AVTransmitter( Tx tx, int data_port) {
         this.tx= tx;
         local_data_port= data_port;
    * Starts the transmission. Returns null if transmission started ok.
    * Otherwise it returns a string with the reason why the setup failed.
    public synchronized String start( String filename, Vector targets) {
         String result;
         locator= new MediaLocator( filename);
         // Create a processor for the specified media locator
         // and program it to output JPEG/RTP
         result = createProcessor();
         if (result != null) {
         return result;
         // Create an RTP session to transmit the output of the
         // processor to the specified IP address and port no.
         result = createTransmitter( targets);
         if (result != null) {
         processor.close();
         processor = null;
         return result;
         // Start the transmission
         processor.start();
         return null;
    * Use the RTPManager API to create sessions for each media
    * track of the processor.
    private String createTransmitter( Vector targets) {
         // Cheated. Should have checked the type.
         PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
         PushBufferStream pbss[] = pbds.getStreams();
         rtpMgrs = new RTPManager[pbss.length];
         localPorts = new int[ pbss.length];
         SessionAddress localAddr, destAddr;
         InetAddress ipAddr;
         SendStream sendStream;
         int port;
         SourceDescription srcDesList[];
         for (int i = 0; i < pbss.length; i++) {
         // for (int i = 0; i < 1; i++) {
         try {
              rtpMgrs[i] = RTPManager.newInstance();     
              port = local_data_port + 2*i;
              localPorts[ i]= port;
              localAddr = new SessionAddress( InetAddress.getLocalHost(),
                                  port);
              rtpMgrs.initialize( localAddr);          
              rtpMgrs[i].addReceiveStreamListener(this);
              rtpMgrs[i].addRemoteListener(this);
         for( int k= 0; k < targets.size(); k++) {
              Target target= (Target) targets.elementAt( k);
              int targetPort= new Integer( target.port).intValue();
              addTarget( localPorts[ i], rtpMgrs[ i], target.ip, targetPort + 2*i);
              sendStream = rtpMgrs[i].createSendStream(dataOutput, i);          
              sendStream.start();
         } catch (Exception e) {
              e.printStackTrace();
              return e.getMessage();
         return null;
    public void addTarget( String ip, String port) {
         for (int i= 0; i < rtpMgrs.length; i++) {
         int targetPort= new Integer( port).intValue();
         addTarget( localPorts[ i], rtpMgrs[ i], ip, targetPort + 2*i);
    public void addTarget( int localPort, RTPManager mgr, String ip, int port) {
         try {
         SessionAddress addr= new SessionAddress( InetAddress.getByName( ip),
                                  new Integer( port).intValue());
         mgr.addTarget( addr);
         tx.addTargetToList( localPort + "", ip, port + "");
         } catch( Exception e) {
         e.printStackTrace();
    public void removeTarget( String ip, String port) {
         try {     
         SessionAddress addr= new SessionAddress( InetAddress.getByName( ip),
                                  new Integer( port).intValue());
         for (int i= 0; i < rtpMgrs.length; i++) {
         rtpMgrs[ i].removeTarget( addr, "target removed from transmitter.");
         } catch( Exception e) {
         e.printStackTrace();
    boolean looping= true;
    public void controllerUpdate( ControllerEvent ce) {
         System.out.println( ce);
         if( ce instanceof DurationUpdateEvent) {
         Time duration= ((DurationUpdateEvent) ce).getDuration();
         System.out.println( "duration: " + duration.getSeconds());
         } else if( ce instanceof EndOfMediaEvent) {
         System.out.println( "END OF MEDIA - looping=" + looping);
         if( looping) {
         processor.setMediaTime( new Time( 0));
              processor.start();
    public void setLooping( boolean flag) {
         looping= flag;
    public void update( ReceiveStreamEvent event) {
         String timestamp= getTimestamp();
         StringBuffer sb= new StringBuffer();
         if( event instanceof InactiveReceiveStreamEvent) {
         sb.append( timestamp + " Inactive Receive Stream");
         } else if( event instanceof ByeEvent) {
         sb.append( timestamp + " Bye");
         } else {
         System.out.println( "ReceiveStreamEvent: "+ event);
         tx.rtcpReport( sb.toString());     
    public void update( RemoteEvent event) {     
         String timestamp= getTimestamp();
         if( event instanceof ReceiverReportEvent) {
         ReceiverReport rr= ((ReceiverReportEvent) event).getReport();
         StringBuffer sb= new StringBuffer();
         sb.append( timestamp + " RR");
         if( rr != null) {
              Participant participant= rr.getParticipant();
              if( participant != null) {
              sb.append( " from " + participant.getCNAME());
              sb.append( " ssrc=" + rr.getSSRC());
              } else {
              sb.append( " ssrc=" + rr.getSSRC());
              tx.rtcpReport( sb.toString());
         } else {
         System.out.println( "RemoteEvent: " + event);
    private String getTimestamp() {
         String timestamp;
         Calendar calendar= Calendar.getInstance();
         int hour= calendar.get( Calendar.HOUR_OF_DAY);
         String hourStr= formatTime( hour);
         int minute= calendar.get( Calendar.MINUTE);
         String minuteStr= formatTime( minute);
         int second= calendar.get( Calendar.SECOND);
         String secondStr= formatTime( second);
         timestamp= hourStr + ":" + minuteStr + ":" + secondStr;     
         return timestamp;
    private String formatTime( int time) {     
         String timeStr;
         if( time < 10) {
         timeStr= "0" + time;
         } else {
         timeStr= "" + time;
         return timeStr;
    * Stops the transmission if already started
    public void stop() {
         synchronized (this) {
         if (processor != null) {
              processor.stop();
              processor.close();
              processor = null;
         for (int i= 0; i < rtpMgrs.length; i++) {
         rtpMgrs[ i].removeTargets( "Session ended.");
              rtpMgrs[ i].dispose();
    public String createProcessor() {
         if (locator == null) {
         return "Locator is null";
         DataSource ds;
         DataSource clone;
         try {
         ds = javax.media.Manager.createDataSource(locator);
         } catch (Exception e) {
         return "Couldn't create DataSource";
         // Try to create a processor to handle the input media locator
         try {
         processor = javax.media.Manager.createProcessor(ds);
         processor.addControllerListener( this);     
         } catch (NoProcessorException npe) {
         return "Couldn't create processor";
         } catch (IOException ioe) {
         return "IOException creating processor";
         // Wait for it to configure
         boolean result = waitForState(processor, Processor.Configured);
         if (result == false)
         return "Couldn't configure processor";
         // Get the tracks from the processor
         TrackControl [] tracks = processor.getTrackControls();
         // Do we have atleast one track?
         if (tracks == null || tracks.length < 1)
         return "Couldn't find tracks in processor";
         // Set the output content descriptor to RAW_RTP
         // This will limit the supported formats reported from
         // Track.getSupportedFormats to only valid RTP formats.
         ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
         processor.setContentDescriptor(cd);
         Format supported[];
         Format chosen;
         boolean atLeastOneTrack = false;
         // Program the tracks.
         for (int i = 0; i < tracks.length; i++) {
         Format format = tracks[i].getFormat();
         if (tracks[i].isEnabled()) {
              supported = tracks[i].getSupportedFormats();
              // We've set the output content to the RAW_RTP.
              // So all the supported formats should work with RTP.
              // We'll just pick the first one.
              if (supported.length > 0) {
              if (supported[0] instanceof VideoFormat) {
                   // For video formats, we should double check the
                   // sizes since not all formats work in all sizes.
                   chosen = checkForVideoSizes(tracks[i].getFormat(),
                                       supported[0]);
              } else
                   chosen = supported[0];
              tracks[i].setFormat(chosen);
              System.err.println("Track " + i + " is set to transmit as:");
              System.err.println(" " + chosen);
              atLeastOneTrack = true;
              } else
              tracks[i].setEnabled(false);
         } else
              tracks[i].setEnabled(false);
         if (!atLeastOneTrack)
         return "Couldn't set any of the tracks to a valid RTP format";
         // Realize the processor. This will internally create a flow
         // graph and attempt to create an output datasource for JPEG/RTP
         // audio frames.
         result = waitForState(processor, Controller.Realized);
         if (result == false)
         return "Couldn't realize processor";
         // Set the JPEG quality to .5.
         setJPEGQuality(processor, 0.5f);
         // Get the output data source of the processor
         dataOutput = processor.getDataOutput();
         return null;
    static SessionAddress destAddr1, destAddr2;
    * For JPEG and H263, we know that they only work for particular
    * sizes. So we'll perform extra checking here to make sure they
    * are of the right sizes.
    Format checkForVideoSizes(Format original, Format supported) {
         int width, height;
         Dimension size = ((VideoFormat)original).getSize();
         Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
         Format h263Fmt = new Format(VideoFormat.H263_RTP);
         if (supported.matches(jpegFmt)) {
         // For JPEG, make sure width and height are divisible by 8.
         width = (size.width % 8 == 0 ? size.width :
                        (int)(size.width / 8) * 8);
         height = (size.height % 8 == 0 ? size.height :
                        (int)(size.height / 8) * 8);
         } else if (supported.matches(h263Fmt)) {
         // For H.263, we only support some specific sizes.
         if (size.width < 128) {
              width = 128;
              height = 96;
         } else if (size.width < 176) {
              width = 176;
              height = 144;
         } else {
              width = 352;
              height = 288;
         } else {
         // We don't know this particular format. We'll just
         // leave it alone then.
         return supported;
         return (new VideoFormat(null,
                        new Dimension(width, height),
                        Format.NOT_SPECIFIED,
                        null,
                        Format.NOT_SPECIFIED)).intersects(supported);
    * Setting the encoding quality to the specified value on the JPEG encoder.
    * 0.5 is a good default.
    void setJPEGQuality(Player p, float val) {
         Control cs[] = p.getControls();
         QualityControl qc = null;
         VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
         // Loop through the controls to find the Quality control for
         // the JPEG encoder.
         for (int i = 0; i < cs.length; i++) {
         if (cs[i] instanceof QualityControl &&
              cs[i] instanceof Owned) {
              Object owner = ((Owned)cs[i]).getOwner();
              // Check to see if the owner is a Codec.
              // Then check for the output format.
              if (owner instanceof Codec) {
              Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
              for (int j = 0; j < fmts.length; j++) {
                   if (fmts[j].matches(jpegFmt)) {
                   qc = (QualityControl)cs[i];
                   qc.setQuality(val);
                   System.err.println("- Setting quality to " +
                             val + " on " + qc);
                   break;
              if (qc != null)
              break;
    * Convenience methods to handle processor's state changes.
    private Integer stateLock = new Integer(0);
    private boolean failed = false;
    Integer getStateLock() {
         return stateLock;
    void setFailed() {
         failed = true;
    private synchronized boolean waitForState(Processor p, int state) {
         p.addControllerListener(new StateListener());
         failed = false;
         // Call the required method on the processor
         if (state == Processor.Configured) {
         p.configure();
         } else if (state == Processor.Realized) {
         p.realize();
         // Wait until we get an event that confirms the
         // success of the method, or a failure event.
         // See StateListener inner class
         while (p.getState() < state && !failed) {
         synchronized (getStateLock()) {
              try {
              getStateLock().wait();
              } catch (InterruptedException ie) {
              return false;
         if (failed)
         return false;
         else
         return true;
    * Inner Classes
    class StateListener implements ControllerListener {
         public void controllerUpdate(ControllerEvent ce) {
         // If there was an error during configure or
         // realiz

    I do this all the time, I put my MBP to a 60 inch Sharp. If you have the video working do the simple thing first. Check to make sure your sound is on your TV and Mac. Then if that doesn't work go to System Prefrences and under sound go to a tab called Output and see if your TV is listed and if it is change it to that setting
    Hope It Works

  • Overlay Images and Shapes on the same canvas

    The example copde below was taken from: http://math.hws.edu/eck/cs124/javanotes3/source/
    Is it possible to update the code so that images (jpg,gif) can be added as well as shapes?
    Any help with this is much appreciated.
        The ShapeDraw applet lets the user add small colored shapes to
        a drawing area and then drag them around.  The shapes are rectangles,
        ovals, and roundrects.  The user adds a shape to the canvas by
        clicking on a button.  The shape is added at the upper left corner
        of the canvas.  The color of the shape is given by the current
        setting of a pop-up menu.  The user can drag the shapes with the
        mouse.  Ordinarily, the shapes maintain a given back-to-front order.
        However, if the user shift-clicks on a shape, that shape will be
        brought to the front.
        A menu can be popped up on a shape (by right-clicking or performing
        some othe platform-dependent action).  This menu allows the user
        to change the size and color of a shape.  It is also possible to
        delete the shape and to bring it to the front.
        This file defines the applet class plus several other classes used
        by the applet, namely:  ShapeCanvas, Shape, RectShape, OvalShape,
        and RoundRectShape.
        David Eck
        July 28,  1998
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.util.Vector;
    public class ShapeDrawWithMenu extends Applet {
       public void init() { 
            // Set up the applet's GUI.  It consists of a canvas, or drawing area,
            // plus a row of controls below the canvas.  The controls include three
            // buttons which are used to add shapes to the canvas and a Choice menu
            // that is used to select the color used for a shape when it is created.
            // The canvas is set as the "listener" for these controls so that it can
            // respond to the user's actions.  (The pop-up menu is created by the canvas.)
          setBackground(Color.lightGray);
          ShapeCanvas canvas = new ShapeCanvas();  // create the canvas
          Choice colorChoice = new Choice();  // color choice menu
          colorChoice.add("Red");
          colorChoice.add("Green");
          colorChoice.add("Blue");
          colorChoice.add("Cyan");
          colorChoice.add("Magenta");
          colorChoice.add("Yellow");
          colorChoice.add("Black");
          colorChoice.add("White");
          colorChoice.addItemListener(canvas);
          Button rectButton = new Button("Rect");    // buttons for adding shapes
          rectButton.addActionListener(canvas);
          Button ovalButton = new Button("Oval");
          ovalButton.addActionListener(canvas);
          Button roundRectButton = new Button("RoundRect");
          roundRectButton.addActionListener(canvas);
          Panel bottom = new Panel();   // a Panel to hold the control buttons
          bottom.setLayout(new GridLayout(1,4,3,3));
          bottom.add(rectButton);
          bottom.add(ovalButton);
          bottom.add(roundRectButton);
          bottom.add(colorChoice);
          setLayout(new BorderLayout(3,3));
          add("Center",canvas);              // add canvas and controls to the applet
          add("South",bottom);
       public Insets getInsets() {
            // Says how much space to leave between the edges of the applet and the
            // components in the applet.
          return new Insets(3,3,3,3);
    }  // end class ShapeDraw
    class ShapeCanvas extends Canvas implements ActionListener, ItemListener,
                                                MouseListener, MouseMotionListener {
          // This class represents a canvas that can display colored shapes and
          // let the user drag them around.  It uses an off-screen images to
          // make the dragging look as smooth as possible.  A pop-up menu is
          // added to the canvas that can be used to performa certain actions
          // on the shapes;
       Image offScreenCanvas = null;   // off-screen image used for double buffering
       Graphics offScreenGraphics;     // graphics context for drawing to offScreenCanvas
       Vector shapes = new Vector();   // holds a list of the shapes that are displayed on the canvas
       Color currentColor = Color.red; // current color; when a shape is created, this is its color
       ShapeCanvas() {
            // Constructor: set background color to white, set up listeners to respond to mouse actions,
            //              and set up the pop-up menu
          setBackground(Color.white);
          addMouseListener(this);
          addMouseMotionListener(this);
          popup = new PopupMenu();
          popup.add("Red");
          popup.add("Green");
          popup.add("Blue");
          popup.add("Cyan");
          popup.add("Magenta");
          popup.add("Yellow");
          popup.add("Black");
          popup.add("White");
          popup.addSeparator();
          popup.add("Big");
          popup.add("Medium");
          popup.add("Small");
          popup.addSeparator();
          popup.add("Delete");
          popup.add("Bring To Front");
          add(popup);
          popup.addActionListener(this);
       } // end construtor
       synchronized public void paint(Graphics g) {
            // In the paint method, everything is drawn to an off-screen canvas, and then
            // that canvas is copied onto the screen.
          makeOffScreenCanvas();
          g.drawImage(offScreenCanvas,0,0,this);
       public void update(Graphics g) {
            // Update method is called when canvas is to be redrawn.
            // Just call the paint method.
          paint(g);
       void makeOffScreenCanvas() {
             // Erase the off-screen canvas and redraw all the shapes in the list.
             // (First, if canvas has not yet been created, then create it.)
          if (offScreenCanvas == null) {
             offScreenCanvas = createImage(getSize().width,getSize().height);
             offScreenGraphics = offScreenCanvas.getGraphics();
          offScreenGraphics.setColor(getBackground());
          offScreenGraphics.fillRect(0,0,getSize().width,getSize().height);
          int top = shapes.size();
          for (int i = 0; i < top; i++) {
             Shape s = (Shape)shapes.elementAt(i);
             s.draw(offScreenGraphics);
       public void itemStateChanged(ItemEvent evt) {
              // This is called to respond to item events.  Such events
              // can only be sent by the color choice menu,
              // so respond by setting the current color according to
              // the selected item in that menu.
          Choice colorChoice = (Choice)evt.getItemSelectable();
          switch (colorChoice.getSelectedIndex()) {
             case 0: currentColor = Color.red;     break;
             case 1: currentColor = Color.green;   break;
             case 2: currentColor = Color.blue;    break;
             case 3: currentColor = Color.cyan;    break;
             case 4: currentColor = Color.magenta; break;
             case 5: currentColor = Color.yellow;  break;
             case 6: currentColor = Color.black;   break;
             case 7: currentColor = Color.white;   break;
       public void actionPerformed(ActionEvent evt) {
              // Called to respond to action events.  The three shape-adding
              // buttons have been set up to send action events to this canvas.
              // Respond by adding the appropriate shape to the canvas.  This
              // also be a command from a pop-up menu.
          String command = evt.getActionCommand();
          if (command.equals("Rect"))
             addShape(new RectShape());
          else if (command.equals("Oval"))
             addShape(new OvalShape());
          else if (command.equals("RoundRect"))
             addShape(new RoundRectShape());
          else
             doPopupMenuCommand(command);
       synchronized void addShape(Shape shape) {
              // Add the shape to the canvas, and set its size/position and color.
              // The shape is added at the top-left corner, with size 50-by-30.
              // Then redraw the canvas to show the newly added shape.
          shape.setColor(currentColor);
          shape.reshape(3,3,50,30);
          shapes.addElement(shape);
          repaint();
       // ------------ This rest of the class implements dragging and the pop-up menu ---------------------
       PopupMenu popup;
       Shape selectedShape = null;     // This is null unless a menu has been popped up on this shape.
       Shape draggedShape = null;      // This is null unless a shape has been selected for dragging.
       int prevDragX;  // During dragging, these record the x and y coordinates of the
       int prevDragY;  //    previous position of the mouse.
       Shape clickedShape(int x, int y) {
             // Find the frontmost shape at coordinates (x,y); return null if there is none.
          for ( int i = shapes.size() - 1; i >= 0; i-- ) {  // check shapes from front to back
             Shape s = (Shape)shapes.elementAt(i);
             if (s.containsPoint(x,y))
                return s;
          return null;
       void doPopupMenuCommand(String command) {
             // Handle a command from the pop-up menu.
          if (selectedShape == null)  // should be impossible
             return;
          if (command.equals("Red"))
             selectedShape.setColor(Color.red);
          else if (command.equals("Green"))
             selectedShape.setColor(Color.green);
          else if (command.equals("Blue"))
             selectedShape.setColor(Color.blue);
          else if (command.equals("Cyan"))
             selectedShape.setColor(Color.cyan);
          else if (command.equals("Magenta"))
             selectedShape.setColor(Color.magenta);
          else if (command.equals("Yellow"))
             selectedShape.setColor(Color.yellow);
          else if (command.equals("Black"))
             selectedShape.setColor(Color.black);
          else if (command.equals("White"))
             selectedShape.setColor(Color.white);
          else if (command.equals("Big"))
             selectedShape.resize(75,45);
          else if (command.equals("Medium"))
             selectedShape.resize(50,30);
          else if (command.equals("Small"))
             selectedShape.resize(25,15);
          else if (command.equals("Delete"))
             shapes.removeElement(selectedShape);
          else if (command.equals("Bring To Front")) {
             shapes.removeElement(selectedShape);
             shapes.addElement(selectedShape);
          repaint();
       synchronized public void mousePressed(MouseEvent evt) {
             // User has pressed the mouse.  Find the shape that the user has clicked on, if
             // any.  If there is a shape at the position when the mouse was clicked, then
             // start dragging it.  If the user was holding down the shift key, then bring
             // the dragged shape to the front, in front of all the other shapes.
          int x = evt.getX();  // x-coordinate of point where mouse was clicked
          int y = evt.getY();  // y-coordinate of point
          if (evt.isPopupTrigger()) {            // If this is a pop-up menu event that
             selectedShape = clickedShape(x,y);  // occurred over a shape, record which shape
             if (selectedShape != null)          // it is and show the menu.
                popup.show(this,x,y);
          else {
             draggedShape = clickedShape(x,y);
             if (draggedShape != null) {
                prevDragX = x;
                prevDragY = y;
                if (evt.isShiftDown()) {                 // Bring the shape to the front by moving it to
                   shapes.removeElement(draggedShape);  //       the end of the list of shapes.
                   shapes.addElement(draggedShape);
                   repaint();  // repaint canvas to show shape in front of other shapes
       synchronized public void mouseDragged(MouseEvent evt) {
              // User has moved the mouse.  Move the dragged shape by the same amount.
          if (draggedShape != null) {
             int x = evt.getX();
             int y = evt.getY();
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
       synchronized public void mouseReleased(MouseEvent evt) {
              // User has released the mouse.  Move the dragged shape, then set
              // shapeBeingDragged to null to indicate that dragging is over.
              // If the shape lies completely outside the canvas, remove it
              // from the list of shapes (since there is no way to ever move
              // it back onscreen).
          int x = evt.getX();
          int y = evt.getY();
          if (draggedShape != null) {
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             if ( draggedShape.left >= getSize().width || draggedShape.top >= getSize().height ||
                     draggedShape.left + draggedShape.width < 0 ||
                     draggedShape.top + draggedShape.height < 0 ) {  // shape is off-screen
                shapes.removeElement(draggedShape);  // remove shape from list of shapes
             draggedShape = null;
             repaint();
          else if (evt.isPopupTrigger()) {        // If this is a pop-up menu event that
             selectedShape = clickedShape(x,y);   // occurred over a shape, record the
             if (selectedShape != null)           // shape and show the menu.
                popup.show(this,x,y);
       public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
       public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
       public void mouseMoved(MouseEvent evt) { }
       public void mouseClicked(MouseEvent evt) { }
    }  // end class ShapeCanvas
    abstract class Shape {
          // A class representing shapes that can be displayed on a ShapeCanvas.
          // The subclasses of this class represent particular types of shapes.
          // When a shape is first constucted, it has height and width zero
          // and a default color of white.
       int left, top;      // Position of top left corner of rectangle that bounds this shape.
       int width, height;  // Size of the bounding rectangle.
       Color color = Color.white;  // Color of this shape.
       void reshape(int left, int top, int width, int height) {
             // Set the position and size of this shape.
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
       void resize(int width,int height) {
             // Set the size without changing the position
          this.width = width;
          this.height = height;
       void moveTo(int x, int y) {
              // Move upper left corner to the point (x,y)
          this.left = x;
          this.top = y;
       void moveBy(int dx, int dy) {
              // Move the shape by dx pixels horizontally and dy pixels veritcally
              // (by changing the position of the top-left corner of the shape).
          left += dx;
          top += dy;
       void setColor(Color color) {
              // Set the color of this shape
          this.color = color;
       boolean containsPoint(int x, int y) {
             // Check whether the shape contains the point (x,y).
             // By default, this just checks whether (x,y) is inside the
             // rectangle that bounds the shape.  This method should be
             // overridden by a subclass if the default behaviour is not
             // appropriate for the subclass.
          if (x >= left && x < left+width && y >= top && y < top+height)
             return true;
          else
             return false;
       abstract void draw(Graphics g); 
             // Draw the shape in the graphics context g.
             // This must be overriden in any concrete subclass.
    }  // end of class Shape
    class RectShape extends Shape {
          // This class represents rectangle shapes.
       void draw(Graphics g) {
          g.setColor(color);
          g.fillRect(left,top,width,height);
          g.setColor(Color.black);
          g.drawRect(left,top,width,height);
    class OvalShape extends Shape {
           // This class represents oval shapes.
       void draw(Graphics g) {
          g.setColor(color);
          g.fillOval(left,top,width,height);
          g.setColor(Color.black);
          g.drawOval(left,top,width,height);
       boolean containsPoint(int x, int y) {
             // Check whether (x,y) is inside this oval, using the
             // mathematical equation of an ellipse.
          double rx = width/2.0;   // horizontal radius of ellipse
          double ry = height/2.0;  // vertical radius of ellipse
          double cx = left + rx;   // x-coord of center of ellipse
          double cy = top + ry;    // y-coord of center of ellipse
          if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry )
             return true;
          else
            return false;
    class RoundRectShape extends Shape {
           // This class represents rectangle shapes with rounded corners.
           // (Note that it uses the inherited version of the
           // containsPoint(x,y) method, even though that is not perfectly
           // accurate when (x,y) is near one of the corners.)
       void draw(Graphics g) {
          g.setColor(color);
          g.fillRoundRect(left,top,width,height,width/3,height/3);
          g.setColor(Color.black);
          g.drawRoundRect(left,top,width,height,width/3,height/3);
    }

    Manveer-Singh
    Please don't post in old threads that are long dead. When you have a question, please start a topic of your own. Feel free to provide a link to an old thread if relevant.
    I'm locking this 3 year old thread now.
    db
    edit You have earlier been advised not to post in old dead threads.
    [http://forums.sun.com/thread.jspa?threadID=354443]
    Continuing to ignore this advice will render your account liable to be blocked.
    Edited by: Darryl.Burke

  • Resizing JFrame on button click to show an image on the JFrame

    Dear All,
    I have a JFrame which has an empty label. On button click I want to set an icon for the label and want the JFrame to be resized to show that icon. I am using frame.pack() and I am not using any other sizing function. The code that I have right now, prints the image on the panel, but does not resize the frame to show the image. Pleae could someone help.package gui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class ComponentDemo extends JPanel implements ActionListener,
    ItemListener, MouseListener, KeyListener {
         private JTextArea textarea;
         private JButton button;
         private final static String newline = "\n";
         private JLabel imageIcon;
         public ComponentDemo() {
              button = new JButton("JButton welcomes you  to CO2001");
              button.addActionListener(this);
              add(button);
              textarea = new JTextArea(10, 50);
              textarea.setEditable(false);
              addMouseListener(this);
              textarea.addKeyListener(this);
              JScrollPane scrollPane = new JScrollPane(textarea);
              add(scrollPane);
              imageIcon = new JLabel();
              add(imageIcon);
              setBackground(Color.pink);
              new JScrollPane(this);
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("Simple FrameDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation(700, 200);
              // get the content pane and set the background colour;
              frame.add(new ComponentDemo());
         //     frame.setSize(screenSize);
              // frame.getContentPane().setBackground(Color.cyan);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setResizable(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         @Override
         public void actionPerformed(ActionEvent e) {
              // TODO Auto-generated method stub
              if (e.getSource() instanceof JButton) {
                   // System.out.println(e.getSource());
                   String text = ((JButton) e.getSource()).getText();
                   textarea.append(text + newline);
                   textarea.setBackground(Color.cyan);
                   textarea.setForeground(Color.BLUE);
                   textarea.setCaretPosition(textarea.getDocument().getLength());
                   imageIcon.setIcon(createImageIcon("SwingingDuke.png",
                   "Image to be displayed"));
         @Override
         public void itemStateChanged(ItemEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseClicked(MouseEvent arg0) {
              textarea.append("A Mouse click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.green);
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent e) {
              System.out.println(e.getKeyChar());
              textarea.append("The key " + e.getKeyChar()
                        + " click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.YELLOW);
              textarea.setFont(new Font("Arial", Font.ITALIC, 16));
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyReleased(KeyEvent e) {
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.green);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyTyped(KeyEvent e) {
              // TODO Auto-generated method stub
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.blue);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected ImageIcon createImageIcon(String path, String description) {
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null) {
                   System.out.println("found");
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
    }

    myJPanel.setPerferredSize(new Dimension(new_width, new_hight));
    myJFrame.pack();

  • Subclassing the AbstractButton class

    I am having problem to define my own button class that subclasses the AbstractButton class. I used setBorder(Border b) to set the border for the button but how can I draw the text(caption) of the button. And what should I do to change the background color of the button when the button is pressed. (I have tried to use ActionListener and MouseListener but it didn't work) ????
    any help is highly appreciated!
    regards,

    Check if this is what you are looking for. Hope it helps
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    class TestCustomButton
         public static void main(String args[])
              JFrame fr = new JFrame("Testing Custom button");
              JButton button = new JButton("My Button");
              button.addActionListener(new MyListener());
              fr.getContentPane().add(button);
              fr.setSize(200,200);
              fr.setVisible(true);
    class MyListener implements ActionListener
         public void actionPerformed(ActionEvent ae)
              ((JButton)(ae.getSource())).setText("");
    }

  • TreeSelectionListener

    A question about the TreeSelectionListener. I was having trouble adding the interface to my app, and after reading one of the examples under the JTree tutorials, I tried adding an import statement for TreeSelectionListener, along with TreeSelectionEvent, which fixed the problem. My question is, why is that necessary? I've never had to import a listener interface or event class before today, with ActionListener or MouseListener or any of the other commonly used interfaces. Thx.

    That is probably just a fluke that you have never had to do this. Listener classes and interfaces are usually in different packages so you always will have to import those packages.
    Bryan

  • Preferred style of event handling?

    Having developed several java applications I found that my preferred method of event handling in java is to have one component (often named EventHandler) which implements ActionListener's, MouseListener's, ListSelectionListeners, etc. I like this approach because it allows me to finalize code such as menu bars, toolbars, etc and essentially turns the EventHandler into the engine of the application.
    The problem I often run into is that while a lot of our code is finalized and can be left alone, the EventHandler becomes monstrously large with all of the logic code necessary to make the application accomplish it's task.
    I would really appreciate some ideas/opinions on this topic and possibly ways to improve this design which might make it easier to handle the events of a java app.

    I find it useful to create event handlers that focus on a particular function like a toolbar or menubar or whatever. For example, I would create a MyFrameMenuEventHandler for all menu events. If that became to cumbersome I would break the event handler up into menus like MyFrameFileMenuEventHandler and MyFrameEditMenuEventHandler.
    All of my event handlers really do nothing but call handler methods on the parent object from which the event originated (usually a frame object). This allows mapping of the same event from different sources to the same handler code.
    It also allows subclasses to override the handler methods without needing to modify the event handlers. It is also useful for providing hooks like afterFileOpen and beforeFileOpen for the handleFileOpen handler method.
    If the class containing the handler methods becomes to cumbersome you could subclass the frame, for instance, and include a logical subset of handler methods. Provide additional subclasses for the remaining handler methods. For example, you might have MyFrame, which creates components, sets layout, providers component accessor methods, and creates event handlers and registers components. Then create a subclass of MyFrame called MyFrameMenuHandler that contains all handler methods for menu events and so on.
    Although if classes start getting this big you probably would need to break it up into logical components to make it more manageable.
    I have used this technique both in Java and Forte 4GL--where I original used the technique.

  • Making thread

    Hi , everyone , i have a homework to do , i want to make this SSWindow class as a thread or implements a runnable method , but i have no idea to solve this , can anyone help me please ?
    // SSWindow class
    import javax.swing.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    * The Slide Show window
    public class SSWindow extends JWindow implements
    ActionListener, FileFilter , MouseListener {
    /** The image label */
    JLabel imageLabel;
    /** The parent */
    JFrame parent;
    /** The directory */
    String direc;
    /** List of files in the directory */
    String[] filenames;
    /** Delay in milliseconds */
    int delay;
    /** Counter */
    int count;
    /** The timer that displays the Slide Show */
    Timer timer;
    /* Constructor */
    public SSWindow(JFrame par, String direc, float seconds) {
         super(par);
         parent = par;
         this.direc = direc;
         delay = (int)(seconds*1000);
         // Add label to center of screen
         Container back = getContentPane();
         imageLabel = new JLabel();
         back.setBackground(Color.black);
         back.add(imageLabel);
         imageLabel.setVerticalAlignment(JLabel.CENTER);
         imageLabel.setHorizontalAlignment(JLabel.CENTER);
         setSize(getToolkit().getScreenSize());
         setVisible(true);
         // Get the names of the files
         File[] files = (new File(direc)).listFiles(this);
         filenames = new String[files.length];
         for (int i=0; i<filenames.length; i++) {
              filenames[i] = files.toString();
         count = -1;
         timer = new Timer(delay, this);
         timer.start();
    } // End constructor
    /** Function that changes the image */
    public void updateImage() {
         try {
              imageLabel.setIcon(new ImageIcon(filenames[count]));
              imageLabel.addMouseListener(this);
         } catch(Exception ex) {
              timer.stop();
              SSWindow.this.dispose();
              parent.setVisible(true);
    } // End updateImage()
    public void mouseClicked(MouseEvent e)
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    public void mousePressed(MouseEvent e)
         timer.stop();
         parent.setVisible(true);
         SSWindow.this.dispose();
    public void mouseReleased(MouseEvent e)
    public void actionPerformed(ActionEvent e) {
         count++;
    // If we have gone past the last file,...*/
    // return to beginning.
         if (count > (filenames.length-1)) {
              count = 0;
         updateImage();
    } // End actionPerformed()
    public boolean accept(File file) {
         String filename = file.toString();
         if (filename.endsWith(".tiff") ||
         filename.endsWith(".tif") ||
         filename.endsWith(".gif") ||
         filename.endsWith(".jpeg") ||
         filename.endsWith(".jpg")) {
              return true;
         } else {
              return false;
    } // End accept()
    } // End class SSWindow
    // Here is the main class
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    * The Slide Show's Opening Screen
    public class SSFrame extends JFrame {
    JTextField direcText, delayText;
    JFileChooser fc;
    static final String
    WINTITLE="Kengs' Slide Show Viewer",
    DIRECTORY="Directory : ",
    BROWSE="Browse...",
    DELAY="Delay : ",
    TIME="2",
    SECONDS="seconds",
    START="Start SlideShow!",
    ADVANCED="Advanced...",
    ABOUT="About...",
    EXIT="Exit";
    public static void main(String args[])
         SSFrame ss = new SSFrame();
    } // End main()
    public SSFrame() {
    // Set the title
    setTitle(WINTITLE);
         Container back = getContentPane();
         back.setLayout(new GridLayout(0,1));
         back.add(new JLabel(new ImageIcon("images/kss.gif")));
         fc = new JFileChooser();
         fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
         JPanel p1 = new JPanel();
         p1.add(new JLabel(DIRECTORY, new ImageIcon("images/directory.gif"), JLabel.CENTER));
    p1.add(direcText = new JTextField(20));
         JButton browseButton = new JButton(BROWSE, new ImageIcon("images/browse.gif"));
         browseButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    int returnVal = fc.showOpenDialog(SSFrame.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
              direcText.setText(fc.getSelectedFile().toString());
         p1.add(browseButton);
         back.add(p1);
         JPanel p1e = new JPanel();
         p1e.add(new JLabel(DELAY, new ImageIcon("images/delay.gif"), JLabel.CENTER));
         p1e.add(delayText = new JTextField(TIME, 5));
         p1e.add(new JLabel(SECONDS));
         back.add(p1e);
         JPanel p2 = new JPanel();
         JPanel butPanel = new JPanel();
         butPanel.setBorder(BorderFactory.createLineBorder(Color.black));
         JButton startButton = new JButton(START, new ImageIcon("images/start.gif"));
         startButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
              SSFrame.this.hide();
              SSWindow s = new SSWindow(
              SSFrame.this, direcText.getText(),
              new Float(delayText.getText()).floatValue()
         butPanel.add(startButton);
         p2.add(butPanel);
         JButton aboutButton = new JButton(ABOUT, new ImageIcon("images/about.gif"));
         aboutButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
              // Should display message box here
         p2.add(aboutButton);
         JButton exitButton = new JButton(EXIT, new ImageIcon("images/exit.gif"));
         exitButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
              System.exit(0);
         p2.add(exitButton);
         back.add(p2);
         addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
         pack();
         setVisible(true);
    } // End constructor
    } // End class MainFrame

    public class MyRunnable implements Runnable{
    public static void main(String[] args){
    Thread t = new Thread(new MyRunnable());
    t.start();
    public void run(){
    System.out.println("Dead thread walking");
    }I always overwrite start() and stop()
    http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
    This means I have control in a consistent manner when and how I want.
    ie:
    public class MyClass implements Runnable
    static Object waitObject = new Object();
    Thread task;
    pubic void start()
       task = new Thread(this);
       task.start();
    pubic void stop()
       task = null;
    public void run()
    Thread controlThread = Thread.currentThread();
       while(controlThread == task)
              ///do something.
               synchronized waitObject
                    try
                         waitObject.wait(20);   //. preempt (Not sleep) for 20 MS
                     }                     // Set to taste.   proper waits / synchronization
                     catch(InterruptedException ie)  // eliminates races
    }

  • Why is keyPressed() not being executed in this code..??

    HI,
    I am trying to develop a simple game program but what is banging my head is the keyPressed(KeyEvent evnt) is not being executed, i.e. the System.out.println("XXXX") inside this method is not being reached and hence shows no any output. Any suggestion would be appriciated. The code goes like this....
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.geom.*;
    public class ArrowGame
      static GameField gfield;
      private static void createGUI()
        JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame=new JFrame("Arrow Game");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gfield=new GameField();
         frame.getContentPane().add(gfield,BorderLayout.CENTER);
         frame.setVisible(true);
         frame.pack();
      public static void main(String args[])
        SwingUtilities.invokeLater(new Runnable()
           public void run()
             createGUI();
      static class GameField extends JPanel implements ActionListener, KeyListener, MouseListener
        Timer timer;
        int w,h;
         int arrowPos;
         double dynamicX=1.5;
         double ovalX;
         final double ovalY=2.0;
         final double ovalW=45.0;
         final double ovalH=45.0;
         double ovalXX=(ovalX+10);
         final double ovalYY=(ovalY+10);
         double ovalXXX=(ovalXX+10);
         final double ovalYYY=(ovalYY+10);
         private boolean shotTriggered=false;
        GameField()
           setPreferredSize(new Dimension(525,450));
           addMouseListener(this);
           addKeyListener(this);
         public void paintComponent(Graphics g)
           super.paintComponent(g);
          w=getWidth();
           h=getHeight();
           Graphics2D g2=(Graphics2D)g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
           g2.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
           g2.setColor(Color.darkGray);
           g2.fillRect(0,0,w,h);
           drawTarget(g2,w,h);
           drawArrow(g2,w,h);
         private void drawTarget(Graphics2D g2,int w,int h)
           ovalX+=dynamicX;
           ovalXX+=dynamicX;
           ovalXXX+=dynamicX;
           if (ovalX < 0 && ovalXX < 10 && ovalXXX < 20)
             ovalX=0;
              ovalXX=10;
              ovalXXX=20;
             dynamicX=1.5;
           else if (ovalX > (w-45) && ovalXX > (w-35) && ovalXXX > (w-25))
              ovalX=(w-45);
              ovalXX=(w-35);
              ovalXXX=(w-25);
              dynamicX=-1.5;
           g2.setColor(Color.green);
           g2.fill(new Ellipse2D.Double(ovalX,ovalY,ovalW,ovalH));
           g2.setColor(Color.blue);
           g2.fill(new Ellipse2D.Double(ovalXX,ovalYY,(ovalW-20),(ovalH-20)));
           g2.setColor(Color.red);
           g2.fill(new Ellipse2D.Double(ovalXXX,ovalYYY,(ovalW-40),(ovalH-40)));
         private void drawArrow(Graphics2D g2,int w,int h)
           arrowPos=w/2;
           g2.setColor(Color.white);
           g2.drawLine(arrowPos,((h/2)+175),arrowPos,h);
         public void keyPressed(KeyEvent evnt)
           int code=evnt.getKeyCode();
           System.out.println(code);
         public void keyTyped(KeyEvent evnt){}
         public void keyReleased(KeyEvent evnt){}
         public void mousePressed(MouseEvent evt)
           if (timer!=null)
             timer.stop();
              timer=null;
           else
             timer=new Timer(75,this);
             timer.start();
         public void mouseReleased(MouseEvent evt){}
         public void mouseEntered(MouseEvent evt){}
         public void mouseExited(MouseEvent evt){}
         public void mouseClicked(MouseEvent evt){}
         public void actionPerformed(ActionEvent event)
           repaint();
    };regards,
    Jay

      GameField()
        setPreferredSize(new Dimension(525,450));
        setFocusable(true); //<-----------------------------------------
        addMouseListener(this);
        addKeyListener(this);
      }

  • My thread is ceated but doesn't have desired effect. Help?

    Basically I have a jDesktopPane wiith many jInternalFrames. I need each one to be its own thread so if one locks up the whole program doesn't crash. Right now it all works fine, but if you run a method on a huge file in a jInternalFrame it'll lock the whole program up. Using netbeans I can tell that I am indeed creating a thread. I think. ok here's some code- (yes I know its not the simple, compilable, blah blah blah thing. Its 12 java files, I'm not making an example program)
    getCurFrame();
    new Thread(SimpleJavaEditor.ifArr[SimpleJavaEditor.curFrame]=new NewJInternalFrame(SimpleJavaEditor.curFrame,jFileChooser1.getSelectedFile())).start();
    SimpleJavaEditor.jDesktopPane1.add(SimpleJavaEditor.ifArr[SimpleJavaEditor.curFrame]);
    public class NewJInternalFrame extends javax.swing.JInternalFrame implements Runnable, InternalFrameListener, ActionListener, KeyListener, MouseListener {
        @Override
        public void run() {
            initComponents();
            requestFocus();
            jTextPane1.getDocument().addUndoableEditListener(
            new UndoableEditListener() {
              public void undoableEditHappened(UndoableEditEvent e) {
                if(e.getEdit().isSignificant()){
                    undoManager.addEdit(e.getEdit());
            jScrollPane1.getVerticalScrollBar().addAdjustmentListener(new java.awt.event.AdjustmentListener() {
                public void adjustmentValueChanged(AdjustmentEvent e) {
                    if(jScrollPane1.getVerticalScrollBar().getValue()<=jScrollPane2.getVerticalScrollBar().getValue()){
                       jScrollPane2.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getValue());
                    }else{
                       jScrollPane2.getVerticalScrollBar().setValue(jScrollPane2.getVerticalScrollBar().getMaximum());
            jScrollPane2.getVerticalScrollBar().addAdjustmentListener(new java.awt.event.AdjustmentListener() {
                public void adjustmentValueChanged(AdjustmentEvent e) {
                    if(jScrollPane2.getVerticalScrollBar().getValue()<=jScrollPane1.getVerticalScrollBar().getValue()){
                       jScrollPane1.getVerticalScrollBar().setValue(jScrollPane2.getVerticalScrollBar().getValue());
                    }else{
                       jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum());
            FontMetrics fm = jTextPane1.getFontMetrics(jTextPane1.getFont());
            int charWidth = fm.charWidth( 'w' );
            int tabWidth = charWidth * 3;
            TabStop[] tabs = new TabStop[10];
            for (int j=0;j<tabs.length;j++){
                int tab = j + 1;
                tabs[j] = new TabStop(tab*tabWidth);
            TabSet tabSet = new TabSet(tabs);
            SimpleAttributeSet attributes = new SimpleAttributeSet();
            StyleConstants.setTabSet(attributes, tabSet);
            int length = jTextPane1.getDocument().getLength();
            jTextPane1.getStyledDocument().setParagraphAttributes(0, length, attributes, true);
            length = jTextPane2.getDocument().getLength();
            jTextPane2.getStyledDocument().setParagraphAttributes(0, length, attributes, true);
            keyWord();       
        public NewJInternalFrame(int Frame,File fileA) {
            frame=Frame;
            file=fileA;
        }I think that should be enough. Ask if you need more code.
    Thanks
    Edited by: ghostbust555 on Dec 23, 2009 12:57 PM

    ghostbust555 wrote:
    ok here's some code- (yes I know its not the simple, compilable, blah blah blah thing. Its 12 java files, I'm not making an example program)That's your prerogative, but you have to note that we won't put a shred more effort into fixing your problem than you do. And since you aren't making the effort to make an example program, we probably won't go to much effort to help.
    That said, I didn't read your code since it wasn't simple or compilable, but it sounds like you need to do your logic on a separate thread. Try looking at SwingWorker.

  • JDBC Result Set Control

    In Oracle JDBC, when I retrieve data from Oracle server, I would like fetch page by page instead of all the data returned, and allow user scroll up and down.
    How can I do this in Oracle JDBC?
    Thanks,
    null

    But compiling it otherwise fails?
    Yes..it is progress..your event handling is using deprecated methods..if you compile with the deprecation flag, it will tell you where you used them, and compile... at least that way.
    Also..look into java.awt.event.* (Listeners and such)..
    The basic way they work is this:
    1- Implement a Listener interface (ActionListener, XYZListener, MouseListener, whatever).
    2- Implement the methods from that interface (for ActionListener and buttons it is public void actionPerformed(ActionEvent ae))
    3- Add your listener to the GUI element (( element.addActionListener(this); ))
    There is documentation as well.
    ~David

  • Click Double click

    Hi there,
    Just a little question about java. I want to make call a method x when i click on my row and when i do a double click i want to call an different method as y
    I ve found this on the web :
    if (e.getClickCount() == 2)
    System.out.println( "-- and it's a double click!");
    else
    System.out.println( " and it's a simple click!");
    But with this part of code when i double click the simpleclick is also called. Is there another tips to detect a double click ?
    Regards

    Here is some code, it could be made more robust (synchronization, upgraded to 1.5, ...)
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.Timer;
    public class MouseClicked implements MouseListener, ActionListener
         private MouseListener objListener;
         private MouseEvent objEvent;
         private Timer objTimer;
         private boolean bStop;
         public MouseClicked(MouseListener argListener)
              objListener = argListener;
              objEvent = null;
              objTimer = new Timer(100, this);
              bStop = false;
         public void actionPerformed(ActionEvent argEvent)
              if (bStop) {
                   objTimer.stop();
                   objListener.mouseClicked(objEvent);
                   objEvent = null;
              } else {
                   bStop = true;
         public void mouseClicked(MouseEvent argEvent)
              if (objEvent == null) {
                   objEvent = argEvent;
              } else {
                   if (objEvent.getComponent() == argEvent.getComponent()) {
                        if (objEvent.getClickCount() < argEvent.getClickCount()) {
                             objEvent = argEvent;
                        } else {
                             objEvent = new MouseEvent(argEvent.getComponent(), argEvent.getID(), argEvent.getWhen(), argEvent.getModifiers(), argEvent.getX(), argEvent.getY(), argEvent.getClickCount() + objEvent.getClickCount(), argEvent.isPopupTrigger());
                   } else {
                        objListener.mouseClicked(objEvent);
                        objEvent = argEvent;
              bStop = false;
              objTimer.restart();
         public void mouseEntered(MouseEvent argEvent)
         public void mouseExited(MouseEvent argEvent)
         public void mousePressed(MouseEvent argEvent)
         public void mouseReleased(MouseEvent argEvent)
    DeltaCoder

Maybe you are looking for

  • Error while invoking custom API using Database Adapter

    Hi, I've a requirement where in I need to fetch the data returned by a recordtype of a custom API. I've implemented this by invoking the custom API using Database Adapter. I'm facing a problem while performing this. The custom API holds the signature

  • My app tabs fail to open when i reopen the browser. why?

    After installing 4.0 yesterday I started experimenting with new features, including the app tabs. I closed some of the app tabs, though not all, and then as an experiment closed & reopened the browser. Your specs say that: All of the App Tabs you hav

  • Uc560 - CUE Webinterface not reachable

    Hello, i have a problem with my UC560. Especially with the CUE Webinterface. After config my UC560 everthings working fine. But the webinterface of the CUE is not reachable. I can ping the integtr. Service. Engine with IP 10.1.10.1. from my network.

  • Flat file upload ( data from Non SAP)

    Hi experts -- Need to create say morethan 400 infobjects in our scenario. so can any one help me, is there any alternative to create the same rather than creating manually.Is there any option thru BDC. i mean thru a file with data types,length,..desc

  • Non-English language install of the SUN OS on Sparc

    Hello... I'm sure that you used to be able to do a totally non-English install e.g. in French, German, Japanese etc. but I'm told the only way that you can now install Solaris Sparc is in English and then add the language packs. Can you advise if thi