A graybox inside JTextField !!!

I have a JTextField as one of the components in a GridBagLayout.
I see a very small gray rectangular box inside that JTextField.
Once I type something in that textfield, that gray box goes away!!!
Why is that happening ? Also, that gray magix box seem to be in the
same location. So, if I position my JTextField to someother place in
the layout, I dont see it !! Any ideas about why this is happening ?

My crystal ball says you have two components in that location (or set of locations) in the layout.

Similar Messages

  • JTextField doesn't cause a validateTree()

    Hello,
    I've written a new layout manager. If I change the visible state of a component the layout manager should do a new layout. This works for
    JLabel, JButton, JRadioButton, JCombobox, JPanel and JCheckbox but not for JTextField.
    After debugging I noticed, that JTextField is the only Component witch ovewrites the method isValidateRoot() and so it returns true instead of false. This causes that the RepaintManager.addInvalidComponent() returns before it adds an event to the EventQueue if the JTextfield is changed to visible = false.
    Is this a bug, or how can I solv this problem?
    Thx
    Guido

    If somebody has an answer to this question I would still be very interested.
    I am also puzzled about the logic inside the method isValidateRoot() inside JTextField:
        public boolean isValidateRoot() {
         Component parent = getParent();
         if (parent instanceof JViewport) {
             return false;
            return true;
        }Meaning the JTextField is itself in charge for handling layout updates inside its own boundaries, but also when calling setVisible(true) on the JTextField. The documentation says that it is for handling calls to revalidate from within the component itself (unless it is contained inside a JViewport). I don't understand this. If anyone can explain this?
    At first sight overriding isValidateRoot() always returning true in a subclass of JTextField would also solve the problem. But that could lead to a much heavier revalidation of the internal JTextField mechanisms?
    Conclusion (without knowing answers to the questions above) is that when you call setVisible on a JTextField that you have to call revalidate() on its container again in order to see the new layout situation.

  • Placing a JButton inside a JTextfield aligned to right

    hi,
    i would like to add a JButton inside a JTextField. Actually the textfield shows the current path to which image is saved. So to get a file browser, user will click a small button present inside the textfield and selects the file and simultaneously the text of jtextfield is updated.
    i tried of using jTextField1.add(jButton1); but it has no effect. Neither button was displayed nor any error message was displayed.
    So plzz help me out. thanx

    You shouldn't try to put the JButton in the JTextField. A JTextField isn't meant to hold other components.
    Create a JPanel and add the JTextField and the JButton to it.

  • Setting two JTextFields inside JTable cell

    hi,
    I am really stick trying to figure out how to set two cells inside a JTable cell. This needs to be done because if there is a value already inside the cell then i want to drop another value - this new value should be displayed inside another cell but along with the other value already in the cell.
    I assume that i would need to create two JTextFields.
    But can anyone help me further please.

    That should be a simple issue of customizing table cell editor and renderer.
    See tutorials.

  • Jtextfield inside jtable..please i need help

    Hello, im trying to put textfield in a cell of Jtable but appears the following text inside of JTextField that i've inserted...
    javax.swing.JTextField[,0,0,0x0,invalid,disabled,layout=javax.swing.plaf.basic.Basic
    TextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.Border
    UIResource$CompoundBorderUIResource@196c1b0,flags=296,maximumSize=,minimumSize
    =,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabled
    TextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=
    javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=
    sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.Color
    UIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontal
    Alignment=LEADING]
    Thus i've implemented a class FBaseTableCellEditor extends DefaultCellEditor that allow me to have JTextfield like cell of JTable.
    this is the source code :
    public class FBaseTableCellEditor extends DefaultCellEditor {
    public FBaseTableCellEditor() {
    super(new javax.swing.JTextField());
    this.editorComponent = new javax.swing.JTextField();
    //this.setClickCountToStart(1);
    ths is the source code to insert a new row in the JTable:
    private void AddRowsinTable(){
    int row = JTable.getRowCount() - 1;
    JTextField[] newrow = CreateRow();
    this.DefaultTableModel.addRow(newrow);
    private JTextField[] CreateRow()
    JTextField[] newrow = {this.JTextField0, this.JTextField1, this.JTextField2, this.JTextField3, this.JTextField4, this.JTextField5, this.JTextField6};
    return newrow;
    PLEASE I NEED HELP...
    Message was edited by:
    negrera

    tripple posting: http://forum.java.sun.com/thread.jspa?threadID=5120228

  • Can i put a Image  or ImageIcon inside a JTextField?

    youst the same way it is on Windows Media Player 11(the textField on the toolBar) and add AddXXXListerner to the image?
    or maybe like the textField on the iTunes toolbar?

    Can i put a Image or ImageIcon inside a JTextField?http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=014531

  • Inputverifier+Jtextfield inside JTable

    I've got an application which a JTable.
    Inside the JTable I've got a JTextfield for editing the fisrt column
    jTable1.getColumn("First" ).setCellEditor( new DefaultCellEditor( mytextfield ) );
    The JTextField has a InputVerifier
    This InputVerifier is called when I try to click outside the JTextField
    But The JTextField lost the focus always.
    What should I do to keep the focus on the JtextField ?
    The problem is only when the JTextfield is inside the JTable, if the JTextField is outside then the focus works fine.
    Thanks.
    wmiro.

    Hi,
    Create your own editor which implements TableCellEditor and let the stopCellEditing() method
    have a logic like this:
    public boolean stopCellEditing()
          if (selectedEditor == stringEditor)
             boolean valid = textField.getInputVerifier().verify(textField);
             if (!valid) return false;
          return selectedEditor.stopCellEditing();
       }

  • Disable keyboard action inside a JTextField

    Hi,
    I am new to Swing programming ... I just want to know how to disable all keyboard actions inside a JTextField. I don't want to use setEnabled / setDisabled or setEditable(true / false) ... because this causes the textfield background to turn gray color. It should be like HTML TextFields ... plzz help
    Thankss in advance

    Hi,
    thanks for ur reply, but I have aready used JTextField .. and implemented a logic so that the background stays default by calling setEditable(TRUE) just after setEditable(false) is called .. but still for atleast 1 sec the JTextField is turning gray and then default color ..

  • JTextFields inside a JPanel inside a JTable

    I have a JTable of one column, in which each row is a JPanel. The JPanel has JTextFields and JComboBoxs. The JPanel implements TableCellRenderer and TableCellEditor. It also declares an attribute as follows;
    DefaultCellEditor defCellEd = new DefaultCellEditor(new JComboBox);.
    All of the TableCellEditor methods are implemented in the same manner as the following method (except getCellEditorComponent(...)), i.e. they all pass the implementation onto the declared DefaultCellEditor;
    public boolean stopCellEditing()
         return defCellEd.stopCellEditing();
    getCellEditorComponent(...) is implemented to
    return (java.awt.Component)value;
    All seems to work fine, with one minor exception. My textfields are right justified, so for text that exceeds the default size of the textfield it is in, the first n characters are not visible initially. I would rather have it left justified with the trailing characters being not visible.
    If I do not set the cell editor for the panel (just setting the renderer) the text is left justified - problem there is, none of the fields are editable. Furthermore, testing of the JPanel standalone has the textfields left justified, also.
    Any help is appreciated, thanks in advance.

    I'm glad that helped.
    Basically, every text component has a caret, and the caret wants to be visible all the time, setText() moves the caret to the end, that's why setting the caret to null prevents this behavior.
    It appears that Sun doesn't intend to change this behavior so this fix is as far as I know the best we could do for now. See http://developer.java.sun.com/developer/bugParade/bugs/4227520.html for more information.

  • Requesting focus for JTextField inside JPanel

    I have an application with following containment hierarchy.
    JFrame --> JSplitPane --> JPanel.
    JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
    regards,
    Nirvan.

    I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.

  • Is it possible to embed html inside a JTextField?

    I have a Jpanel, which lists some information, but I want everything on there to be disabled. i.e. the user cant input anything (I want it to be so that the user knows they cant input anything as well)
    I have some textFields, but when I setEnabled(false), the text within is rather hard to read, so I wanted to try to use html to make the text bold, but that doesn't work.
    I also have a similar problem with havinga JCheckBox selected with is it not enabled. (its tough to see that it is selected)
    anyone have any ideas?

    Or just make the checkbox's icon ignore the enabled status, as in
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CheckBoxIconTest {
         public static void main( String[] args ) {
              JPanel p = new JPanel();
              final JCheckBox cb = new JCheckBox( "CheckBox" );
              cb.setIcon( new CheckBoxIcon() );
              JButton button = new JButton( "Toggle Enabled" );
              button.addActionListener( new ActionListener() {
                   public void actionPerformed( ActionEvent e ) {
                        cb.setEnabled( !cb.isEnabled() );
              p.add( cb );
              p.add( button );
              JFrame f = new JFrame( "CheckBoxIconTest" );
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.getContentPane().add( p );
              f.pack();
              f.setVisible( true );
         private static class CheckBoxIcon implements Icon {
              private JCheckBox cb = new JCheckBox();
              private Icon icon = UIManager.getIcon( "CheckBox.icon" );
              public void paintIcon( Component c, Graphics g, int x, int y ) {
                   ButtonModel itsModel = ( (JCheckBox) c ).getModel();
                   ButtonModel myModel = cb.getModel();
                   myModel.setArmed( itsModel.isArmed() );
                   myModel.setPressed( itsModel.isPressed() );
                   myModel.setSelected( itsModel.isSelected() );
                   icon.paintIcon( cb, g, x, y );
              public int getIconWidth() {
                   return icon.getIconWidth();
              public int getIconHeight() {
                   return icon.getIconHeight();
    }: jay

  • How to capture the event on changing focus from a JTextField?

    Hi All,
    I have got a problem...
    I want to do something (say some sort of validations/calculations) when I change the focus by pressing tab from a JTextField. But I am not able to do that.
    I tried with DocumentListener (jtf01.getDocument().addDocumentListener(this);). But in that case, it's calling the event everytime I ke-in something in the text field. But that's not what I want. I want to call that event only once, after the value is changed (user can paste a value, or even can key-in).
    Is there any way for this? Is there any method (like onChange() in javascript) that can do this.
    Please Help me...
    Regards,
    Ujjal

    Hi Michael,
    I am attaching my code. Actual code is very large containing 'n' number of components and ActionListeners. I am attaching only the relevant part.
    //more codes
    public class PaintSplitDisplay extends JApplet implements ActionListener
         JFrame jf01;
         JPanel jp01;
         JTextField jtf01, jtf02;
         //more codes
         public void start()
              //more codes
             jtf01 = new JTextField();
              jtf01.setPreferredSize(longField);
              jtf01.setFont(new Font("Courier new",0,12));
              jtf01.setInputVerifier(new InputVerifier(){public boolean verify(JComponent input)
                   //more codes
                   System.out.print("updating");
                   jtf02.setText("updated value");
                   System.out.print("updated");
                   return true;
              //more codes
              jtf02 = new JTextField();
              jtf02.setPreferredSize(mediumField);
              jtf02.setEditable(false);
              jp01.add(jtf02, gbc);
              //more codes
              jf01.add(jp01);
              jf01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf01.setVisible(true);
              //more codes
         public static void main(String args[])
              PaintSplitDisplay psp = new PaintSplitDisplay();
              psp.start();
         public void actionPerformed(ActionEvent ae)
              //more codes
    }As you can see I want to update the second JTextField based on some calculations. That should happen when I change the focus from my frist JTextField. I have called jtf02.setText() method inside InputVerifier. But it's giving error...
    Please suggest...
    Ujjal

  • Swing: when trying to get the values from a JTable inside an event handler

    Hi,
    I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
    I put two buttons (plus labels) and a JTextField . The buttons have the following role:
    One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
    So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
    do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
    I would thank you very much for the help.
    Daniel V. Gomes
    here goes the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import AdvanceMath.*;
    public class MathF2 extends JFrame {
    private JTextField ArrayOfFields[];
    private JTextField DimOfSis;
    private JButton Calcular;
    private JButton Ativar;
    private JLabel label1;
    private JLabel label2;
    private Container container;
    private int value;
    private JTable DataTable;
    private double[][] A;
    private double[] B;
    private boolean dimensionado = false;
    private boolean podecalc = false;
    public MathF2 (){
    super("Math Calcs");
    Container container = getContentPane();
    container.setLayout( new FlowLayout(FlowLayout.CENTER) );
    Calcular = new JButton("Resolver");
    Calcular.setEnabled(false);
    Ativar = new JButton("Dimensionar");
    label1 = new JLabel("Clique no bot�o para resolver o sistema.");
    label2 = new JLabel("Qual a ordem do sistema?");
    DimOfSis = new JTextField(4);
    DimOfSis.setText("0");
    JTable DataTable = new JTable(10,10);
    container.add(label2);
    container.add(DimOfSis);
    container.add(Ativar);
    container.add(label1);
    container.add(Calcular);
    container.add(DataTable);
    for ( int i = 0; i < 10 ; i ++ ){
    for ( int j = 0 ; j < 10 ; j++) {
    DataTable.setValueAt("0",i,j);
    myHandler handler = new myHandler();
    Calcular.addActionListener(handler);
    Ativar.addActionListener(handler);
    setSize( 500 , 500 );
    setVisible( true );
    public static void main ( String args[] ){
    MathF2 application = new MathF2();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing (WindowEvent event)
    System.exit( 0 );
    private class myHandler implements ActionListener {
    public void actionPerformed ( ActionEvent event ){
    if ( event.getSource()== Calcular ) {
    if ( event.getSource()== Ativar ) {
    //dimensiona a Matriz A
    if (dimensionado == false) {
    if (DimOfSis.getText()=="0") {
    value = 2;
    } else {
    value = Integer.parseInt(DimOfSis.getText());
    dimensionado = true;
    Ativar.setEnabled(false);
    System.out.println(value);
    } else {
    Ativar.setEnabled(false);
    Calcular.setEnabled(true);
    podecalc = true;
    try {
    InitValores( DataTable, value );
    } catch (Exception e) {
    System.out.println("Erro ao criar matriz" + e );
    private class myHandler2 implements ItemListener {
    public void itemStateChanged( ItemEvent event ){
    private void InitValores( JTable table, int n ) {
    A = new double[n][n];
    B = new double[n];
    javax.swing.table.TableModel model = table.getModel();
    for ( int i = 0 ; i < n ; i++ ){
    for (int j = 0 ; j < n ; j++ ){
    Object temp1 = model.getValueAt(i,j);
    String temp2 = String.valueOf(temp1);
    A[i][j] = Double.parseDouble(temp2);

    What I did is set up a :
    // This code will setup a listener for the table to handle a selection
    players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = players.getSelectionModel();
    rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
    //Class will take the event and call a method inside the Delete_Player object.
    class Delete_Player_row_Selection
    implements javax.swing.event.ListSelectionListener
    Delete_Player adaptee;
    Delete_Player_row_Selection (Delete_Player temp)
    adaptee = temp;
    public void valueChanged (ListSelectionEvent listSelectionEvent)
    adaptee.row_Selection(listSelectionEvent);
    in the row_Selection function
    if(ex.getValueIsAdjusting()) //To remove double selection
    return;
    ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
    if(lsm.isSelectionEmpty())
    System.out.println("EMtpy");
    else
    int selected_row = lsm.getMinSelectionIndex();
    ResultSetTableModel model = (ResultSetTableModel) players.getModel();
    String name = (String) model.getValueAt(selected_row, 1);
    Integer id = (Integer) model.getValueAt(selected_row, 3);
    This is how I got info out of a table when the user selected it

  • 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.

  • Need some help in jtextfield

    (repost from Programming Forum)
    Hello
    I want to create a jtextfield that only allows user to key in numerics and with fixed character length (means only a fixed length of characters can be entered).
    I have viewed this post:
    http://forum.java.sun.com/thread.jspa?threadID=536977&messageID=2597211
    and one of the reply said that the numeric part can be done with key listener, but I just don`t know how to do this, even after viewing the API.
    Hope that anyone could help me on this.
    Regards.

    camickr:
    Thanks, I`m now starting to study how to use
    JFormattedTextField. I hope it won`t be complicated.
    javabinge:
    I`ve tested your code, and the part inside keyTyped
    really needs to move to other parts, as getKeyCode()
    in keyTyped only returns VK_UNDEFINED, which is 0;
    And after moving the code the KeyPressed and
    keyReleased, only numeric keys can be entered, even
    Directional Key, Backspace and Delete won`t work
    lol
    t thank you for the code anyway, as it does help me A
    LOT.oh shoot, sorry for the mixup... just add an else if for other keys...
    ie.
    if( !event.getKeyCode()==KeyEvent.VK_LEFT)
    event.consume();
    actually if you put the condition for numerics in the keyTyped, it should work... because directionals and delete/backspace are not keytypes... they should be captured in keypress
    another thing to look at would be input verifier and the document

Maybe you are looking for