JTextField in JTableHeader

Hello,
I am trying to create table with filterbar. I am using my own reneder/editor for the table header which consist of JButton and JTextField on JPanel. After a character is typed to JTextField the table model is filtered and fireTableDataChanged is called. It works fine, but the JTextField loses focus and JTable gains it. I tried to request for focus again when JTable gains it, but it has no effect. Can you help me what should I do? Thank you!

I tried to request for focus again when JTable gains it, but it has no effectWhen you use the fireTableDataChanged() method the TableColumnMode and TableHeader is recreated. So even though you request focus on your text field this code may be executed before the table header has actually been recreated.
You can try wrapping the textField.requestFocusInWindow() method in a SwingUtilities.invokeLater() method. This will cause the request to be added to the end of the Event Thread, hopefully after the table has been recreated.
Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]How to Use Threads for more information on invokeLater.

Similar Messages

  • JTableHeader Animation

    I want to make the JTableHeader of my table animate the way a regular button does when click - flat,lowerd when pressed and high poped-up when released.
    I tried making a TableCellRenderer for the header and it works, the Header doesnt animate like a button. Nothing happens when i click it. Still remains flat.
    Here is the code:
    package tabledemo;
    import javax.swing.*;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.net.URL;
    public class ButtonHeaderRenderer extends JButton implements TableCellRenderer {
         static URL picUrl = ClassLoader.getSystemResource("smile.gif");
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                      boolean isSelected, boolean hasFocus,
                                                      int row, int column){
            LookAndFeel.installColorsAndFont(this,"TableHeader.background",
                                             "TableHeader.foreground",
                                             "TableHeader.font");
            LookAndFeel.installBorder(this,"TableHeader.cellBorder");
            setIcon(new ImageIcon(picUrl));
            setText((String)value);
            return this;
    }The icon and text show in the table header, but no animation.
    I was thinking maybe i can do something if i extend the JTableHeader class. I did that and i can change the dimensions of the columns with it but i dont know how to make the button animate here either.
    Here is the extended JTableHeader class:
    package tabledemo;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumnModel;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.*;
    public class JTableHeaderMouseEvents extends JTableHeader {
        String[] columnNames = {"FirstName","Lastname","Progress"};
        public JTableHeaderMouseEvents(TableColumnModel tcm){
            super(tcm);
            this.setPreferredSize( new Dimension( 70, 18  ) );
            addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent event){
                    int i = columnAtPoint(event.getPoint());
                    int column = getColumnModel().getColumn(i).getModelIndex();
                   // JOptionPane.showMessageDialog(null, "You pressed "+columnNames[column] + " column");
    }Maybe in the mousePressed/Released method of MouseAdapter i can use some method to programatically change the button effects?
    Any tips are appreciated.

    I saw the same problem when I try to put a JComboBox as a column's header. Just set the renderer is not enough, the button won't animate. I can think of two solutions.
    1. Do the animation manually.
         JTableHeader th = table.getTableHeader();
         th.addMouseListener( yourMouseListener);
    in yourMouseListener, you define have the component
    repaint itself, with shadow or without shadow.
    2. Make the header editable, just like the editable cells.
    Try this:
    import javax.swing.*;
    import javax.swing.table.*;
    * @version 1.0 08/21/99
    public class EditableHeaderTableColumn extends TableColumn {
    protected TableCellEditor headerEditor;
    protected boolean isHeaderEditable;
    public EditableHeaderTableColumn() {
    setHeaderEditor(createDefaultHeaderEditor());
    isHeaderEditable = true;
    public void setHeaderEditor(TableCellEditor headerEditor) {
    this.headerEditor = headerEditor;
    public TableCellEditor getHeaderEditor() {
    return headerEditor;
    public void setHeaderEditable(boolean isEditable) {
    isHeaderEditable = isEditable;
    public boolean isHeaderEditable() {
    return isHeaderEditable;
    public void copyValues(TableColumn base) {
    modelIndex = base.getModelIndex();
    identifier = base.getIdentifier();
    width = base.getWidth();
    minWidth = base.getMinWidth();
    setPreferredWidth(base.getPreferredWidth());
    maxWidth = base.getMaxWidth();
    headerRenderer = base.getHeaderRenderer();
    headerValue = base.getHeaderValue();
    cellRenderer = base.getCellRenderer();
    cellEditor = base.getCellEditor();
    isResizable = base.getResizable();
    protected TableCellEditor createDefaultHeaderEditor() {
    return new DefaultCellEditor(new JTextField());
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * @version 1.0 08/21/99
    public class EditableHeader extends JTableHeader
    implements CellEditorListener {
    public final int HEADER_ROW = -10;
    transient protected int editingColumn;
    transient protected TableCellEditor cellEditor;
    transient protected Component editorComp;
    public EditableHeader(TableColumnModel columnModel) {
    super(columnModel);
    setReorderingAllowed(false);
    cellEditor = null;
    // The columnModel is changed. It also exists in JTable.
    recreateTableColumn(columnModel);
    public void updateUI(){
    setUI(new EditableHeaderUI());
    resizeAndRepaint();
    invalidate();
    protected void recreateTableColumn(TableColumnModel columnModel) {
    int n = columnModel.getColumnCount();
    EditableHeaderTableColumn[] newCols = new EditableHeaderTableColumn[n];
    TableColumn[] oldCols = new TableColumn[n];
    for (int i=0;i<n;i++) {
    oldCols[i] = columnModel.getColumn(i);
    newCols[i] = new EditableHeaderTableColumn();
    newCols.copyValues(oldCols[i]);
    for (int i=0;i<n;i++) {
    columnModel.removeColumn(oldCols[i]);
    for (int i=0;i<n;i++) {
    columnModel.addColumn(newCols[i]);
    public boolean editCellAt(int index){
    return editCellAt(index);
    public boolean editCellAt(int index, EventObject e){
    if (cellEditor != null && !cellEditor.stopCellEditing()) {
    return false;
    if (!isCellEditable(index)) {
    return false;
    TableCellEditor editor = getCellEditor(index);
    if (editor != null && editor.isCellEditable(e)) {
    editorComp = prepareEditor(editor, index);
    editorComp.setBounds(getHeaderRect(index));
    add(editorComp);
    editorComp.validate();
    setCellEditor(editor);
    setEditingColumn(index);
    editor.addCellEditorListener(this);
    return true;
    return false;
    public boolean isCellEditable(int index) {
    if (getReorderingAllowed()) {
    return false;
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.isHeaderEditable();
    public TableCellEditor getCellEditor(int index) {
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.getHeaderEditor();
    public void setCellEditor(TableCellEditor newEditor) {
    TableCellEditor oldEditor = cellEditor;
    cellEditor = newEditor;
    // firePropertyChange
    if (oldEditor != null && oldEditor instanceof TableCellEditor) {
    ((TableCellEditor)oldEditor).removeCellEditorListener((CellEditorListener)this);
    if (newEditor != null && newEditor instanceof TableCellEditor) {
    ((TableCellEditor)newEditor).addCellEditorListener((CellEditorListener)this);
    public Component prepareEditor(TableCellEditor editor, int index) {
    Object value = columnModel.getColumn(index).getHeaderValue();
    boolean isSelected = true;
    int row = HEADER_ROW;
    JTable table = getTable();
    Component comp = editor.getTableCellEditorComponent(table,
    value, isSelected, row, index);
    // if (comp instanceof JComponent) {
    // ((JComponent)comp).setNextFocusableComponent(this);
    return comp;
    public TableCellEditor getCellEditor() {
    return cellEditor;
    public Component getEditorComponent() {
    return editorComp;
    public void setEditingColumn(int aColumn) {
    editingColumn = aColumn;
    public int getEditingColumn() {
    return editingColumn;
    public void removeEditor() {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
    editor.removeCellEditorListener(this);
    requestFocus();
    remove(editorComp);
    int index = getEditingColumn();
    Rectangle cellRect = getHeaderRect(index);
    setCellEditor(null);
    setEditingColumn(-1);
    editorComp = null;
    repaint(cellRect);
    public boolean isEditing() {
    return (cellEditor == null)? false : true;
    // CellEditorListener
    public void editingStopped(ChangeEvent e) {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
    Object value = editor.getCellEditorValue();
    int index = getEditingColumn();
    columnModel.getColumn(index).setHeaderValue(value);
    removeEditor();
    public void editingCanceled(ChangeEvent e) {
    removeEditor();
    // public void setReorderingAllowed(boolean b) {
    // reorderingAllowed = false;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    * @version 1.0 08/21/99
    public class EditableHeaderUI extends BasicTableHeaderUI {
    protected MouseInputListener createMouseInputListener() {
    return new MouseInputHandler((EditableHeader)header);
    public class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler {
    private Component dispatchComponent;
    protected EditableHeader header;
    public MouseInputHandler(EditableHeader header) {
    this.header = header;
    private void setDispatchComponent(MouseEvent e) {
    Component editorComponent = header.getEditorComponent();
    Point p = e.getPoint();
    Point p2 = SwingUtilities.convertPoint(header, p, editorComponent);
    dispatchComponent = SwingUtilities.getDeepestComponentAt(editorComponent,
    p2.x, p2.y);
    private boolean repostEvent(MouseEvent e) {
    if (dispatchComponent == null) {
    return false;
    MouseEvent e2 = SwingUtilities.convertMouseEvent(header, e, dispatchComponent);
    dispatchComponent.dispatchEvent(e2);
    return true;
    public void mousePressed(MouseEvent e) {
    if (!SwingUtilities.isLeftMouseButton(e)) {
    return;
    super.mousePressed(e);
    if (header.getResizingColumn() == null) {
    Point p = e.getPoint();
    TableColumnModel columnModel = header.getColumnModel();
    int index = columnModel.getColumnIndexAtX(p.x);
    if (index != -1) {
    if (header.editCellAt(index, e)) {
    setDispatchComponent(e);
    repostEvent(e);
    public void mouseReleased(MouseEvent e) {
    super.mouseReleased(e);
    if (!SwingUtilities.isLeftMouseButton(e)) {
    return;
    repostEvent(e);
    dispatchComponent = null;
    Here is my source code for using it:
    EditableHeaderTableColumn column0 = (EditableHeaderTableColumn)columnModel.getColumn(0);
    ComboRenderer renderer = new ComboRenderer(items);
    column0.setHeaderRenderer(renderer);
    // setHeaderEditor is provided by EditableHeaderTableColumn
    column0.setHeaderEditor(new DefaultCellEditor(combo));
    I can create DefaultCellEditor using a combobox. But you need to create the ButtonEditor, because DefaultCellEditor constructor won't take JButton.
    Good luck!

  • Open and Close OnScreen Keyboard while focus gain on JTextField

    Hi
    I have a Jtextfield when ever I click on textfield I want to open OSK(On Screen Keyboard) of Windows 8 OS and windows 7.
    I tried in below mentioned way to open and close in focus listener focusGained() and focusLost() but it is not working. could some body do needful.
    Opening OSK:
    builder = new ProcessBuilder("cmd /c " + sysroot + " /System32/osk.exe");
    Closing Osk:
    Runtime.getRuntime().exec("taskkill /f /im osk.exe");

    You need to start() the ProcessBuilder and you need to split the command like this:
    builder  = new ProcessBuilder("cmd", "/c", sysroot + " /System32/osk.exe");
    builder.start();
    And naturally you should wrap the call in a new Thread or use an ExecutorService to avoid EDT problems.

  • Displaying the results of an iterator in JTextfields.

    Hi people,
    I have got two methods which basically iterate through statements (forward and back).
    However I have a separate class which is basically the GUI for my program. I want the user to be able to click the next button and it iterates through the list and displays the element in the list in the JTextField.
    The problem I am having is that it will not display the element in the predefined fields, does anyone know how I can go about this? My code for my two methods is below:
    public void MusicNext()
               try
               if(titerator==null)
                   titerator = iList.listIterator();
               if(titerator.hasNext())
                   System.out.println(titerator.next());//Just prints out the iterator atm.
               else
                  titerator = null;
                  MusicNext();
               catch(ConcurrentModificationException ex)
                  titerator = iList.listIterator();
                  System.out.println("Iterator has been reset.");
              public Music MusicNext(String pTitle)
                Music tTitle = null;
             boolean found = false;
                Iterator it = iList.iterator();
                if(it.hasNext() && !found)
              tTitle = (Music) it.next();
              found = tTitle.getTitle().equalsIgnoreCase(pTitle);
                return tTitle;
            public void MusicPrevious()
               try
               if(titerator==null)
                   titerator = iList.listIterator();
               if(titerator.hasPrevious())
                   System.out.println(titerator.previous());//Just prints out the iterator atm.
               else
                  titerator = null;
               catch(ConcurrentModificationException ex)
                  titerator = iList.listIterator();
                  System.out.println("Iterator has been reset.");
               catch(NoSuchElementException ex)
                  //titerator = iList.listIterator();
                  System.out.println("No such element.");
         }I am pretty sure they shouldn't be void but should return an element, but I am really not sure what to return.
    Many Thanks,
    Rob.
    (Sorry I posted this before but I left out alot of detail).

    Don't get or instantiate the iterator in often-called methods.
    It should be get or instantiated as a class global field once and for all.
    Your ListIterator is good for such treatment becuase it can be
    freely scanned backward, while Iterator can't.

  • Initial JTextField value

    Hello!
    I'm puzzled with API docs:
    public JTextField()
    Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.
    But when I read the textfield with textfield.getText I do not get a null Object but an empty String object, i.e(""). Why?

    Hmm, very curious.Yes it is, so I looked into it.
    Perhaps the no-arugument constructor creates a default
    Document with an empty string?You are correct sir. In a round about way a character array is created which consists of a single character, that being the null terminator. If your still curious, its done in the GapContent constructor.

  • Can't Copy text unless console is opened before applet with JTextField

    If an applet uses JTextFields, it is impossible to copy text from the console to the clipboard (or anywhere else) if the console is opened after the applet.
    See http://demo.capmon.dk/~pvm/nocopy/nocopy.html for a working applet with source and class file to try it out on...
    So if something bad has happened, and there are hints in the console e.g. a stack trace, it all has to be retyped by hand, since all Copy or export is impossible...
    Does anyone know of a workaround for this? I'd like to be able to e.g. copy stack traces to bug reports.
    Try these test cases:
    * Close all browser windows. Open a browser and visit this page. After the page with this applet has loaded, then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Select some text in the console. There is no way to put this text on the clipboard; the "Copy" button doesn't work, and neither does CTRL+Insert, CTRL+C or anything else.
    * Close all browser windows. Open a browser window no some non-java page and then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Then visit this page. Select some text in the console. Now the "Copy" button does work, enabling "export" of e.g. stack traces to other applicaitons e.g. email.
    The difference is which is opened first: The console or the applet. If you look at the very rudimentary Java source code, it is the mere creation of a JTextField is what disables or breaks the Copy functionality.
    I've tried this on Windows XP with IE 6.0 and Mozilla 1.3 and they behave exactly the same. The JVM is Sun's 1.4.2 and I've tried 1.4.1_02 also with the same behavior. I've also tried javac from both 1.4.2 and 1.4.1_01

    hey .. this seems like a bug.. can you please file a bug at
    http://java.sun.com/webapps/bugreport
    thanks...

  • 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

  • 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

  • Getting values from a JTextField on a JPanel in another class

    I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
      int val;
      public TextFieldChooser(String str){
        val = 0;     
        setLayout(new FlowLayout());
        add(new JLabel(str));
        JTextField txtf = new JTextField(5);
        txtf.addActionListener(new TextFieldListener());
        add(txtf);
      }//end constructor     
      private class TextFieldListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
           val = Integer.parseInt(e.getActionCommand());
      }//end text field listener
      public int getValue(){
        return val;     
    }//class

    The problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
    I have created a class which extends a JPanel and
    added a JTextField to it, which has an
    addActionListener for getting the values typed in the
    JTextField. I want to use the class created in
    another class and retrieve the values typed in the
    JTextField, so how do i go about that? I have the
    class created below so the problem is how to retrieve
    content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
    int val;
    public TextFieldChooser(String str){
    val = 0;
    setLayout(new FlowLayout());
    add(new JLabel(str));
    JTextField txtf = new JTextField(5);
    txtf.addActionListener(new TextFieldListener());
    add(txtf);
    }//end constructor
    private class TextFieldListener implements
    s ActionListener{
    public void actionPerformed(ActionEvent e) {
    val = Integer.parseInt(e.getActionCommand());
    }//end text field listener
    public int getValue(){
    return val;
    }//class

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

  • Problem with focus and selecting text in jtextfield

    I have problem with jtexfield. I know that solution will be very simple but I can't figure it out.
    This is simplified version of situation:
    I have a jframe, jtextfield and jbutton. User can put numbers (0-10000) separated with commas to textfield and save those numbers by pressing jbutton.
    When jbutton is pressed I have a validator which checks that jtextfield contains only numbers and commas. If validator sees that there are invalid characters, a messagebox is launched which tells to user whats wrong.
    Now comes the tricky part.
    When user presses ok from messagebox, jtextfield should select the character which validator said was invalid so that user can replace it by pressing a number or comma.
    I have the invalid character, but how can you get the focus to jtextfield and select only the character which was invalid?
    I tried requestFocus(), but it selected whole text in jtextfield and after that command I couldn't set selected text. I tried with commands setSelectionStart(int), setSelectionEnd(int) and select(int,int).
    Then I tried to use Caret and select text with that. It selected the character I wanted, but the focus wasn't really there because it didn't have keyFocus (or something like that).
    Is there a simple way of doing this?

    textField.requestFocusInWindow();
    textField.select(...);The above should work, although read the API on the select(...) method for the newer recommended approach on how to do selection.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • Problem with PropertyChangeListener and JTextField

    I'm having a problem with PropertyChangeListener and JTextField.
    I can not seem to get the propertychange event to fire.
    Anyone have any idea why the code below doesn't work?
    * NewJFrame.java
    * Created on May 15, 2005, 4:21 PM
    import java.beans.*;
    import javax.swing.*;
    * @author wolfgray
    public class NewJFrame extends javax.swing.JFrame
    implements PropertyChangeListener {
    /** Creates new form NewJFrame */
    public NewJFrame() {
    initComponents();
    jTextField1.addPropertyChangeListener( this );
    public void propertyChange(PropertyChangeEvent e) {
    System.out.println(e);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1, java.awt.BorderLayout.NORTH);
    jFormattedTextField1.setText("jFormattedTextField1");
    jScrollPane1.setViewportView(jFormattedTextField1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    pack();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    }

    If you want to listen to changes in the textfield's contents you should use a DocumentListener and not a PropertyChangeListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html
    And please use [co[/i]de]  tags when you are posting code (press the code button above the message window).

  • Memory problem with JTextFields

    Hello,
    I have a wierd problem with JTextField and the memory.
    I need to fill a JPanel with different Components (including JTextFields), then do some calculation, remove the Components and filling the JPanel again.
    When i so this too often my i get an OutOfMemory Exception. I narrowed to problem down and wrote a small sample program to demonstrate the problem.
    When i call the method doIT (where the Panel is repeatedly filled) from the main-function everything works fine, but when it is called as a result from the GUI-Button-Event the memory for the JTextFields is not freed (even the call of the Garbage collector changes nothing)
    When i only use JButtons to fill the Panel everything works fine.
    Has anyone an idea why this problem occurs and how i can work around it?
    [Edit] I tested it whith java 1.5.0_06, 1.5.0_11, 1.6.0_02
    Thanks
    Marc
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryUsage;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class MemoryTestDLG extends JDialog {
         public MemoryTestDLG(Frame owner) {
              // create Dialog with one Button that calls the testMethod
              super(owner);
              JButton b = new JButton("doIT ...");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doIT();
                        setVisible(false);
              getContentPane().add(b);
              pack();
         public void doIT() {
              // Testmethod that fills a JPanel 20 times with Components and clears it
              // again
              JPanel p = new JPanel();
              long memUse1 = 0;
              long memUse2 = 0;
              long memUseTemp = 0;
              for (int count = 0; count < 20; count++) {
                   // Clear the panel
                   p.removeAll();
                   // Get memory usage before the task
                   Runtime.getRuntime().gc();
                   memUse1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // Fill Panel with components
                   for (int i = 0; i < 200; i++) {
                        // The Buttons seem to be released without any problem
                        p.add(new JButton("test" + Math.random()));
                        // JTextFields are not released when used from the dialog.
                        p.add(new JTextField("test " + Math.random()));
                   // get memory usage after the task
                   Runtime.getRuntime().gc();
                   memUseTemp = memUse2;
                   memUse2 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // print Memory results
                   System.out.println("Memory Usage: " + f(memUse1) + "   ->"
                             + f(memUse2) + " [ Used:" + f(memUse2 - memUse1)
                             + " ] [ Freed: " + f(memUseTemp - memUse1) + "]");
         public String f(long m) // formats the output
              String s = "" + m;
              while (s.length() < 8)
                   s = " " + s;
              return s;
         public static void main(String[] args) {
              MemoryTestDLG d = new MemoryTestDLG(null);
              System.out
                        .println("------------------ Direct Call (all is OK) -------------------");
              d.doIT(); // Memory is freed with every call to JPanel.removeAll()
              System.out
                        .println("------------ Call from Dialog (memory is not freed) -------------");
              // The Memory keeps blocked
              d.setModal(true);
              d.setVisible(true);
              System.exit(0);
    }Message was edited by:
    marcvomorc

    Thank you for your answer,
    In this sample the programm does not run out of memory. But when you look at the output you see, that in the first run (direct call) the memory ist freed immediately when tha panel is cleared but in the second run (from the Button) the memory usage is getting bigger and bigger. Wenn you change the number of components to 2000 (4000)
    // Fill Panel with components
            for (int i = 0; i < 2000; i++) {
                // The Buttons seem to be released without any problem
    //... ...and use the default memory settings (69mb heap) the programm runns out of memory.
    I get the following output:
    ------------------ Direct Call (all is OK) -------------------
    Memory Usage:   445504   -> 8121016 [ Used: 7675512 ] [ Freed:  -445504]
    Memory Usage:   617352   -> 8114336 [ Used: 7496984 ] [ Freed:  7503664]
    Memory Usage:   810488   -> 8491768 [ Used: 7681280 ] [ Freed:  7303848]
    Memory Usage:   943704   -> 8114976 [ Used: 7171272 ] [ Freed:  7548064]
    Memory Usage:   836760   -> 8505072 [ Used: 7668312 ] [ Freed:  7278216]
    Memory Usage:   978352   -> 8114784 [ Used: 7136432 ] [ Freed:  7526720]
    Memory Usage:   835552   -> 8498288 [ Used: 7662736 ] [ Freed:  7279232]
    Memory Usage:   977096   -> 8114312 [ Used: 7137216 ] [ Freed:  7521192]
    Memory Usage:   835640   -> 8498376 [ Used: 7662736 ] [ Freed:  7278672]
    Memory Usage:   977296   -> 8115000 [ Used: 7137704 ] [ Freed:  7521080]
    Memory Usage:   835392   -> 8504872 [ Used: 7669480 ] [ Freed:  7279608]
    Memory Usage:   976968   -> 8115192 [ Used: 7138224 ] [ Freed:  7527904]
    Memory Usage:   836224   -> 8501624 [ Used: 7665400 ] [ Freed:  7278968]
    Memory Usage:   977840   -> 8115120 [ Used: 7137280 ] [ Freed:  7523784]
    Memory Usage:   835664   -> 8498256 [ Used: 7662592 ] [ Freed:  7279456]
    Memory Usage:   976856   -> 8114384 [ Used: 7137528 ] [ Freed:  7521400]
    Memory Usage:   835784   -> 8502848 [ Used: 7667064 ] [ Freed:  7278600]
    Memory Usage:   977360   -> 8114592 [ Used: 7137232 ] [ Freed:  7525488]
    Memory Usage:   835496   -> 8502720 [ Used: 7667224 ] [ Freed:  7279096]
    Memory Usage:   976440   -> 8115128 [ Used: 7138688 ] [ Freed:  7526280]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   866504   -> 8784320 [ Used: 7917816 ] [ Freed:  -866504]
    Memory Usage:  7480760   ->14631152 [ Used: 7150392 ] [ Freed:  1303560]
    Memory Usage: 14245264   ->22127104 [ Used: 7881840 ] [ Freed:   385888]
    Memory Usage: 19302896   ->27190744 [ Used: 7887848 ] [ Freed:  2824208]
    Memory Usage: 27190744   ->35073944 [ Used: 7883200 ] [ Freed:        0]
    Memory Usage: 31856624   ->39740176 [ Used: 7883552 ] [ Freed:  3217320]
    Memory Usage: 39740176   ->47623040 [ Used: 7882864 ] [ Freed:        0]
    Memory Usage: 44410480   ->52293864 [ Used: 7883384 ] [ Freed:  3212560]
    Memory Usage: 52293864   ->58569304 [ Used: 6275440 ] [ Freed:        0]
    Memory Usage: 58569304   ->64846400 [ Used: 6277096 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spacewhen I outcomment the adding of the JButtons the amount of freed memory is 0 in the second run. So my guess is, that there is a problem with freeing the memory for the JTextFields.
    Memory Usage:   447832   -> 6509960 [ Used: 6062128 ] [ Freed:  6332768]
    Memory Usage:   722776   -> 6785632 [ Used: 6062856 ] [ Freed:  5787184]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   468880   -> 6770240 [ Used: 6301360 ] [ Freed:  -468880]
    Memory Usage:  6770240   ->13016264 [ Used: 6246024 ] [ Freed:        0]
    Memory Usage: 13016264   ->19297080 [ Used: 6280816 ] [ Freed:        0]
    Memory Usage: 19297080   ->25570152 [ Used: 6273072 ] [ Freed:        0]
    Memory Usage: 25570152   ->31849160 [ Used: 6279008 ] [ Freed:        0]
    Memory Usage: 31849160   ->38124368 [ Used: 6275208 ] [ Freed:        0]
    Memory Usage: 38124368   ->44402072 [ Used: 6277704 ] [ Freed:        0]
    Memory Usage: 44402072   ->50677928 [ Used: 6275856 ] [ Freed:        0]
    Memory Usage: 50677928   ->56955880 [ Used: 6277952 ] [ Freed:        0]
    Memory Usage: 56955880   ->63232152 [ Used: 6276272 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spaceAdditionally the JPanel I am using is not displayed on the screen. It stays invisible the whole time, but i cannot work around that, because the calculation is depending on the values being in components on the JPanel)
    Marc

  • How to change background color of all JTextFields

    Hi,
    I have made the code below to show all properties available in UIDefaults.
    Then, I would like to have the same behaviour that this Web Forum, that sets a yellow color in background of "Subject input text", when the user focus this field. I want this in my Swing apps, when user changes from a field to other. But I didn't find something like "TextField.focusBackground" to do this...
        UIDefaults uidef = UIManager.getDefaults();
        Enumeration enumkey = uidef.keys();
        Enumeration enumdef = uidef.elements();
        while (enumdef.hasMoreElements()) {
          System.out.println(
            enumkey.nextElement().toString() + " = " +
            enumdef.nextElement().toString());
        }I would like to set up colors in the beggining of my Swing app, something like this for all components:
    UIManager.put("TextField.focusBackground", java.awt.Color.YELLOW);
    UIManager.put("PasswordField.focusBackground", java.awt.Color.YELLOW);
    UIManager.put("TextArea.focusBackground", java.awt.Color.YELLOW);
    ...

    You can use the KeyBoardFocusManager. Start with the code below and customize to your requirements:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   JTextField textField = (JTextField)e.getNewValue();
                   textField.selectAll();
    });

  • How can a JTextField in a Dialog gain focus while mainframe is clicked

    Hi
    I have been trying to develop a 3d application. I have some shapes on a Canvas3D laid on a JFrame.
    I open a new shape dialog after pressing the appropriate button.
    Once the dialog is open I need to select two shapes on canvas for reference hence there are two text fields to show the name of each.
    when I select the first shape the corresponding textfield is being updated.
    Now the Problem
    I place the cursor in the second tex field and click on second shape on canvas.
    I lose focus from text field to canvas.
    Now I am unsure if the second textfield has the focus or is the focus with the first text field. Based on this focus info I can update the text fields.
    I understand that only one field can have focus at a time.
    My doubt is How can the JTextField retain its focus while the components on main window are being clicked.
    The following code is enclosed in a listener that responds to picked shapes.
    if(gooi.getSketchDialog() != null && gooi.getSketchDialog().isShowing()){
                gooi.getPick1().getCanvas().setFocusable(false);
                if(gooi.getSketchDialog().getSelectedPlaneTextField().isFocusOwner()){
                        if( pickResult != null)
                            gooi.getSketchDialog().getSelectedPlaneTextField().setText(pickResult.getNode(PickResult.SHAPE3D).getUserData().toString());
                        else if (pickResult == null){
                            gooi.getSketchDialog().getSelectedPlaneTextField().setText("");
            }Any help is appreciated.
    Thanks in Advance
    Venkat
    Edited by: pushinglimits on Oct 31, 2008 6:52 AM

    Michael
    The text field still loses focus when its containing window is no longer focused.import java.awt.FlowLayout;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class NoFocusTransfer implements FocusListener {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new NoFocusTransfer().makeUI();
       public void makeUI() {
          JTextField one = new JTextField(20);
          one.addFocusListener(this);
          JTextField two = new JTextField(20);
          two.addFocusListener(this);
          JFrame frameOne = new JFrame("");
          frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frameOne.setSize(400, 400);
          frameOne.setLocationRelativeTo(null);
          frameOne.setLayout(new FlowLayout());
          frameOne.add(one);
          frameOne.add(two);
          JButton button = new JButton("Click");
          button.setFocusable(false);
          JFrame frameTwo = new JFrame();
          frameTwo.add(button);
          frameTwo.pack();
          frameTwo.setFocusable(false);
          frameOne.setVisible(true);
          frameTwo.setVisible(true);
       public void focusGained(FocusEvent e) {
          try {
             System.out.println("Focus from: " +
                     e.getOppositeComponent().getClass().getName());
             System.out.println("Focus to: " +
                     e.getComponent().getClass().getName());
          } catch (NullPointerException npe) {
       public void focusLost(FocusEvent e) {
          try {
             System.out.println("Focus from: " +
                     e.getComponent().getClass().getName());
             System.out.println("Focus to: " +
                     e.getOppositeComponent().getClass().getName());
          } catch (NullPointerException npe) {
    }db

Maybe you are looking for

  • Can't open fresh install of iTunes (fresh install of Windows 7)

    Hi everyone, Well this problem has my head spinning. I'm an IT troubleshooter so I've done a lot of various trailing already which I detail below. Basically, we're looking at a brand new computer with a new installation Windows 7 Home Premium 64-bit.

  • New updates excludes me from opening Wimba audio posts

    I would go onto Drexel U. website and listen to audio posts from students through Wimba. Updated MacBook Pro last evening and now cannot access Wimba site. I can, however, access Wimba after I restart the computer. But, I need to restart every time t

  • JDialog best practice

    I am building a custom JDialog that includes a JPanel so that it's easier for me to customize (I'm using NetBeans). This is my first solo project as a developer so I want to make sure I follow best practice whenever possible. I have two questions in

  • ITunes Emergency 9.0.2

    Here's the situation: I spend a lot of time managing my iTunes library, be it buying new music at Best Buy (albums are getting cheaper these days) and putting cover art, years, etc. on them or managing podcasts, subcribing, unsubcribing and the like.

  • Link does not see W7 music

    I have read through other threads without success. My situation is this. On my Mac, Link works fine with iTunes. On my Windows 7 machine it simply sees no music. (no itunes on it, just WMP and VLC). It claims there is no music in my library, yet it s