Password column in a JTable

I want the values entered in a column to have "***********" i.e as password, instead of actually displaying the text . How can I do this? Thanks.

Thanks for you response. I got it working now. but I have another question.
I see the JPasswordField added when the table gets displayed. I want it to be added only when I click on it. what can I modify to get this.
tblConnections =
new JTable(tm) {
public String getToolTipText(MouseEvent e) {
Point pt = e.getPoint();
int column = columnAtPoint(pt);
int row = rowAtPoint(pt);
if (column > -1 && row > -1) {
String tooltipString = "";
Project project = ProjectSet.getProject();
IconData iconData = (IconData) tblConnections.getValueAt(0, 0);
String connectionName = (String)iconData.getData();
List connectionList = project.getDefaultConnections();
for (java.util.Iterator itr = connectionList.iterator(); itr.hasNext(); ) {
Connection connection = (Connection) itr.next();
if ((connection.getName()).equals(connectionName)) {
tooltipString = "Connector" + " = " + connection.getName() + "\n"
+ "Type" + " = " + connection.getDataType() + "\n"
+ "Server" + " = " + connection.getDataServerName();
tooltipString = "<html><pre>" + tooltipString + "</pre></html>";
return tooltipString;
} else {
return (null);
public TableCellRenderer getCellRenderer(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = tableColumn.getCellRenderer();
if (renderer == null) {
Class c = getColumnClass(column);
if (c.equals(Object.class)) {
Object o = getValueAt(row, column);
if (o != null) {
c = getValueAt(row, column).getClass();
renderer = getDefaultRenderer(c);
if(column == (tblConnections.getColumnModel().getColumnIndex("Password"))) {
MyRenderer myRenderer = new MyRenderer();
return myRenderer;
if(column == (tblConnections.getColumnModel().getColumnIndex("Connection Name"))) {
TextWithIconCellRenderer renderer1 = new TextWithIconCellRenderer();
return renderer1;
return renderer;
public TableCellEditor getCellEditor(final int row, final int column) {
DefaultCellEditor defaultEditor;
if (column == (tblConnections.getColumnModel().getColumnIndex("Password"))) {
MyCellEditor editor = new MyCellEditor();
editor.addCellEditorListener(this);
editor.getPasswordField().addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) { }
public void focusLost(FocusEvent e) {
tblConnections.setValueAt(((JPasswordField) (e.getSource())).getPassword(), row, column);
tblConnections.getCellEditor().stopCellEditing();
return editor;
} else if (column == (tblConnections.getColumnModel().getColumnIndex("Userid"))) {
JTextField txtField = new JTextField();
defaultEditor = new DefaultCellEditor(txtField);
defaultEditor.addCellEditorListener(this);
txtField.addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) { }
public void focusLost(FocusEvent e) {
tblConnections.setValueAt(((JTextField) (e.getSource())).getText(), row, column);
tblConnections.getCellEditor().stopCellEditing();
return defaultEditor;
return null;
Thanks.

Similar Messages

  • How to get all the values in one column of a JTable

    How to get all the values in one column of a JTable as a Collection of String.
    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column.

    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column. You could always write a custom TableModel that stores the data in the format you want it. It would probably be about 50 lines of code. Or you could write a loop in 3 lines of code. I'll let you decide which approach you want to take.

  • How can I add custom right-click-menu to column headers in JTable?

    Can anyone point me to a topic on how to customize a popup menu for column headers in JTable? Specifically, I want to add things like "auto-size column" and "hide column".
    Thanks,
    Matt

    Right-click on your table.  Then go to Advanced->Runtime Shortcut Menu->Edit.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to create Hyperlink column in a JTable

    Can anyone help in creating a hyperlink column in a JTable.
    Thanks in advance,
    Sridhar.

    If the parent is an Applet it is very simple .
    catch the mouse click on columns and execute the following code
    String url = getValueAt(i,j);
    getAppletContext().showDocument(new
    URL(url ), "_blank");
    thatz all .
    if ur program is an application use this getRuntime.exec() and use parameters to rundll32.exe url and iexplore.exe in Windows platform,
    if u have still doubts plz get back to me
    Renjith K.V

  • How to fix the value of first column in the JTable in java swing for every

    Hi ,
    I have a swing page that have table panel in which there is a table of size 7x4 now when I click on the perticulat row then that row data will displayin the table like that the selected row become the second column in the new table and the fist column of this table will remain constant for all the entry but the second column update according to the roe which is selected .How it is possible .
    Thanks in Advace,
    anu

    One thing you can do is to prevent the user from editing that column and programatically supply the values of that column yourself.
    JTable table = new JTable() {
       public boolean isCellEditable(int row, int col) {
           if(col == 0) {
              return false;
           return super.isCellEditable(row, col);
    };This allows you to prevent the user from editing the column information so you can supply some sort of a default value for the column always
    ICE

  • Looking for component: flexible rows like columns in a JTable

    Hello,
    I need a swing component to display several rows which can be moved up and down, the height resized, interchanged with the mouse like the columns in a JTable. But there is no need for columns. I think there is no standard swing component.
    Any ideas, resource hints?
    Thanks, Ulrich

    One more piece of advice. It is not very easy to get "pre-written custom components". Most developers do things to meet their own needs and these may not be exactly what you are looking for. The best thing to do is to try to develop this yourself. It will give you loads of experience and in later programmes you may write, based on the experience you obtained from the "pain-staking" development process you'll know how to go round these problems quicker and may be able to help others also.
    So just start writing some stuff. You may end up finishing sooner than you think. And remember forum members are always ready to help with problems (accompanied by minimal code examples of the actual problem).
    ICE

  • Help for adjusting columns of a JTAble in a Table Model

    Hello community,
    In order to have a good display of by DataBase in a JTable, I've wrote some code to adjust columns in function of datas. Those datas are displayed with a TableModel ( which I've declared in a class JDBCAdapter ).
    When I start my application, I call adjustColumns(), and all is great but when I add information to my DB and display it, the columns of my JTable return to default width...
    So I want to incorporate my function adjustColumns in my TableModel, and I need help...
         void adjustColumns()
         // Ajuste les colonnes aux donnes pour que tout soit visible
         int nbRow,nbCol;
         nbRow = JTable1.getRowCount();
         nbCol = test.getColumnCount();
         for ( int i = 0; i < nbCol; i++ )
         com.sun.java.swing.table.TableColumn column = null;
         column = JTable1.getColumnModel().getColumn(i);
         int dataLength = 0;
         for ( int j = 0; j< nbRow; j++ )
         FontMetrics fm;
         int dataLengthTmp;
         String valueTable;
         fm = JTable1.getFontMetrics(JTable1.getFont());
         if ( test.getValueAt(j, i) == null )
         System.out.println("Valeur nulle...");
         dataLengthTmp = 0;
         else
         valueTable = test.getValueAt(j, i).toString();
         dataLengthTmp = fm.stringWidth(valueTable);
         System.out.println(valueTable + " = " + dataLengthTmp);
         if ( dataLengthTmp > dataLength )
         dataLength = dataLengthTmp;
         if ( dataLength != 0 )
    column.setWidth(dataLength + 5);
    else
    column.sizeWidthToFit();
    JTable1.setModel(test);
    JTable1.repaint();
    import java.util.Vector;
    import java.sql.*;
    import com.sun.java.swing.table.AbstractTableModel;
    import com.sun.java.swing.event.TableModelEvent;
    public class JDBCAdapter extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector rows = new Vector();
    ResultSetMetaData metaData;
    public JDBCAdapter(String url, String driverName,
    String user, String passwd) {
    try {
    Class.forName(driverName);
    System.out.println("Ouverture de la connexion a la base de donnee...");
    connection = DriverManager.getConnection(url, user, passwd);
    statement = connection.createStatement();
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public void executeQuery(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    resultSet = statement.executeQuery(query);
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
    newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex+" query = "+query);
    public void executeUpdate(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    statement.executeUpdate(query);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex+" query = "+query);
    public void close() throws SQLException {
    System.out.println("Fermeture de la connection a la base de donnee... Bye !");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // Implementation of the TableModel Interface
    // MetaData
    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return super.getColumnClass(column);
    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;
    case Types.BIT:
    return Boolean.class;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;
    case Types.BIGINT:
    return Long.class;
    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;
    case Types.DATE:
    return java.sql.Date.class;
    default:
    return Object.class;
    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    Thanks to help me.

    Hi,
    OK. I have read your code sample again. It looks like the JDBCAdapter class is reloading table data in the executeQuery method. Why not call adjustColumns at the end of this method after the new rows and columns are loaded? Perhaps it also should be called at the end of executeUpdate. Have you tried doing that?
    I would still set
    JTable1.setAutoCreateColumnsFromModel (false); to prevent Java from readjusting the size automatically at some other time.
    regards,
    Terry

  • How to set a JRadioButton as a column in a JTable

    Hello Friends,
    I need a help in JTable.
    I want to have a Radio button as a column of a JTable.(The Other Columns should be Strings).
    The heading of the Column which has the RadioButton is "Select" which means that I can select only one radiobutton at a time.
    Could you please give me a solution on this.
    I would appreciate if u give me the code for this, as it is very urgent.
    Thanks in Advance,
    Regards,
    Vijayakannan

    Hi,
    use a TableCellRenderer and CellEditor as described in http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Propably you need to track the selected button yourself, e.g. by using an int value representing the row selected.

  • Right Justify a column in a JTable

    Hello,
    I formatted a decimal number and want to put it into a column in a JTable. Unfortunately, the value is being left justified. How do I make the data for the column right justitified?

    Thank you both for your answers. I had looked in the tutorial, but could not find the area for justifications. I did have a table model with a getColumnClass too, but didnt realize that I didnt have to use the actual data type's class to render the justification.
    Looking back at the tutorial, I now find that ImageIcon is supposed to be used for centering, but this didnt work. It wiped out the data for the column I tried to use it on rather than justifying it left or right. Any ideas how to get centering to work?

  • Adding mouse listener to the column header of a column in a JTable

    Hi
    I want to add a mouse listener to the column header of the 3rd column in a JTable. I dont find any appropriate method to do this. The code I have written to do this is below. But on using this code, the mouselistener is invoked if I click on any column header. Can anyone please help me to fix this.
    table.getTableHeader().addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    /* some actions */
    }

          table.getTableHeader().addMouseListener(new MouseAdapter(){
               public void mousePressed(MouseEvent me) {
                   int tableColumn  =table.columnAtPoint(me.getPoint());//it returns the column index
            });

  • How to programmatically select a column in a JTable

    Hi,
    I'm writing a program which requires me to select a column in the JTable through code. The problem is that I could only find getSelectedColumn() function in JTable and no setSelectedColumn().
    Please let me know if there is any workaround for this.
    Regards,
    Derreck

    Hi,
    table.setColumnselectionInterval(index0,index1);
    The above line will suffice your requirement.
    Cheers,
    Gokul.

  • Setting the Size of a Column in a JTable

    Hi there,
    does anybody knows a way how to set the size of a specified column in a JTable without changinge the size of the other columns?
    thx anyway
    Errraddicator

    You've got to change the JTable's column resizing policy to prevent the other columns resizing:
    JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)Otherwise all the columns will be adjusted to fit into the width of the table - changing one column would have to result in at least one other column changing!
    Hope this helps.

  • How can I use a column header to select columns in a JTable?

    Hello,
    I've been working for ages on this, but I still can't come up with a suitable solution. What I want to be able to do is select a column header from a JTable, which in turn would select the corresponding column in my JTable. I cant seem to do this with a mouse listener, and I can't see how to toggle the buttons of the header either.
    Any help would be gratefully appreciated.
    Mike

    I have both row and columns selected depending on what you do in the JTable. Here's my code:
    where you init your JTable add:
    addressTable = new JTable(addressTableModel, addressTableColumnModel);
    JTableHeader th = addressTable.getTableHeader();
    th.addMouseListener(new tableHeaderMouseAdapter(addressTable));
    addressTable.getSelectionModel().addListSelectionListener(new selectionListener(addressTable));
    addressTable.setColumnSelectionAllowed(true);
    tableHeaderMouseAdapter looks like this (it should look familiar):
    private class tableMouseAdapter extends MouseAdapter
         private JTable tableView;
         public tableMouseAdapter(JTable newTableView)
              tableView = newTableView;
         public void mouseClicked(MouseEvent e)
              int selectedRow = tableView.getSelectedRow();
              if ((e.getClickCount() == 1) && (selectedRow != -1))
                   tableView.clearSelection();
                   tableView.setRowSelectionInterval(selectedRow, selectedRow);
                   tableView.setColumnSelectionInterval(0, tableView.getColumnModel().getColumnCount() - 1);
    selectionListener looks like this:
    private class selectionListener implements ListSelectionListener
         private JTable tableView;
         private boolean changingSelection;
         public selectionListener(JTable newTableView)
              tableView = newTableView;
              changingSelection = false;
         public void valueChanged(ListSelectionEvent e)
              if ((!changingSelection) && (tableView.getSelectedColumnCount() < tableView.getColumnCount()) && (tableView.getSelectedRowCount() < tableView.getRowCount()))
                   changingSelection = true;
                   int selectedRow = tableView.getSelectedRow();
                   if (selectedRow >= 0)
                        tableView.clearSelection();
                        tableView.setRowSelectionInterval(selectedRow, selectedRow);
                   tableView.setColumnSelectionInterval(0, tableView.getColumnModel().getColumnCount() - 1);
                   changingSelection = false;
    I'm sure there is a better way to do this, but it's the first thing I could get to work.
    disclamer:
    Use this code at your own risk. I make no claims about this code whatsoever.

  • ( im new to java) How do I increase number of columns in a JTable ?

    I am dooing a small calculating program in school and can't figure out how to change the amount of columns in a JTable, my programming skills sofar are extremely basic and therefore we are using the netbeans GUI to create our windows. The code generated by the GUI cannot be edited and I have tried to copy paste the code into Eclipse but it didn't work.
    I have a fair idea of where in the code you can preform the things I want but I need to do it in the grapical interface.
    any suggestions are very much appriciated.

    my programming skills sofar are extremely basic and therefore we are using the netbeans GUI to create our windows.Using and IDE doesn't not make it easier. As you've found out it only makes it harder since you can't edit the code and take full control.
    Read the Swing tutorial, it contains plenty of example for building GUI applications:
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html
    I don't really understand your question, because if you create the table correctly, then then is no need to increase the number of columns. However, the table does support an addColumn(....) method.

  • Simulating one column using two columns in a JTable

    What I need to do is "join" the two first columns of a JTable...
    What do I mean by saying "join" ?
    I want to make dissapear the right border of the first column, and the same thing for the left border of the second column, also do both things for the column headers of that two columns.
    All that to simulate having one column when there's actually two differents columns.
    How can i do that ? Thanks !

    Make a TableModel that filters your original table model.
    See JTable.setModel.
    public class MergedColumnsTableModel extends javax.swing.table.AbstractTableModel
         javax.swing.TableModel model;
         int[] columnSpans;
          * Assume for simplicity that model does not change (no columns inserted/deleted).
         public MergedColumnsTableModel(javax.swing.TableModel model) {
              this.model = model;
              columnSpans = new int[model.getColumnCount()];
              for (int columnIndex = 0; columnIndex < columnSpans.length; ++columnIndex) {
                   columnSpans[columnIndex] = 1;
         public void merge2(int columnIndex) {
              int leftSpan = columnSpans[columnIndex];
              int rightSpan = columnSpans[columnIndex + leftSpan];
              columnSpans[columnIndex + leftSpan] = 0;
              columnSpans[columnIndex] += rightSpan;
         public int getRowCount() {
              return model.getRowCount();
         public int getColumnCount() {
              int n = 0;
              for (int i = 0; i < columnSpans.length; ++i) {
                   if (columnSpans[i] != 0) {
                        ++n;
              return n;
         public Object getValueAt(int row, int column) {
              int n = 0;
              for (int i = 0; i < columnSpans.length; ++i) {
                   if (columnSpans[i] != 0) {
                        if (n == column) { // We are at the column
                             return model.getValueAt(row, i);
                        ++n;
    }

Maybe you are looking for