Sending keyevents to JTextField programatically.

Hi All,
Can anybody let me know how do I sent key event to a text field programatically. I want to send all keystrokes in the keyboard (including ENTER, ESCAPE,letters,numbers etc) to a textfield.
I tried something like this and it didn't work. No exception is thrown, but the characters does not appear in the target field.
int kcf = KeyEvent.VK_UNDEFINED;
char kcharf = '9';
KeyEvent event = new KeyEvent(_mTarget,
     KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0,
     kcf, kcharf);
try {
      java.lang.reflect.Field f =
          AWTEvent.class.getDeclaredField("focusManagerIsDispatching");
          f.setAccessible(true);
          f.set(event, Boolean.TRUE);
   catch(Exception exp) {
        System.err.println(exp);
   _mTarget.dispatchEvent(event);Please help me to resolve the problem. My main purpose is to write a virtual keypad.
Thanks
Deekshit M

Maybe create a custom EventQueue:
EventQueue queue = new EventQueue()
     protected void dispatchEvent(AWTEvent event)
          if (event.getID() == KeyEvent.KEY_TYPED
          ||  event.getID() == KeyEvent.KEY_PRESSED
          ||  event.getID() == KeyEvent.KEY_RELEASED)
               // create new KeyEvent and dispatch it to your text field
          else
               super.dispatchEvent(event);
Toolkit.getDefaultToolkit().getSystemEventQueue().push(queue);

Similar Messages

  • Send KeyEvents to a TextField

    Hi,
    I have a small problem with sending Key events from code to a JTextField component. I use the EventQueue's postEvent method to post the event:
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event)
    It seems, that the listeners associated to the JTextField gets notified that a key has been pressed, but the UI is not updated with the text.
    Can somebody help me in this, how to update the UI of the JTextField component? Why the Text field's UI is not updated by default?
    Thanks and Regards,
    -Mixer

    Here it is a code snipplet how I subscribe to the key events:
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
                   @Override
                   public void eventDispatched(AWTEvent event) {
                        if (registerEvents == false)
                             return;
                        if (event.getID() == KeyEvent.KEY_RELEASED){
                             occured_events.add(new TestKeyEvent(TEST_EVENTS.KEY,(KeyEvent)event));
              }, AWTEvent.KEY_EVENT_MASK);
    Sending then the events from the occured_events (List):
    for(int i=0;i<occured_events.size();i++){
    AWTEvent event = occured_events.get(i).getEvent();
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
    }

  • No keyevents on JTextField when adding it through method

    Hi all,
    I generated a simple control with axbridge which just has two JTextFields finally.
    The first one is added in the constructor and the second is added by calling doSomething externally (i.e. from HTML/JavaScript testpage).
    The strange about it is that the first textfield can be edited and the second one not... but why?!?!?
    I checked that the textfields are editable and enabled... both were...
    I registered a keylistener for both textfields... I got events from the first textfield but none from the second...
    Here the simple code:
    package axtest;
    import java.awt.BorderLayout;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    public class AxTest extends JComponent {
         public AxTest() {
              this.setLayout(new BorderLayout());
              this.add(new JTextField(), BorderLayout.NORTH);
         public void doSomething() {
              this.add(new JTextField(), BorderLayout.SOUTH);
              this.validate();
    <html>
    <form name="test">
    <input type="button" onclick="document.axtest.doSomething()"/>
    </form>
    <object name="axtest" width="300" height="200" classid="CLSID:65B496AE-BFA3-42A6-B4AD-B6CD515355A1">
    </object>
    </html>

    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5029022

  • SunLink OSI 8.1 - how to send OSI echo requests programatically (C)

    Since the osi_ping provided by the SUN packages will not give any information about roundtrip times I am about to write an independend implemenation of the protocol.
    Unfortunately neither the TLI nor the APLI documentation give any hints on how to send non DT PDUs (for the echo function ERQ/ERP is required while binding to the local NSAP configured for CLNS and used by the OSI stack).
    Can any body help out with links, hints or even code samples here ?
    Best Regards
    Falk John

    Hi.
    This product EOL. Oracle request support contract for any contacts.
    In case you have support contract you can upgrade OSI to 9.0 + patch. After this you not need additional license key.
    Additional information:
    http://www.oracle.com/us/support/licensecodes/sun/solstice-connectivity-deveoper-tools-274762.html
    You can try submit request from URL above.
    Regards

  • How to send email in labview in intranet network

    hii all...
    i am quite new to networking concept in labview...
    i want to develop a ayatem where on completion of particularevent an email will be sent to concerned person regarding the completion of task...ans the email should be autogenerated....meaning that on completion of task directly email should me send to concerned persion programatically......This system will work for office only...
    i have tried to send email by using outlook...but i m having doubts..
    1)when i send mail using outlook in labview it is shown in outbox(of outlook) but the sent mail i didnt receive in inbox.i have not created the account on outlook.is the problem is related to this?
    2)what server address should i give if i want to use SMTP vi's??
    plz help me regarding this...
    thanks....

    smercurio_fc wrote:
    Shruti G wrote:
     2)what server address should i give if i want to use SMTP vi's??
    The same server that Outlook connects to. Do you have an internal server or an external server (i.e., one provided by your ISP or perhaps your domain name hosting service)? If it's internal is it a POP server, or MS Exchange, or ... ?
    One relatively easy way to figure this out is to Google "MX Lookup".  Go to one of those sites and enter the name of your domain, e.g. "somecompany.com".  The MX lookup page will return the name and/or IP of the SMTP server for the domain.  The MX lookup retrieves DNS information for the domain that is used to route email between servers.

  • Add Bullet point in mail content in send mail

    Hi,
    Can you please let me know how to add Bullet point in the mail content while sending email from SAP programatically??

    do you generate mails by custom program?
    if yes, you can create a mail with body in TXT or HTML formats. For TXT, simply use a star (*) character. For HTML, use
    <ul>
    <li>first bulleted line</li>
    <li>second bulleted line</li>
    </ul>
    To send HTML body from a custom program, some examples are listed in wiki Sending Mails - Home Page.

  • Sockets Problem / sort of Echoing Server

    Hey all, basically the problem i got is related to sockets, client program freezes up once i press the button 'send', Mainly all im trying to do right now is have a client send text to the server, then the server sends back whatever the client sent and this is then shown on the clients screen..
    The code i got is
    public class Server {
         public static void main(String[] args){
              try {
                   ServerSocket sSocket = new ServerSocket(3000);
                   Socket clientSocket = sSocket.accept();
                   BufferedReader fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   PrintWriter toClient = new PrintWriter(clientSocket.getOutputStream(), true);
                   String fClient;
                   while((fClient = fromClient.readLine())!= null){
                        toClient.println(fClient);
              }catch(IOException e) {
                   System.err.println(e);
    }And for the client class
    public class Client extends JFrame implements ActionListener {
         JTextArea result;
         JTextField text;
         Socket socket;
         public Client(){
              super("Client");
              try{
                   socket = new Socket("localhost", 3000);
              } catch (UnknownHostException e){
                   System.err.println("Unknown Host");
              } catch (IOException e) {
                   System.err.println("Exception");
              JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              result = new JTextArea(13,10);
              JButton send = new JButton("Send");
              text = new JTextField(19);
              send.addActionListener(this);
              panel.add(text);
              panel.add(send);
              add(new JScrollPane(result), BorderLayout.NORTH);
              add(panel, BorderLayout.SOUTH);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setSize(300,300);
              setVisible(true);          
         public void actionPerformed(ActionEvent e) {
              String fServer = null;
              BufferedReader fromServer = null;
              PrintWriter toServer = null;
              String aCommand = e.getActionCommand();
              if(e.getSource() instanceof JButton){
                   if(aCommand.endsWith("Send")) {
                        try {
                             fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                             toServer = new PrintWriter(socket.getOutputStream());
                        }catch(IOException e1){
                             System.err.println("Exception occured");
                        toServer.println(text.getText());
                        try{
                             fServer = fromServer.readLine();
                        }catch (IOException e1) {
                             System.err.println("Error Recievieng Result");
                        result.append(fServer);
    }However after debugging the application, i think the main problem comes from the server side, mainly the while loop which keeps looping to see if the input recieved is null, i think the problem why the client freezes up is because nothing is being sent therefore the loops keeps going on in circles, hence not supplying the client with any text..
    I would appreciate if someone could give me some help how to fix this problem
    Thanks

    What else could the server do? There's no problem there. The problem is that you're calling network code inside an actionPerformed method. This freezes your GUI because the method is invoked within the AWT thread, which handles all the events on the GUI. As your code is blocked in network operations, no GUI events can be processed.
    Do the network operations in a separate thread.

  • Email In and Out of LabVIEW

    I am interested in sending and receiving email programatically from LabVIEW.
    I have yet to find something that does everything well. Besides the
    following
    list, what have people used for email with LabVIEW.
    Thanks.
    Fred Genett
    Internet Toolkit : SMTP (send mail) with attachments
    POP VIs from NI: POP (receive mail) no attachments
    SMPT VIs from PICA FTP: no attachments

    Mikrobi wrote:
    > >> I am interested in sending and receiving email programatically from
    > LabVIEW.
    > >> I have yet to find something that does everything well. Besides the
    > >> following
    > >> list, what have people used for email with LabVIEW.
    >
    > >I believe that the most popular may be Outlook
    > >using ActiveX ?
    > > Kevin Kent
    >
    > yes, but can somebody explain me how it could be done ...?
    >
    > Kevin...?
    > could you help...?
    >
    > best regards
    >
    > Zbigniew StS aka Mikrobi
    I am afraid that my main platform is UNIX do I have little experience
    with ActiveX and Outlook express.
    I would suggest you explore the documents and examples
    on using ActiveX and then try some experiments.
    Basically you drop an ActiveX container on the FronT Panel
    and then b
    rowse to find the correct component.
    You may want to search the NI knowledge base and
    (for Outlook Express , ActiceX ) check out Microsoft's web site.
    Kevin (trying to stay away from Wintel, but not having much success)
    Attachments:
    Kevin.Kent.vcf ‏1 KB

  • Multithreading server /- client doesnt update need a little help

    I have three classes, one is my client called lobby, the second is my server, then my third is the server thread. Everything works but the client doesnt seem to update unless you type stuff in and hit enter or press send and that isbecause of the key and action listeners, how do i go about having to updating every 10 seconds or less..? I tried doing a while statement and of course it freezed it because its an infinite loop, tried making it a thread, not to good at that, i just need some advice on how to solve this problem, thanks.
    public class Lobby extends JPanel {
         public Lobby()
              listenSocket();
              send = new JButton("Send");
              chatter = new JTextField();
              motd = new JLabel("The Lobby");
              this.setLayout(new MigLayout());
              this.setSize(800, 600);
              this.setBackground(Color.white);
              this.setAutoscrolls(true);
              this.add(motd, "span 1, align center");
              this.add(UserListTop(), "align center, wrap");
              this.add(ChatBox(), "");
              this.add(UserList(), "wrap");
              this.add(Chatter(), "");
              this.add(Send(), "");
              this.setVisible(true);
         public Component ChatBox()
              Dimension dscroll = new Dimension(590, 400);
              chatbox = new JTextArea(20, 50);
              chatbox.setLineWrap(true);
              chatbox.setEditable(true);
              chatbox.setWrapStyleWord(true);
              JScrollPane areaScrollPane = new JScrollPane(chatbox);
              areaScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              areaScrollPane.setAutoscrolls(true);
              areaScrollPane.setPreferredSize(dscroll);
              return areaScrollPane;
         public Component Chatter()
              KeyListener enter = new KeyListener()
                   @Override
                   public void keyPressed(KeyEvent event) {
                        if((event.getKeyChar() == KeyEvent.VK_ENTER) && (chatter.getText() != "") && (chatter.getText() != null))
                             //Send data over socket
                             String text = chatter.getText();
                             out.println(text);
                             chatter.setText(new String());
                             //Receive text from server
                             try{
                                  String line = in.readLine();
                                  chatbox.append("Usernamehere: " + line + "\n");
                             } catch (IOException e){
                                  System.out.println("Read failed");
                                  System.exit(1);
                   @Override
                   public void keyReleased(KeyEvent e) {
                   @Override
                   public void keyTyped(KeyEvent e) {
              String line;
              try {
                   line = in.readLine();
                   chatbox.append("usernamehere: " + line + "\n");
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              chatter.addKeyListener(enter);
              Dimension chattersize = new Dimension(590, 30);
              chatter.setPreferredSize(chattersize);
              chatter.setVisible(true);
              return chatter;
         public Component Send()
              ActionListener sendl = new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent event) {
                        Object source = event.getSource();
                        if(source == send){
                             //Send data over socket
                             String text = chatter.getText();
                             out.println(text);
                             chatter.setText(new String(""));
                             //Receive text from server
                             try{
                                  String line = in.readLine();
                                  System.out.println("UserNameHere: " + line);
                                  chatbox.append("Usernamehere: " + line + "\n");
                             } catch (IOException e){
                                  System.out.println("Read failed");
                                  System.exit(1);
              send.addActionListener(sendl);
              send.setVisible(true);
              return send;
         public Component UserListTop()
              JLabel userlisttop = new JLabel("Players");
              return userlisttop;
         public Component UserList()
              Dimension scrollsize = new Dimension(170, 400);
              String names[] = new String[1500];
              for(int i = 0; i < 1500; i++)
                   names[i] = "Player" + i;
              userlist = new JList( names );
              userlist.setBackground(Color.white);
              userlist.setSize(50, 200);
              JScrollPane userlistscroll = new JScrollPane(userlist);
              userlistscroll.setPreferredSize(scrollsize);
              return userlistscroll;
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: localhost");
                   System.exit(1);
              } catch  (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
    }

    3rd class
    package server;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    // This client thread opens the input and the output streams for a particular client,
    // ask the client's name, informs all the clients currently connected to the
    // server about the fact that a new client has joined the chat room,
    // and as long as it receive data, echos that data back to all other clients.
    // When the client leaves the chat room this thread informs also all the
    // clients about that and terminates.
    import java.net.Socket;
    public class clientThread extends Thread{
        DataInputStream is = null;
        PrintStream os = null;
        Socket clientSocket = null;      
        clientThread t[];
        public clientThread(Socket clientSocket, clientThread[] t){
         this.clientSocket=clientSocket;
            this.t=t;
        public void run()
         String line;
            String name;
         try{
             is = new DataInputStream(clientSocket.getInputStream());
             os = new PrintStream(clientSocket.getOutputStream());
             os.println("Enter your name.");
             name = is.readLine();
             os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
             for(int i=0; i<=9; i++)
              if (t!=null && t[i]!=this)
              t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
         while (true) {
              line = is.readLine();
    if(line.startsWith("/quit")) break;
              for(int i=0; i<=9; i++)
              if (t[i]!=null) t[i].os.println("<"+name+"> "+line);
         for(int i=0; i<=9; i++)
              if (t[i]!=null && t[i]!=this)
              t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
         os.println("*** Bye "+name+" ***");
         // Clean up:
         // Set to null the current thread variable such that other client could
         // be accepted by the server
         for(int i=0; i<=9; i++)
              if (t[i]==this) t[i]=null;
         // close the output stream
         // close the input stream
         // close the socket
         is.close();
         os.close();
         clientSocket.close();
         catch(IOException e){};

  • Keyevent

    hi there!!
    i have to write a program which gives some keyboard input to an
    application on windows, without using a keyboard... i mean how
    can i send Keyevents to certain application on windows...
    ne help??
    TIA
    aryaSP

    hi there!!
    i have to write a program which gives some keyboard
    input to an
    application on windows, without using a keyboard... i
    mean how
    can i send Keyevents to certain application on
    windows...
    ne help??
    TIA
    aryaSP You can't do it to arbitrary applications due to security reasons. You don't want any web applets to take over your computer, do you?
    Within the same Java application, you can send a keyevent message to any swing/awt component.

  • Please help me with centering a component and clearing a JRadioButton

    Hi, could someone help me to cener the label and clear the selected JRadioButton?
    I have put a comment beside the problematic place. Thanks a lot! ann
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class ButtonAction extends JPanel implements ActionListener {
         private JRadioButton button1, button2;
         private JButton send, clear;
         private JTextField text;
         private JLabel label;
         private ButtonGroup group;
         public ButtonAction() {
              setPreferredSize(new Dimension(300, 200));
              setLayout(new GridLayout(0, 1, 5, 5));
            setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            setBorder(BorderFactory.createLineBorder(Color.blue));
            JPanel p1 = new JPanel();
            button1 = new JRadioButton("Button One");
              button2 = new JRadioButton("Button Two");
              group = new ButtonGroup();
              group.add(button1);
              group.add(button2);
              p1.add(button1);
              p1.add(button2);
              JPanel p2 = new JPanel();
              send = new JButton("Send");
              clear = new JButton("Clear");
              label = new JLabel(" ");
              label.setAlignmentX(Component.CENTER_ALIGNMENT);    //this doesn't work
              send.addActionListener(this);
              clear.addActionListener(this);
              p2.add(send);p2.add(clear);
              add(p1); add(p2); add(label);
         public void DisplayGUI(){
              JFrame frame = new JFrame();
              frame.getContentPane().add(this);
              frame.pack();
              frame.setVisible(true);
         public String getButton(){
              String result = "";
              if (button1.isSelected())
                   result += "\t You have clicked the first button";
              else if (button2.isSelected())
                   result += "\t You have clicked the second button";
              return result;
         public void setButton(){                  // this method doesn't work
              if (button1.isSelected() == true)
                   button1.setSelected(false);
              else if (button2.isSelected() == true)
                   button2.setSelected(false);
         public void actionPerformed (ActionEvent e) {
              if (e.getSource() == send) {
                   label.setText(getButton());
              else if (e.getSource() == clear) {
                   setButton();
                   label.setText("no button is selected");
         public static void main(String[] args) {
              ButtonAction ba = new ButtonAction();
              ba.DisplayGUI();
    }

    setHorizontalAlignmentX(Component.CENTER_ALIGNMENT) is a container method and I don't think it does what you think. Try this instead:label = new JLabel("Some text");
    //label.setHorizontalAlignmentX(Component.CENTER_ALIGNMENT);    //this doesn't work
    label.setHorizontalAlignment(SwingConstants.CENTER);When you alter the state of a radio button you should probably use the group methods - because the group "coordinates" the state of the buttons as a whole. Note that setSelection() isn't quite like a user click in that it doesn't fire a method. Now, in your case you are essentially clearing the selection of the group and ButtonGroup provides a method for that.     public void setButton(){                  // this method doesn't work
        if (button1.isSelected() == true)
        button1.setSelected(false);
        else if (button2.isSelected() == true)
        button2.setSelected(false);
        group.clearSelection();
    }Note we don't usually write if(foo == true), it's enough to say if(foo).
    You will get better and faster help from the Swing forum and it helps everyone if posts are made to the right place. http://forum.java.sun.com/forum.jspa?forumID=57

  • Reports-Mail ?

    after the completion of a report, i want a sending a mail through programatically ? How explain plzzzzz ?

    This code which follows is for both running the mail in foreground and bakground.
    if its foreground put the entire code in a perform and before that just say if sy-batch = 'X'. if this condition satisfies then it runs in background otherwise it runs in foreground.
    Just maintain your email ids in Z_TAB table.
    *-- variables
      data : v_title type SODOCCHGI1-OBJ_DESCR,
             v_attachname type char50,
             v_attachdes type SO_OBJ_DES,
             v_sender  TYPE  SOMLRECI1-RECEIVER,
             v_date(10) type c.
    *-- internal tables
      data : i_rcv type standard table of  SOMLRECI1,
             i_MSG type standard table of   SOLISTI1,
             i_email type standard table of Z_TAB.
    *-- work areas
      data : wa_rcv type SOMLRECI1,
             wa_MSG type SOLISTI1,
             wa_email type Z_TAB.
    *-- fill in message details
      write p_start to v_date  DD/MM/YYYY.
      concatenate text-003 v_date into v_title separated by space.
      concatenate text-004 v_date into v_attachname separated by space.
      concatenate text-005 v_date into v_attachdes separated by space.
      v_sender = sy-uname.
      wa_MSG-line = text-006.
      append wa_msg to i_msg.
      wa_MSG-line = text-007.
      append wa_msg to i_msg.
    *-- fill inreceivers
      select * from Z_TAB
                    into table i_email
                    where cprog = sy-cprog
                    and   SLSET = sy-slset.
      if sy-subrc  = 0.
        loop at i_email into wa_email.
          CLEAR wa_rcv.
          wa_rcv-receiver = wa_email-emailid.
          wa_rcv-rec_type = 'U'.
          wa_rcv-com_type = 'INT'.
          wa_rcv-notif_del = 'X'.
          wa_rcv-notif_ndel = 'X'.
          APPEND wa_rcv to i_rcv.
          clear : wa_email.
        endloop.
    *-- sending email
        CALL FUNCTION 'Z_SY_EMAIL_REPORT_AS_PDF'
          EXPORTING
            IMP_MAIL_TITLE             = v_title
            IMP_ATTACHNAME             = v_attachname
            IMP_ATTACHDESCR            = v_attachdes
            IMP_SENDER                 = v_sender
          TABLES
            T_RECEIVERS                = i_rcv
            T_MSG_BODY                 = i_msg
          EXCEPTIONS
            ERR_NO_ABAP_SPOOLJOB       = 1
            ERR_NO_SPOOLJOB            = 2
            ERR_NO_PERMISSION          = 3
            ERR_CONV_NOT_POSSIBLE      = 4
            ERR_BAD_DESTDEVICE         = 5
            USER_CANCELLED             = 6
            ERR_SPOOLERROR             = 7
            ERR_TEMSEERROR             = 8
            ERR_BTCJOB_OPEN_FAILED     = 9
            ERR_BTCJOB_SUBMIT_FAILED   = 10
            ERR_BTCJOB_CLOSE_FAILED    = 11
            TOO_MANY_RECEIVERS         = 12
            DOCUMENT_NOT_SENT          = 13
            DOCUMENT_TYPE_NOT_EXIST    = 14
            OPERATION_NO_AUTHORIZATION = 15
            PARAMETER_ERROR            = 16
            X_ERROR                    = 17
            ENQUEUE_ERROR              = 18
            OTHERS                     = 19.
        IF SY-SUBRC <> 0.
          if ( not SY-MSGID is initial ) and ( not SY-MSGTY is initial ).
            MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          else.
            write:/ 'FM failed with error:',
                    sy-subrc .
          endif.
        ENDIF.
      else.
        message 'No mailing list maintained in table Z_TAB for current variant'
        type 'E'.
      endif.
    Reward points if useful.
    Thank you,
    Swetha

  • Chat client sorta

    I have to write this Chat client program for a class, not fully functioning, but I can't figure out what to do in order to have text from one window where it is to be entered to copy to another widow were all messages end up.. I tried InputStreamReader to do it, but couldn't get that to work..either it was the way I was triing to do it or it isn't what I should be using.. not sure..Anyway how would I do this? What should I be using?

    Make two JFrames. One will hold a JTextArea for the text, the other will send data. Create an instance of that first object in your second, passing a reference to the JTextArea. Like this:
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
         class InputWin extends JFrame {
              private JTextArea refArea;
              private JLabel textLabel;
              private JTextField text;
              private JButton button;
              public InputWin(JTextArea refArea) {
                   this.refArea = refArea;
                   textLabel = new JLabel("Send:");
                   text = new JTextField(20);
                   button = new JButton("Send");
                   this.getContentPane().setLayout(new java.awt.FlowLayout());
                   this.getContentPane().add(textLabel);
                   this.getContentPane().add(text);
                   this.getContentPane().add(button);
                   this.pack();
                   this.setResizable(false);
                   this.setTitle("Send Text");
                   this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                   this.setLocationRelativeTo(null);
                        button.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                  sendText();
              private void sendText() {
                   refArea.append(text.getText() + "\n");
                   text.setText("");
                   text.requestFocus();
         public class TextFrame extends JFrame {
              private JTextArea jta;
              private JScrollPane jsp;
              private InputWin inputWin;
              public TextFrame() {
                   jta = new JTextArea();
                   jta.setLineWrap(true);
                   jta.setWrapStyleWord(true);
                   jsp = new JScrollPane(jta);
                   inputWin = new InputWin(jta); /* pass the JTextArea as a reference to your InputWin class */
                   this.getContentPane().add(jsp);
                   this.pack();
                   this.setSize(400, 400);
                   this.setLocationRelativeTo(null);
                   this.setTitle("Text Pane");
                   this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                   inputWin.setVisible(true);
              public static void main(String[] argv) { new TextFrame().setVisible(true); }
         }

  • Best way to send a jtextfield with a button action

    i have searched the internet and forums and cannot find this answer... does anyone have a best way to send the data in a jtextfield when a button is clicked? thank you.

    Window.java
    public class Window extends JFrame
        public Window()
            JPanel panel = new JPanel(new FlowLayout());
            JLabel hostLabel = new JLabel("hostname or IP address: ");
            JTextField hostname = new JTextField(20);
            JButton checkButton = new JButton("Check");
            checkButton.addActionListener(new CheckEvent());
            panel.add(hostLabel);
            panel.add(hostname);
            panel.add(checkButton);
    }CheckEvent.java
    public class CheckEvent extends AbstractAction
        public CheckEvent()
            super();
        @Override
        public void actionPerformed(ActionEvent event)
            System.out.println(event);
            boolean serverReachable = false;
            try
                InetAddress server = InetAddress.getByName(hostname);
                System.out.println("\t\tName: " + server.getHostName());
                System.out.println("\t\tAddr: " + server.getHostAddress());
                System.out.println("\t\tReach: " + server.isReachable(300));
                serverReachable = server.isReachable(30);
            catch (UnknownHostException e)
                System.err.println("Unable to lookup" + hostname);
            catch (IOException e)
                System.err.println("Unable to reach "+ hostname);
            return serverReachable;
    }My problem lies in the hostname jtextfield that i want to send the string to the CheckEvent.java.
    Thank you.

  • Sending mail programatically

    hI GUYS
    This is sri, i need to have done an application to send mails programatically, below is the code, can any one fix the bug or give me the code which works fine?
    Any help will be appreciable!!!!!!
    Thanks & Regards,
    Sri.
    CODEimport java.util.*;
    import java.sql.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class Mail
    public static void main(String g[])
    String from="[email protected]";
    String[] to={"[email protected]","[email protected]"};
    Mail m=new Mail();
    m.sendMail(from,to,"test","Ignore this dear");
    public void sendMail(String from,String to[],String sub,String msg)
    try{
    String host = "smtp.gmail.com";     //String host = "smtp.gmail.com";
    //String from = "[email protected]";//String from = "[email protected]";
    //String to = "[email protected]";
    //String to = "[email protected]";
    //String to = "[email protected]";
    //String to = "[email protected]";
    String[] recipients=new String[to.length];
    for(int i=0;i<to.length;i++){
    recipients=to[i];
    // Get system properties
    Properties props = System.getProperties();
    // Setup mail server
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    // Get session
    Authenticator auth = new MyAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);
    // Define message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setSubject(sub);
    message.setText(msg);
    for (int i = 0; i < to.length; i++) {
         message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to[i]));
    //msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Send message
    //com.sun.mail.smtp.SMTPSSLTransport.send(message);
    Transport.send(message);
    }catch(Exception e){e.printStackTrace();}
    class MyAuthenticator extends Authenticator
    MyAuthenticator()
    super();
    //protected PasswordAuthentication getPasswordAuthentication()
    public PasswordAuthentication getPasswordAuthentication()
    return new PasswordAuthentication("[email protected]", "XXXXXXXX");
    } // sendmail changeme cms
    OUTPUTC:\ftp\r&d>CP
    C:\ftp\r&d>set classpath=C:\Program Files\IBM\WebSphere MQ\Java\lib\providerutil
    .jar;C:\Program Files\IBM\WebSphere MQ\Java\lib\com.ibm.mqjms.jar;C:\Program Fil
    es\IBM\WebSphere MQ\Java\lib\ldap.jar;C:\Program Files\IBM\WebSphere MQ\Java\lib
    \jta.jar;C:\Program Files\IBM\WebSphere MQ\Java\lib\jndi.jar;C:\Program Files\IB
    M\WebSphere MQ\Java\lib\jms.jar;C:\Program Files\IBM\WebSphere MQ\Java\lib\conne
    ctor.jar;C:\Program Files\IBM\WebSphere MQ\Java\lib\fscontext.jar;C:\Program Fil
    es\IBM\WebSphere MQ\Java\lib\com.ibm.mq.jar;c:\lib;C:\jdk1.5.0_06\lib;.;;C:\srin
    ivas\mail\web\WEB-INF\lib\activation.jar;C:\srinivas\mail\web\WEB-INF\lib\mail.j
    ar;;C:\srinivas\mail\web\WEB-INF\lib\activation.jar;C:\srinivas\mail\web\WEB-INF
    \lib\mail.jar;
    C:\ftp\r&d>javac Mail.java
    C:\ftp\r&d>java Mail
    javax.mail.MessagingException: Exception reading response;
    nested exception is:
    java.net.SocketException: Connection reset
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java
    :1462)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:37
    0)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at Mail.sendMail(Mail.java:67)
    at Mail.main(Mail.java:21)
    Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:235)
    at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java
    :1440)
    ... 9 more
    C:\ftp\r&d>

    See the entry in the JavaMail FAQ about debugging connection problems.
    Most likely you have a firewall on your machine or network that is preventing
    you from connecting.

Maybe you are looking for