JTextField and Chars

How can I setText in a JTextField which is a char?
I do text.setText("" + character);
but it doesn't print right. However if i do System.out.println(character);
it prints it just as i want to. How can i make JTextField work with chars?

pbrockway2: Ok, as you said have it return a string. Well I gave it a go. But it only gives out just the first char of the string. Maybe you can help me figure out if there is another way. Thanks for your help.
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
    public class Capital extends JPanel
      JTextField rename;
      JTextField original;
      JPanel panel1;
      JButton capsB;
          String g;
       public Capital()
         capsB = new JButton("Capitalize");
         capsB.addActionListener(
                new ActionListener()
                   public void actionPerformed(ActionEvent e)
                              rename.setText(Capitalize(g));                              
         original = new JTextField(50);
               g = "this is original text. this needs to be capitalized.";
               original.setText(g);
               rename = new JTextField(50);
               rename.setText("This is where the capitalized text needs to be displayed.");
               this.setLayout(new BorderLayout());
         this.add(original, BorderLayout.NORTH);
               this.add(capsB, BorderLayout.CENTER);
         this.add(rename, BorderLayout.SOUTH);
       public String Capitalize(String in)
               char ch;      
         char prevCh;  
         int i;        
         prevCh = '.';
         String caps = in.trim();
               String[] j = new String[caps.length()];
         for (i = 0; i < caps.length(); i++ )
            ch = caps.charAt(i);
            if(Character.isLetter(ch) && ! Character.isLetter(prevCh))
               j[i] = "" + Character.toUpperCase(ch);
            else
               j[i] = "" + ch;
            prevCh = ch;
                    return j;
               return j[i];
public static void main (String[] args)
JFrame frame = new JFrame("Capitalize");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Capital panel = new Capital();
//frame.setPreferredSize(new Dimension(1000, 1000));
frame.getContentPane().add(panel);
// frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);

Similar Messages

  • Reading values from JTextField and using them?

    Hello,
    I am trying to make a login screen to connect to an oracle database. Im pretty new to creaing GUI. I need help with reading the values from the JTextField and to be able to use them for my connection. So do I need to apply a listener? How do I go about doing that in this project. Thanks for any code or advice.
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.sql.*;
    public class UserDialog
        String databaseURL;
        String driver;
        String database;
        String username;
        String password;
        String hostname;
        String port;
        UserDialog() {
            getInfo();
        static String[] ConnectOptionNames = { "Login", "Cancel" };
        static String   ConnectTitle = "Login screen";
        public void getInfo() {
            JPanel      connectionPanel;
            JLabel     databaseURLLabel = new JLabel("Database URL:   ", JLabel.LEFT);
         JTextField databaseURLField = new JTextField("");
         JLabel     driverLabel = new JLabel("Driver:   ", JLabel.LEFT);
         JTextField driverField = new JTextField("");
            JLabel     databaseLabel = new JLabel("Database:   ", JLabel.LEFT);
         JTextField databaseField = new JTextField("");
            JLabel     usernameLabel = new JLabel("User Name:   ", JLabel.LEFT);
         JTextField usernameField = new JTextField("");
            JLabel     passwordLabel = new JLabel("Password:   ", JLabel.LEFT);
         JTextField passwordField = new JPasswordField("");
            JLabel     hostnameLabel = new JLabel("Host Name:   ", JLabel.LEFT);
         JTextField hostnameField = new JTextField("");
            JLabel     portLabel = new JLabel("Port:   ", JLabel.LEFT);
         JTextField portField = new JTextField("");
         connectionPanel = new JPanel(false);
         connectionPanel.setLayout(new BoxLayout(connectionPanel,
                                  BoxLayout.X_AXIS));
         JPanel namePanel = new JPanel(false);
         namePanel.setLayout(new GridLayout(0, 1));
         namePanel.add(databaseURLLabel);
         namePanel.add(driverLabel);
            namePanel.add(databaseLabel);
            namePanel.add(usernameLabel);
            namePanel.add(passwordLabel);
            namePanel.add(hostnameLabel);
            namePanel.add(portLabel);
         JPanel fieldPanel = new JPanel(false);
         fieldPanel.setLayout(new GridLayout(0, 1));
         fieldPanel.add(databaseURLField);
            fieldPanel.add(driverField);
            fieldPanel.add(databaseField);
            fieldPanel.add(usernameField);
         fieldPanel.add(passwordField);
            fieldPanel.add(hostnameField);
            fieldPanel.add(portField);
         connectionPanel.add(namePanel);
         connectionPanel.add(fieldPanel);
            // Connect or quit
            databaseURL = databaseURLField.getText();
            driver = driverField.getText();
            database = databaseField.getText();
            username = usernameField.getText();
            password = passwordField.getText();
            hostname = hostnameField.getText();
            port = portField.getText();
            int n = JOptionPane.showOptionDialog(null, connectionPanel,
                                            ConnectTitle,
                                            JOptionPane.OK_CANCEL_OPTION,
                                            JOptionPane.PLAIN_MESSAGE,
                                            null, ConnectOptionNames,
                                            ConnectOptionNames[0]);
            if (n == 0) {
                System.out.println("Attempting login: " + username);
                String url = databaseURL+hostname+":"+port+":"+database;
             // load the JDBC driver for Oracle
             try{
                   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   Connection con =  DriverManager.getConnection (url, username, password);
                System.out.println("Congratulations! You are connected successfully.");
                con.close();
                System.out.println("Connection is closed successfully.");
             catch(SQLException e){
                System.out.println("Error: "+e);
            else if (n == 1)
                    System.exit(0);
        public static void main (String args []) {
             UserDialog ud = new UserDialog();
    }thanks again,
    James

    the reason why you can't get the text is because you are reading the value before some actually inserts anything in any fields.
    Here is what you need to do:
    Create a JDialog/JFrame. Create a JPanel and set that panel as contentPane (dialog.setContentPane(panel)). Insert all the components, ie JLabels and JTextFields. Add two buttons, Login and Cancel to the panel as well. Now get the username and password field values using getText() inside the ActionListener of the Login.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class LoginDialog extends JDialog
    String username, password;
      public LoginDialog( ){
        setTitle( "Login" );
        JPanel content = new JPanel(new GridLayout(0, 2) ); // as many rows, but only 2 columns.
        content.add( new JLabel( "User Name" ) );
        final JTextField nameField = new JTextField( "" );
        content.add( nameField );
        content.add( new JLabel( "Password" ) );
        final JTextField passField = new JTextField( "" );
        content.add( passField );
        JButton login = new JButton( "Login" );
        login.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent ae ){
            username = nameField.getText();
            password = passField.getText();
            // call a method or write the code to verify the username and login here...
        content.add( login );
        JButton cancel = new JButton( "Cancel" );
        cancel.addActionListener( new ActionListener( ){
          public void actionPerformed( ActionEvent ae ){
            dispose(); // close the window or write any code that you want here.
        content.add( cancel );
        pack( ); // pack everything in the dialog for display.
        show(); // show the dialog.

  • JTextfield and JButton

    Hi all
    My problem is that i have a JTextfield that is connected to a Oracle database that allow the user to enter data in the database. I want to have a button that will allow the user to test to see whether the data entered in the textfield is valid.
    I'm not sure if i need to use sqlj or not. Any help would be gladly received.
    Thanks
    null

    Hmmm... lots and lots of ways to handle this, depending on your particular need for the particular type of 'validation'. ( More info? )
    "JTextField" is not connected to a database in the same way that the infoswing "TextFieldControl" is.. .therefore one could trap the event ActionPerformed off the JTextField and do the checks ( or use the jbutton like you suggest..but it would seem like you'd always want it checked and corrected before continuing towards the inevitable commit attempt??? ).
    You can use sqlj, or you can not use it... depends upon the way you've architected your application/environment and your needs and desires.
    Note (if you haven't already ) that you can also do a heck of a lot of validation at the entity/view object level.
    In my case ( an application ) I have a jdbc connection up at the front end for all my miscellaneous stuff, and a validate PL/SQL stored function. The nice things about using stored procedures/functions are that the validate routines can be nested for quick and easy use by triggers and stored procedures. If you put it outside the database it gets more fun should you want to get at the common validation routines from all approaches.
    Curious as to how other folk are architecting their validations....

  • JTextField and JButtons not appearing until clicked.

    I'm writing a program to refresh my CS1 java skills. For some reason when I try to add a JTextField and two JButtons to my container they don't appear until Ive clicked them.
    Actually more specifically, this only happens after a 100ms wait after setting the frame visible. Any less and the components wind up visible, but scrunched up in the top middle of my frame.
    Ive found that if I add the components before and after the wait they are visible and in the correct place, but this makes a noticeable flicker.
    I'm running windows vista if that matters.
    If someone could help me I would appreciate it.
    snippet of code:
    public scrollText()
         drawingThread.start();
         mainFrame.setSize(640,160);
         mainFrame.setContentPane(draw);
         mainPane = mainFrame.getContentPane();
         mainPane.setBackground(Color.white);
         mainFrame.setResizable(false);
         mainFrame.setVisible(true);
         try
              Thread.sleep(100);
              addInterface();
         catch(InterruptedException e){}
    public void addInterface()
         textInput.setBounds(1,103,501,31);
         play.setBounds(502,103,65,30);
         play.addActionListener(this);
         stop.setBounds(568,103,65,30);
         stop.addActionListener(this);
         mainPane.add(textInput);
         mainPane.add(play);
         mainPane.add(stop);
    }

    Postings can't be moved between forums. Now you know for the next time.
    The general form for building a GUI is
    frame.getContentPane().add( yourComponentsHere );
    frame.pack();
    frame.setVisible( true );Then all the compnoent will show up according to the rules of the layout managers used.
    However is you add components to the GUI "after" the GUI is visible then the components are not automatically painted. You need to tell the GUI to invoke the layout manager again so your code would be:
    frame.getContentPane().add( componentsToVisibleGUI );
    frame.getContentPane().validate();

  • JtextField and list of data

    Hi everyone (and sorry for my english language....).
    I've this problem:
    I've a Frame with a JtextField and a button. When I click on this button, I want to show a list of data from a database and then I must choose a value that must go to the JtextField.
    Have you an idea how I can implement this? Sorry for this generic question, but I don't know how to do..
    Thank you!

    >
    As to your question.
    I've a Frame with a JtextField and a button. When I click on this button, I want to show a list of data from a database and then I must choose a value that must go to the JtextField.
    Have you an idea how I can implement this? ..Sure, plenty of people. But they will want to know exactly what you are having trouble with. E.G.
    - Getting data from a DB.
    - Putting data into a JList.
    - Adding listeners to that JList so that choices are acted on, rather than simply high-lighted as the selection.
    - Using the event provided to the listener, to update the JTextField.
    - Adding a JTextField and JList to a JFrame using layout managers.
    If your answer is 'all of that', then I suspect they would be tempted to:
    a) Advise you to put this project aside until you have considerably more experience.
    b) Refer you to the [Java Tutorial|http://java.sun.com/docs/books/tutorial/].

  • JTextField and JTextArea don't get focus occuasionally

    I am developing a Java Swing Applet. At edit mode, JComboBox, JCheckBox, JRadioBox, and JButton work fine, but JTextField and JTextArea can't get focus occuasionally while I click them.
    Anyone has idea?
    Thanks

    Thank you Himanshu,
    but that's not exactly what my issue is. This link describes the undesired effect of ending up outisde of the player window and in the browser.
    My problem is kind of the opposite. When I launch the page in the html file I cannot use the tab key to get to any of the controls in the captivate window. I'm stuck in the browser unless I click on the captivate window. That is not acceptable if we want it accessible without using a mouse. I found a way to make it work for chrome like I stated above, but not in FF. Do you have any ideas for this?
    Thanks!
    Monique

  • JTextField and JPasswordField

    Hi!
    How do I limit the character number that can be inserted into a JtextField and JPasswordField.
    For examen is the Password can be mam 6 characters, how do I do from limit the input?
    Thanks

    The most common way to limit what is entered in a JTextField is to create your own document. See the following thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=414464
    Graeme

  • JTextField and TextListener

    I am using an JTextField and I want to be notified when the text there have been changed. But there is no TextListener accessible in JTextField. Do I have to modify a CaretListener ?
    many Thanks/ Sam

    I am using an JTextField and I want to be notified
    when the text there have been changed. But there is no
    TextListener accessible in JTextField. Do I have to
    modify a CaretListener ?DocumentListener.

  • JTextField and transparency

    I have a JTextField and I am trying to set it up so it is somewhat transparent.
    mTextField.setBackground(new Color(255,255,255,50));
    But what happens when i do that is this: the textfield as a text value gets the text that i have set up for one of the neighbouring components.
    I am not sure why this happens.
    Has anyone experienced this problem before? Is there a fix to it?
    I tried setting up the text using setText to an empty string but it happens agian. I dont have this problem when the transparency is Not set.
    Cheers
    Dan

    I am not sure why this happens. An opaque component is responsible for painting the entire area of the component, which basically means that the RepaintManager doesnt' have to worry about the garbage that may exist where the component is about to be repainted.
    Since you background is somewhat transparent, you can see the garbage left behind. (Don't ask me what its left behind from, thats in the details of the Swing repaint manager which I know nothing about).
    Michaels suggestion makes the component transparent which means Swing will paint the background of the components parent. However when you do this, the background of your component isn't painted.
    So heres a solution that paints the background of the parent and the child:
    JTextField textField = new JTextField("Some Text")
         protected void paintComponent(Graphics g)
              g.setColor( getBackground() );
              g.fillRect(0, 0, getSize().width, getSize().height);
              super.paintComponent( g );
    textField.setBackground(new Color(0, 255, 255, 50));
    textField.setOpaque( false );

  • Accelerators, JTextField, and focus

    I created a JMenuItem for Save. I also created an accelerator for the Save menu item.
    JMenuItem saveItem;
    JMenu fileMenu = new JMenu ("File");
    fileMenu.add (saveItem = new JMenuItem ("Save"));
    saveItem.setMnemonic ('S');
    KeyStroke cntrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S,
    Event.CTRL_MASK);
    saveItem.setAccelerator (cntrlS);
    saveItem.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    doSaveNote();
    When the user is finished entering data into the JTextField(s), the user then either presses ctrl-S or clicks on the Save button on the menu. My code (not shown) validates data in JTextFields when the Save accelerator or button is pressed (blank field is considered invalid as well as wrong flight number). If data is invalid, then the first field with invalid data gets focus.
    If the JTextField has focus and invalid data is there, then when the user clicks the Save button the JTextField still has focus with a message letting the user know the data is invalid. However, if the user puts invalid data in the JTextField and uses the accelerator ctrl-S without tabbing out of the field first, the invalid JTextField does not get focus and no error message is presented. When using the accelerator the invalid JTextField only gets focus and prints an error message if the user tabs out of the JTextField befor pressing ctrl-S.
    I don't want to tab out of the field. Why is the behavior different between the accelerator and clicking the Save button? Any help is appreciated.

    You can request focus for another component.
    Or you could do: myTextField.setFocusable(false). But in this case you would have to make it fosucable later on if you want to use it.

  • JTextField [] and MouseEntered

    Hello
    I know this type of question has been asked in the forums before, but might is kind of different...i think.
    I have an array of JTextFields and i want each of there color to turn to GRAY when the mouse is on top of them.
    So if mouse is on top of TextField1 then only TextField1 turns GRAY.
    my Current mouseEntered() method is this
    public void mouseEntered(MouseEvent me)
                 for (int i=0; i < nasdaqTFs.length; i++){
                nasdaqTFs.setEditable(false);
              nasdaqTFs[i].setBackground(Color.GRAY);
    This, obviously, turns ALL the TextFields to GRAY when the cursor is in the Panel. So cursor can be anywhere and they all turn GRAY.
    So the question is...how do i find out when the Cursor is on the Specific TextField.

    Learning from earlier today This time i did write a Short Example of what i want done.
    Maybe this time i didnt do a bad job at it
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Listener extends JFrame implements MouseListener
         JTextField t;
         JTextField t1;
         public Listener ()
              super ("test");
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              t = new JTextField(4);
              c.add(t, BorderLayout.NORTH);
              t1 = new JTextField (4);
              c.add(t1, BorderLayout.SOUTH);
              addMouseListener(this);
              setVisible(true);
              setSize(300,300);
              MouseMotionListener don = new MouseMotionAdapter(){
              public void mouseEntered(MouseEvent me) {
                   System.out.println("Enterd)");
                 me.getComponent().setBackground(Color.GRAY);
              t.addMouseMotionListener(don);
              t1.addMouseMotionListener(don);
         public static void main (String args[])
              Listener l = new Listener ();
           public void mouseEntered(MouseEvent me)
             /*JTextField tf = (JTextField) me.getSource();
             tf.setBackground(Color.GREEN);*/
                me.getComponent().setBackground(Color.GREEN);
           public void mouseExited(MouseEvent me)
             /*JTextField tf = (JTextField) me.getSource();
             tf.setBackground(Color.white);*/
                me.getComponent().setBackground(Color.WHITE);
           public void mousePressed(MouseEvent me){}
           public void mouseReleased(MouseEvent me){}
           public void mouseClicked(MouseEvent me){}
    }This GUI wont change colors of TF's either. However when i move around the GUI i see somethin Green flickering!

  • Link between documentation for chars value and chars

    Hi,
    we need to find out sap transaction or report for link between documentation of chars value and chars.
    we know for specific chars through CT04 and going to VALUES sub-tab then selecting perticular chars value and clicking on the documentation for value.

    Go to transaction CT10 and select display option 'Allowed values'. You will have the characteristics along with their values.

  • How to for JTextField and JButton..

    How can i set the size of the JTextField and getting the words alignment to be in Center format?? Can i use JButton, click on it and key in value to be displayed in text form?

    Hi,
    you can change the alignment really simple:
    JTextField textField = new JTextField("Your Text");
    textField.setHorizontalAlignment(JTextField.LEFT);
    textField.setHorizontalAlignment(JTextField.CENTER);
    textField.setHorizontalAlignment(JTextField.RIGHT);The size can be set by
    setPrefferedSize(int w, int h)or try
    setColumns(int columns)L.P.

  • How to put both number and char in values?

    Hi ,
    Cud anyone tell me how can i put both number and char value in one colun. Such as i want to put ..(A121)..in REFNo column . so it includes both number and char .how can i do this?

    Hi,
    If you will ever want to treat the numeric part of refno as a NUMBER, then I suggest you store the values in two separate columns, refno_alpha and refo_num. For example, if "ORDER BY refno" should produce:
    A1
    A1.1
    A2
    A10
    A11
    A100
    A121
    B1then it will be easier to have two columns.
    When necessary, you can always combine the two columns (using "refno_alpha || refno_num"). You can create a function-based index and/or a view with that expression if it helps you.
    Also, as William said, validation is easier if the numbers are separate.

  • Byte and char !!!

    Hi!
    What is the diference between an byte and char in Java! Could I use char instead of byte and reverse?
    Thanks.

    TYPE BYTE BITS SIGN RANGE
    byte 1 8 SIGNED -128 to 127
    char 2 16 UNSIGNED \u0000 to \uFFFF
    Both the date types can be interchanged
    Have a look at this
    class UText
         public static void main(String[] args)
              byte c1;          
              char c2= 'a';
              c1 = (byte) c2;
              c2 = (char) c1;          
              System.out.println(c1 +" "+c2);
    But It Leads to confusion while interchanging because of its SIGN. And the range of byte is very less.So its better to prefer char.

Maybe you are looking for

  • Photoshop improvements. Disappointment at Adobe.

    Hi! All you know about recent Adobe decision to move to CC bussiness model. "Do less, charge more", good implementation of this principle. Before I was Adobe fan and I sincerely wanted to help them improve their products, I thought they want too. I c

  • Logging to a systemd per-user journal from shell

    Does anybody know how I can log a message to a per-user journal without using a per-user systemd service (~/.config/systemd/user/something.service)? As root, I can run: echo This is a test. | systemd-cat -t test or: echo This is a test. | logger -t t

  • Dividing payment history data (KNB4) under sales area of a customer..

    Hello Everybody,           I need to divide the payment history data available in KNB4 table according to divisions which are available under one customer. But payment history data is automatically updated when we are posting the payments ( If "payme

  • Caremefile is causing problems.

    Over the last two days I have had my Safari browser frozen by a website called Caremefile, (www.caremefile.info), while "Googeling" some web search, which invites you to download something. The first time it said my Media Player was out of date and a

  • STORAGE_PARAMETERS_WRONG_SET problem

    Dear Guru, When i run one copa report , it showed me below short-dump , and i have changed some memory parameters ... but still unavailable ........ Has someone can guide me how to solve this issue ? Many thanks ! Message : Runtime errors         STO