GetText method

I'm brand new to Java programming and I need a little help please. I'm trying to make a simple GUI that will retrieve the text entered into a text field and display it in the DOS box using System.out.println....When I click the Accept button to display it in the DOS box I get a ton of jibberish. What am I doing wrong? Here is my code....
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Gui extends JFrame implements ActionListener
     // Button & TextField reference variables need class scope
     JButton acceptButton, clearButton, closeButton;
     JTextField nameTextField;
     JTextField addressTextField;
     JTextField phoneTextField;
     public static void main(String args[])
          // create instance of SwingFrameAndComponents
          Gui frameAndCompnents = new Gui();      
     // constructor
     public Gui()
          // create Button, Label and TextField instances
          acceptButton = new JButton("Accept");
          clearButton = new JButton("Clear");          
          closeButton = new JButton("Close");
          JLabel nameLabel = new JLabel("Name:");
          JLabel addressLabel = new JLabel("Address:");
          JLabel phoneLabel = new JLabel("Phone:");
          nameTextField = new JTextField(15);
          addressTextField = new JTextField(15);
          phoneTextField = new JTextField(10);
          // create two Panels - default FlowLayout manager
          JPanel upperPanel = new JPanel();
          JPanel lowerPanel = new JPanel();
          // add label & textfield to upper panel
          upperPanel.add(nameLabel);
          upperPanel.add(addressLabel);
          upperPanel.add(phoneLabel);
          upperPanel.add(nameTextField);
          upperPanel.add(addressTextField);
          upperPanel.add(phoneTextField);
          // add buttons to lower panel
          lowerPanel.add(acceptButton);
          lowerPanel.add(clearButton);
          lowerPanel.add(closeButton);
          // add panels to frame - frame default is BorderLayout
          Container c = this.getContentPane();
          c.add("North",upperPanel);
          c.add("South",lowerPanel);
          // register frame as listener for button events
          acceptButton.addActionListener(this);
          clearButton.addActionListener(this);          
          closeButton.addActionListener(this);     
          this.setSize(700,150);
          this.setTitle("GUI");
          this.setVisible(true);
          // create anonymous inner class to handle window closing event
          // register the inner class as a listener with the frame
          this.addWindowListener
          ( // begin inner class definition
               new WindowAdapter() // superclass of inner class is WindowAdapter
                    public void windowClosing(WindowEvent event)
                         {shutDown();} // invoke shutDown in outer class
               }// end of inner class definition     
          ); // end of argument sent to addWindowListener method     
     // actionPerformed is invoked when a Button is clicked
     public void actionPerformed(ActionEvent e)
     {     // see which button was clicked
          if(e.getSource() == acceptButton)
               acceptMessage();
          if(e.getSource() == clearButton)
               clearMessage();
          if(e.getSource() == closeButton)
               shutDown();
     public void acceptMessage()
          { nameTextField.getText();
          System.out.println (nameTextField);     } // Here is where I need to println to the DOS box
public void clearMessage()
          { nameTextField.setText("           ");
          addressTextField.setText(" ");
          phoneTextField.setText(" "); }     
     public void shutDown()
               this.dispose();
               System.exit(0); // terminate
Thanks so much for whatever input you can give me.

try adding the actionlistener directly to each button respectivly
acceptButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
System.out.println(nameTextField.getText());
do the same for the other buttons and replace system.out..... with the respective code u want to run
also i just saw
public void acceptMessage()
{ nameTextField.getText();
System.out.println (nameTextField); } // Here is where I need to println to the DOS boxthe ".getText()" funcion returns a string
so when u called nameTextField.getText() it returned a String to...nowhere!
either make a variable to catch the string like:
String tmp = nameTextField.getText();
OR
just directly put the statement into the system.out.println funciton like:
System.out.println(nameTextField.getText());
nate

Similar Messages

  • Need Help with a getText method

    Gday all,
    I need help with a getText method, i need to extract text from a JTextField. Although this text then needs to converted to a double so that i can multiply a number that i have already specified. As you may of guessed that the text i need to extract already will be in a double format.e.g 0.1 or 0.0000004 etc
    Thanks for your help
    ps heres what i have already done its not very good though
    ToBeConverted.getText();
    ( need help here)
    double amount = (and here)
    total = (amount*.621371192);
    Converted.setText("= " + total);

    Double.parseDouble( textField.getText() );

  • Not able to get content in textarea properly using getText() method.

    I am doing one mail sending application. I have one Jtext area in my swing. The content copied in the text area will be sent as a mail body to the mail id mentioned in the another jtext box. The content copied in the JTextArea is collected usign jt.getText() method.
    When i sent this as a mail i am getting all the content with out any indentation which was there in TextArea. Everything will be sent simply as one paragraph with out any indentation.

    http://forum.java.sun.com/thread.jspa?threadID=5126581&messageID=9449705

  • Can i use getValue() instead of getText() method while retrieving data

    can anybody help me by clearly explaining what is the difference between them.
    Thank you in advance.

    value is property defined by the UIOutput class defined in the ValueHolder interface.. . I suppose both of them (getValue/getText) return a java.lang.Object.
    So,. you should be able to use getValue in your bean without any problems.
    Even though when specifying attrbutes in the jsp page you can only specify it as a text attribute.

  • Problem with a template method in JDialog

    Hi friends,
    I'm experiencing a problem with JDialog. I have a base abstract class ChooseLocationDialog<E> to let a client choose a location for database. This is an abstract class with two abstract methods:
    protected abstract E prepareLocation();
    protected abstract JPanel prepareForm();Method prepareForm is used in the constructor of ChooseLocationDialog to get a JPanel and add it to content pane.
    Method prepareLocation is used to prepare location of a database. I have to options - local file and networking.
    There are two subclasses ChooseRemoteLocationDialog and ChooseLocalFileDialog.
    When I start a local version, ChooseLocalFileDialog with one input field for local file, everything works fine and my local client version starts execution.
    The problem arises when I start a network version of my client. Dialog appears and I can enter host and port into the input fields. But when I click Select, I get NullPointerException. During debugging I noticed that the values I entered into these fields ("localhost" for host and "10999" for port) were not set for corresponding JTextFields and when my code executes getText() method for these input fields it returns empty strings. This happens only for one of these dialogs - for the ChooseRemoteLocationDialog.
    The code for ChooseLocationDialog class:
    public abstract class ChooseLocationDialog<E> extends JDialog {
         private E databaseLocation;
         private static final long serialVersionUID = -1630416811077468527L;
         public ChooseLocationDialog() {
              setTitle("Choose database location");
              setAlwaysOnTop(true);
              setModal(true);
              Container container = getContentPane();
              JPanel mainPanel = new JPanel();
              //retrieving a form of a concrete implementation
              JPanel formPanel = prepareForm();
              mainPanel.add(formPanel, BorderLayout.CENTER);
              JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
              JButton okButton = new JButton(new SelectLocationAction());
              JButton cancelButton = new JButton(new CancelSelectAction());
              buttonPanel.add(okButton);
              buttonPanel.add(cancelButton);
              mainPanel.add(buttonPanel, BorderLayout.SOUTH);
              container.add(mainPanel);
              pack();
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              Dimension screenSize = toolkit.getScreenSize();
              int x = (screenSize.width - getWidth()) / 2;
              int y = (screenSize.height - getHeight()) / 2;
              setLocation(x, y);
              addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        super.windowClosing(e);
                        System.exit(0);
         public E getDatabaseLocation() {
                return databaseLocation;
         protected abstract E prepareLocation();
         protected abstract JPanel prepareForm();
          * Action for selecting location.
          * @author spyboost
         private class SelectLocationAction extends AbstractAction {
              private static final long serialVersionUID = 6242940810223013690L;
              public SelectLocationAction() {
                   putValue(Action.NAME, "Select");
              @Override
              public void actionPerformed(ActionEvent e) {
                   databaseLocation = prepareLocation();
                   setVisible(false);
         private class CancelSelectAction extends AbstractAction {
              private static final long serialVersionUID = -1025433106273231228L;
              public CancelSelectAction() {
                   putValue(Action.NAME, "Cancel");
              @Override
              public void actionPerformed(ActionEvent e) {
                   System.exit(0);
    }Code for ChooseLocalFileDialog
    public class ChooseLocalFileDialog extends ChooseLocationDialog<String> {
         private JTextField fileTextField;
         private static final long serialVersionUID = 2232230394481975840L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel();
              panel.add(new JLabel("File"));
              fileTextField = new JTextField(15);
              panel.add(fileTextField);
              return panel;
         @Override
         protected String prepareLocation() {
              String location = fileTextField.getText();
              return location;
    }Code for ChooseRemoteLocationDialog
    public class ChooseRemoteLocationDialog extends
              ChooseLocationDialog<RemoteLocation> {
         private JTextField hostField;
         private JTextField portField;
         private static final long serialVersionUID = -2282249521568378092L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel(new GridLayout(2, 2));
              panel.add(new JLabel("Host"));
              hostField = new JTextField(15);
              panel.add(hostField);
              panel.add(new JLabel("Port"));
              portField = new JTextField(15);
              panel.add(portField);
              return panel;
         @Override
         protected RemoteLocation prepareLocation() {
              String host = hostField.getText();
              int port = 0;
              try {
                   String portText = portField.getText();
                   port = Integer.getInteger(portText);
              } catch (NumberFormatException e) {
                   e.printStackTrace();
              RemoteLocation location = new RemoteLocation(host, port);
              return location;
    }Code for RemoteLocation:
    public class RemoteLocation {
         private String host;
         private int port;
         public RemoteLocation() {
              super();
         public RemoteLocation(String host, int port) {
              super();
              this.host = host;
              this.port = port;
         public String getHost() {
              return host;
         public void setHost(String host) {
              this.host = host;
         public int getPort() {
              return port;
         public void setPort(int port) {
              this.port = port;
    }Code snippet for dialog usage in local client implementation:
    final ChooseLocationDialog<String> dialog = new ChooseLocalFileDialog();
    dialog.setVisible(true);
    location = dialog.getDatabaseLocation();
    String filePath = location;Code snippet for dialog usage in network client implementation:
    final ChooseLocationDialog<RemoteLocation> dialog = new ChooseRemoteLocationDialog();
    dialog.setVisible(true);
    RemoteLocation location = dialog.getDatabaseLocation();Exception that I'm getting:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:42)
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:1)
         at suncertify.client.gui.dialog.ChooseLocationDialog$SelectLocationAction.actionPerformed(ChooseLocationDialog.java:87)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
         at java.awt.Component.processMouseEvent(Component.java:6134)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
         at java.awt.Component.processEvent(Component.java:5899)
         at java.awt.Container.processEvent(Container.java:2023)
         at java.awt.Component.dispatchEventImpl(Component.java:4501)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
         at java.awt.Container.dispatchEventImpl(Container.java:2067)
         at java.awt.Window.dispatchEventImpl(Window.java:2458)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
         at java.awt.Dialog$1.run(Dialog.java:1046)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Client VM (build 1.6.0-b09, mixed mode, sharing)
    OS: Ubuntu 8.04
    Appreciate any help.
    Thanks.
    Edited by: spyboost on Jul 24, 2008 5:38 PM

    What a silly error! I have to call Integer.parseInt instead of getInt. Integer.getInt tries to find a system property. A small misprint, but a huge amount of time to debug. I always use parseInt method and couldn't even notice that silly misprint. Sometimes it's useful to see the trees instead of whole forest :)
    It works perfectly. Sorry for disturbing.

  • How to use FileOutputStream in a method??

    Dear friend,
    Now I want to write a program use java swing. I can get text from JPasswordField but I can't write the password in a document. I try to use FileOutputStream in a method with actionPerformed. But it seem no work. The problem is where should I put the 'throws IOException'? At the main or at the method?? Thank you very much.
    Ah Siew.

    Hi!
    You can write this methode in a
    try
    }catch(IOException)
    or you write an throws IOException after the Methode.
    Thats the Problem with to IOException
    Now your other problem:
    first: an JPasswordField is an javax.swing element.
    You can get the String with the
    String1 = PasswordFieldObject.getText(); Methode.
    and than you can save it in an "Global" Var.
    Greetings
    F@b

  • Error : 'cannot find symbol getText()'

    please check my java coding. when I compile it, the error: 'cannot find symbol
    getText() ' is appear. What wrong with this coding.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class buatAction
    public static void main(String[] args)
    JFrame f= new JFrame("Contoh Action");
    f.setSize(150,200);
    f.setLocation(200,200);
    f.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent we)
    System.exit(0);
    //setkan button
    final JPanel OK = new JPanel();
    JButton buttonOK = new JButton("OK");
    OK.add(buttonOK);
    final JPanel txt = new JPanel();
    JTextField inputText = new JTextField(15);
    inputText.setFont(new Font("Serif", Font.PLAIN, 12));
    txt.add(inputText);
    Container content = f.getContentPane( );
    content.setLayout(new GridLayout(1,1));
    content.add(txt);
    content.add(OK);
    buttonOK.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    String ayat = txt.getText().getActionCommand();
    System.out.println(ayat);
    f.setVisible(true);
    }

    please check my java coding. when I compile it, the error: 'cannot find symbol
    getText() ' is appear. What wrong with this coding.
    final JPanel txt = new JPanel();...
    buttonOK.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    String ayat = txt.getText().getActionCommand();
    System.out.println(ayat);
    });Final variable 'txt' is a JPanel. JPanels don't have a 'getText()' method; hence
    the compiler diagnostics message.
    kind regards,
    Jos
    ps. better stick your code between [code] ... [/code] tags for readability reasons.

  • Deprecated API on a method.

    I am getting a deprecated API warning when using the JTextField.getText() method. How do I find what method I should use instead? Is there a list somewhere with the replacements? Does someone know what to use instead of that method?

    Yeah sorry guys I was using both a JTextField and a JPasswordField and I see now that you should use the method getPassword() for that. Sorry to bother everyone!!!

  • JLabel.getText doesn't work properly

    I have a main JFrame to build up the application GUI (using NetBeans 6.0.1). This mainPanel contains a JSplitPane and a StatusBar beneath. In the right side of the JSplitPane I put a JPanel with JComboBoxes and JButtons. After selecting an item in the JComboBox and clicking a JButton, the text in the StatusBar (implemented using a simple JLabel) shall be faded out by simply removing the first character until the text is erased and I use a Timer for this. This works well for itself.
    The problem now is that I want to start the 'fading' only if the StatusBar (the JLabel) contains a text at all. Checking this with:
    if ( !targetLabel.getText().equals("") ) {
    <start fading>
    }the getText() method returns "" (an empty string) ever. Even although I initialized this JLabel with a dummy text during initialization. Why?
    Here's the code for trying to set a JLabel in the StatusBar (this part works well) and fading a probably displayed text prior:
    class StatusMessageSetter implements Runnable{
    String myText;
    Color color;
    JLabel target;
    public StatusMessageSetter(JLabel target, Color color, String text) {
    myText = text;
    this.color = color;
    this.target = target;
    public void run() {
    //try {
    System.out.println("StatusMessageSetter: target=" + target);
    //SwingUtilities.invokeLater(new Runnable(){
    //   public void run() {
    System.out.println("StatusMessageSetter: target.getText()=" + target.getText());
    if ( !target.getText().trim().equals("") ) {
    try {
    MessageFader fader = new MessageFader(target);
    Thread th = new Thread(fader);
    th.start();
    th.join();
    } catch(InterruptedException intEx){}
    }//end if
    Thread t = new Thread(new Runnable(){
    public void run(){
    try {
    SwingUtilities.invokeAndWait(new Runnable() {
    //SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    System.out.println("Setting label...: " + myText);
    target.setForeground(color);
    target.setText(myText);
    }//end run
    } catch(InterruptedException intEx) {}
    catch(InvocationTargetException invocEx) {}
    });    //end new Runnable
    t.start();
    }//end run
    };+(Even when I only request the text from the JLabel when the JButton is clicked (in the JButton's actionPerformed() method) and doing nothing else the result is an empty String!!! And it doesn't matter if I do this directly or using SwingUtilities.invokeLater(); Why? I don't undertand this. I am asking: parentView.getStatusMessageLabel().getText(); (No NullPointerException is thrown. Thus, parentView as well as statusMessageLabel exist and I can see the set text in the statusBar.)+
    What I want to do (and I didn't managed this for the time being) is, that I want to display a message to the user what the app is going to do and inform the user afterwards about the result (failure/success) using the JLabel in the StatusBar. (Saying: "I'm going to do this...", executing a time consuming action (parsing a website) and the display the result in the StatusBar. Of course, the messages MUST be displayed well synchronized which means:
    Displaying what the app is currently doing and after the action returns this messagfe shall fade and the new message will be displayed.
    Maybe anyone could give me some code to solve my problem?!!?
    Thanks in advance
    Dirk
    Edited by: dirku on May 8, 2008 5:05 AM

    dirku wrote:
    2. A time consuming operation needs to be executed:
    --> In this case the time consuming operation begins but the message which should tell the user what the time consuming operation does is displayed
    only AFTER the operation has already completed. (The time consuming operation connects to parses a website and must return a state (OK,
    ERROR, ...).
    Thus, I think I need some kind of synchronization, don't I?Hm, not sure. You're probably not even going to see this, but no matter. I played with my code some more and got something like so:
    StatusMessageSetter .java
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JLabel;
    import javax.swing.Timer;
    class StatusMessageSetter
        private static final int DELAY = 1000;
        private String myText;
        private Color color;
        private JLabel target;
        private int delay = DELAY;
        public StatusMessageSetter(JLabel target)
            this.target = target;
        public void setDelay(int delay)
            this.delay = delay;
        public void fadeLabel(Color color, String text)
            this.color = color;
            this.myText = text;
            if (!target.getText().trim().equals(""))
                new Timer(delay, new MessageFader(target, color, myText)).start();
        private class MessageFader implements ActionListener
            private JLabel label;
            private StringBuilder sb;
            private Color color;
            private String text;
            public MessageFader(JLabel target, Color c, String t)
                label = target;
                color = c;
                text = t;
                sb = new StringBuilder(label.getText().trim());
            @Override
            public void actionPerformed(ActionEvent e)
                if (sb.length() > 0)
                    sb.deleteCharAt(0);
                    if (sb.length() == 0)
                        label.setText(" ");
                    else
                        label.setText(sb.toString());
                else
                    label.setForeground(color);
                    label.setText(text);
                    Timer timer = (Timer)e.getSource();
                    timer.stop();
    }StatusBr.java
    import java.awt.Color;
    import java.awt.FlowLayout;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.Border;
    public class StatusBr
        private JPanel mainPanel = new JPanel();
        private JLabel label = new JLabel();
        public StatusBr()
            mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            mainPanel.add(label);
        public JLabel getLabel()
            return label;
        public void setColor(Color c)
            label.setForeground(c);
        public void setText(String text)
            label.setText(text);
        public String getText()
            return label.getText();
        public void setBorder(Border border)
            mainPanel.setBorder(border);
        public JPanel getMainPanel()
            return mainPanel;
    }StatusMsgrTester.java
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingWorker;
    import javax.swing.Timer;
    public class StatusMsgrTester
        private static final String STATUS_BAR = "Status Bar";
        private static final String CONFIRMED = "Confirmed";
        private static final String QUICK_CONFIRM = "Quick Confirmation";
        private static final String SLOW_CONFIRM = "Slow Confirmation";
        private static final String RESET = "Reset";
        private JPanel mainPanel = new JPanel();
        private StatusBr statusbar = new StatusBr();
        StatusMessageSetter statusMsgSetter = new StatusMessageSetter(statusbar
                .getLabel());
        public StatusMsgrTester()
            JButton quickConfirmBtn = new JButton(QUICK_CONFIRM);
            JButton slowConfirmBtn = new JButton(SLOW_CONFIRM);
            JButton resetBtn = new JButton(RESET);
            ConfirmBtnListener confirmListener = new ConfirmBtnListener();
            quickConfirmBtn.addActionListener(confirmListener);
            slowConfirmBtn.addActionListener(confirmListener);
            resetBtn.addActionListener(confirmListener);
            JPanel confirmPanel = new JPanel(new GridLayout(1, 0, 10, 10));
            confirmPanel.add(quickConfirmBtn);
            confirmPanel.add(slowConfirmBtn);
            confirmPanel.add(resetBtn);
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(confirmPanel);
            statusMsgSetter.setDelay(60);
            statusbar.setText(STATUS_BAR);
            statusbar.setBorder(BorderFactory.createCompoundBorder(BorderFactory
                    .createRaisedBevelBorder(), BorderFactory
                    .createLoweredBevelBorder()));
            mainPanel.setPreferredSize(new Dimension(500, 200));
            mainPanel.setLayout(new BorderLayout());
            mainPanel.add(statusbar.getMainPanel(), BorderLayout.SOUTH);
            mainPanel.add(buttonPanel, BorderLayout.NORTH);
        private class ConfirmBtnListener implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                String command = e.getActionCommand();
                if (command.equals(QUICK_CONFIRM))
                    statusMsgSetter.fadeLabel(Color.blue, CONFIRMED);
                else if (command.equals(SLOW_CONFIRM))
                    slowConfirmation();
                else if (command.equals(RESET))
                    statusbar.setColor(null);
                    statusbar.setText(STATUS_BAR);
        public JPanel getMainPanel()
            return mainPanel;
        private void slowConfirmation()
            final Timer timer = new Timer(2000, new ActionListener()
                @Override
                public void actionPerformed(ActionEvent e)
                    statusMsgSetter.setDelay(30);
                    statusMsgSetter.fadeLabel(Color.red, "Confirming User, Please Wait.......");
            timer.setInitialDelay(5);
            timer.start();
            SwingWorker<String, Void> swingworker = new SwingWorker<String, Void>()
                @Override
                protected String doInBackground() throws Exception
                    System.out.println("Long process");
                    for (int i = 0; i < 10; i++)
                        System.out.println(String.valueOf(i));
                        Thread.sleep(1400);
                    return null;
                @Override
                protected void done()
                    timer.stop();
                    System.out.println("Done");
                    statusMsgSetter.fadeLabel(Color.blue, CONFIRMED);
            swingworker.execute();
        private static void createAndShowUI()
            JFrame frame = new JFrame("StatusMsgrTester");
            frame.getContentPane().add(new StatusMsgrTester().getMainPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Help with getText()

    Hi all,
    I could do with a little help using the getText method of TextField.
    Basically what I have is two classes, NewWin and Transmit.
    In NewWin, a small window is created in which a user will type a string in. When they press the submit button, it should send the string through to the constructor of a class called Transmit, where it should get printed out into a window created by Transmit. However, it doesn't do so for some reason.
    My windows work fine and I receive no errors, however the text doesn't seem to be put into my 'myString' variable. The 'myString' variable has been declared as public.
    JTextField preTextField = new JTextField();
    myString = preTextField.getText();...now, later in my NewWin class, this is the method to submit the string to the constructor of the Transmit class (transm has also been declared publicly).
    transm = new Transmit(myString);This is received by the constructor of Transmit (ipNum has been declared public)...
    public Transmit(String destip)
          JLabel preLabelText = new JLabel(ipNum);
          Container prePane = getContentPane();
          prePane.add(preLabelText, "South");
    }...which should print out the received string, but it doesn't. If I change the JLabel value to an actual string then it prints out the string that's written, but it won't print out what's in the variable.
    My only guess is that .getText() isn't working properly, but can anyone see why? I'm stumped as everything else works.
    Thanks,
    Jaiyan

    Sorry, that was a typo and not in my code. This is what I really have in my code, sorry for the confusion.
    public Transmit(String ipNum)
    JLabel preLabelText = new JLabel(ipNum);     
    Container prePane = getContentPane();     
    prePane.add(preLabelText, "South");

  • JTextField.getTExt() causes VerifyError, when running program

    I was looking through the online refernce that has code, as well as some of my old code, but everything returns the same problem. Code compiles, but when attempting to run, whereever I use the getText() method, then that conating method issues a verrifyError. As of now I can't get any values into or out of a textField.

    import javax.swing.*;
    public class guiTest
      public guiTest()
        JFrame window = new Jframe();
        JTextField text = new JTextField(20);
        text.setText("hello World");
        window.getContentPane().add(text);
        window.pack();
        window.show();
      static public void main (String[] Args)
        guiTest app = new guiTest();
    }That is the simplest app and for some reason I still get the same errors, Exception in thread "Main" java.lang.VerifyError: (Class: guiTest, Method: <init> signature: ()V) Incompatable object arugument for function call.

  • HttpUnit- inability to getText

    Heya peeps!
    Simulating web navigation has been easy till now. For some reason I cant view a particular frame(MainFrame).
    all that appears when the getText method is used is this:-
    <html>
    <head DIR="LTR">
    <title>e-point : Web Desktop - Workload</title>
    <link rel="stylesheet" type="text/css" href="styles/ePOINT.css">
    <link rel="stylesheet" type="text/css" href="styles/ePOINT.css">
    <link rel="stylesheet" href="calendar/calendar.css"></link>
    </head>
    <body topmargin="2" leftmargin="6" marginheight="2" marginwidth="6" bgcolor="#ffffff" link="orange" alink="orange" vlink="orange" leftmargin="0" topmargin="0">
    <h2>The script has thrown an exception</h2><[xmp>EXCEPTION:<EXCEPTION><DESC>Unexpected Exception caught in WEBSCRIPT::TRANSFORMLAYOUT:
    @null</DESC><CODE>-7</CODE><ORIGIN entry="TRANSFORMLAYOUT" line="0" /></EXCEPTION></xmp>[/b] </body>
    </html>
    As you can see it says that an unexpected exception was caught in WEBSCRIPT.
    My question is where does this error coming from? Does this happen becoz HttpUnit is unable to read the javascript? Can HttpUnit getText if its written in xml?
    Any inputs will be greatly appreciated

    Pete H --
    No, it is not possible to import Excel files with either the xlsx or the the xlsm file extension.  This is simply a limitation of the Import/Export Wizard.  Sorry.  Hope this helps.
    Dale A. Howard [MVP]
    VP of Educational Services
    msProjectExperts
    http://www.msprojectexperts.com
    http://www.projectserverexperts.com
    "We write the books on Project Server"

  • Unable to return values in joptionpane

    Hi all,
    Im having a slight problem with some code regarding a joptionpane. With the help of some code i found on the internet (lol i know theres a lot of bad stuff out there but i thought id give it a go), im making a new object array containing my fields, and then adding these objects to the joptionpane. it seems to work ok, but i cant get back the values the user entered into the fields - for a normal joptionpane id call the getText() method. (nb this is only a small test application, so it is ok that a password is being returned for anyone to see!)
    In my code below, all i can get it to do is return the objects details eg javax.swing.JTextField[,0,19,195x20,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0 etc...., and not the value the user entered!
    Is this bad code for what im trying to do? what is the easiest way of returning the users password?
    Thanks in advance
    Torre
    here is the code:
    if ("changePwdPressed".equals(e.getActionCommand())){
                   Object complexMsg[] = { "Current Password: ", new JTextField(10), "New Password: ", new JTextField(10), "Confirm New Password: ", new JTextField(10) };
                   JOptionPane optionPane = new JOptionPane();
                   optionPane.setMessage(complexMsg);
                   optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
                  JDialog dialog = optionPane.createDialog(this, "Change Password");
                  dialog.setVisible(true);
                  int i;
                  for (i=0; i<complexMsg.length; i++)
                  System.out.println(complexMsg);

    This works, but it's ugly...
    package forums;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class ComplexJDialogTest
      public static void main(String[] args) {
        try {
          System.out.println("Hello World!");
          message();
          System.out.println("Hello World!");
        } catch (Exception e) {
          e.printStackTrace();
      private static void message() {
        Object messages[] = {
            "Current Password: ", new JTextField(10)
          , "New Password: ", new JTextField(10)
          , "Confirm New Password: ", new JTextField(10)
        JOptionPane optionPane = new JOptionPane(messages, JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = optionPane.createDialog(null, "Change Password");
        dialog.setVisible(true);
        for (int i=1; i<messages.length; i+=2) {
          System.out.println(((JTextField)messages).getText());
    dialog.dispose();
    ... I think I would prefer swmtgoet_x's solution... just create your three JTextField's (keep references to them) pass them to the JDialog, then (after user hits OK done) just access them directly.... ergo...
    package forums;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class ComplexJDialogTest
      public static void main(String[] args) {
        try {
          System.out.println("Hello World!");
          message();
          System.out.println("Hello World!");
        } catch (Exception e) {
          e.printStackTrace();
      private static void message() {
        JTextField oldPassword = new JTextField(10);
        JTextField newPassword = new JTextField(10);
        JTextField newPasswordAgain = new JTextField(10);
        Object messages[] = {
            "Current Password: ", oldPassword
          , "New Password: ", newPassword
          , "Confirm New Password: ", newPasswordAgain
        JOptionPane optionPane = new JOptionPane(messages, JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = optionPane.createDialog(null, "Change Password");
        dialog.setVisible(true);
        dialog.dispose();
        System.out.println(oldPassword.getText());
        System.out.println(newPassword.getText());
        System.out.println(newPasswordAgain.getText());

  • Leaving JTextField with TAB

    A simple question really ... I have a JTextField that I would like to have the user exit from with TAB and get
    the same action as if they had left the field with the
    ENTER key, i.e., I'd like to be able to use the getText
    method to retrieve what the user entered. Currently, with
    no modifcations whatsoever to the JTextField, when I
    invoke getText after the user leaves the field with a TAB,
    getText returns NULL. I've tried just about everything,
    but can't get any of it to work (removeKeyStrokeBinding(), extending JTextField, etc.).
    Thanks in advance for any suggestions.

    As you have niticed this is not such a simple question at all.
    After some experimentation I decided to make the enter key cause the text field to loose focus.
    addKeyListener (new KeyAdapter()
    public void keyPressed (KeyEvent evt)
    int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER)
    transferFocus ();
    Then give the text field a focus listener
    class TextListener extends java.awt.event.FocusAdapter
    public void focusLost (FocusEvent e)
    // evalutate the text using getText()
    Which gets the field's content, validates it and then save it in the appropriate place.
    The advantage to this approach is the whole field edits are always done in the same place (the focus adapter), and the enter and tab actions appear the same to the user.
    The disadvantage is that, unless you know the initial value, you won't be able to tell if the value has changed.
    hope this helpds some.
    Terry

  • How can i get the content of JTextArea with out loosing Indentation.

    I am developing one mail sending application. I am getting mailid , from address, mail body from one Swing. In one JTextArea i am typing i have typed some matter. When i call the content of JTextArea using
    jtx.getText() method, i am getting all the content as one paragraph. That means there is no indentation which was there in TextArea.
    Please provide me some solution how can i get the content of JTextArea wiht out loosing indentation.

    And it was you who asked the question!

Maybe you are looking for

  • LOOP and Read statements

    Hi abapers,                     I want to know the difference between statements. SELECT MATNR MAKTX FROM MAKT INTO TABLE IT_MAKT. SELECT EBELN EBELP ... ..... ..... FROM EKPO INTO IT_EKPO WHERE MATNR = IT_MAKT-MATNR. 1st statement LOOP AT IT_MAKT IN

  • Duplicate Tunes!

    Hey, i have posted this elsewhere, but may hve been in the wrong topic. "hey, when i scroll through my songs on my iPOD i see a lot of songs appearing twice, although ive only added them ONCE using iTunes. For example, i have an album on the iPod, it

  • HELP! Running slow.

    My mac is running slow and i don't know what the problem is. Could someone help me out? Thanks! EtreCheck version: 1.9.15 (52) Report generated September 12, 2014 at 2:15:31 AM GMT+2 Hardware Information: ?   MacBook Pro (13-inch, Early 2011) (Verifi

  • Pictures NTSC to PAL

    I have downscaled and sharpen my pictures in Photoshop. They got the resolution 720x480 which is NTSC. Then I made a video in Premiere Pro CS5. I forget that the other videos to the DVD is PAL. Now I have 2 PAL 4:3 videos, 1 PAL 16:9 video and this 4

  • Merging events in iPhoto with pictures named the same in each event? Will I lose the photo or will iPhoto rename the duplicate names?

    I am trying to merge 2 events in iPhoto, but i notice that in the first event my photos are named by my camera as DSC_001, DSC_002, etc.  But the same is true of the photos in the second event DSC_001, DSC_002, etc.  If I merge these 2 events will I