jtable interview questions
Top jtable frequently asked interview questions
I want to display a JTable that display the data from a DataBase table as it is.
Up till now, I have used JTable that displays data from Object [ ][ ].
I know one way to display the data is to first convert the database table into Object [ ][ ] but Is there any other which is easy yet more powerful and flexible.
Source: (StackOverflow)
I am putting a JTable into a JScrollPane
But When I set JTable Auto Resizeable, then it won't have horizontal scroll bar.
if I set AUTO_RESIZE_OFF, then the Jtable won't fill the width of its container when the column width is not big enough.
So how can I do this:
- when the table is not wide enough, expand to fill its container width
- when the table is wide enough, make it scrollable.
Thanks
Source: (StackOverflow)
How to make a JTable
non-editable? I don't want my users to be able to edit the values in cells by double-clicking them.
Any help would be greatly appreciated.
Thanks.
Source: (StackOverflow)
When a user clicks a cell on a JTable
, how do I figure out the row and column of the clicked cell? How would I show this information in a JLabel
?
Source: (StackOverflow)
I have a JTable with a custom cell renderer. The cell is a JPanel that contains a JTextField and a JButton. The JTextField contains an integer, and when the user clicks on the JButton the integer should be increased.
The problem is that the JButton can't be clicked when I have it in a JTable cell. How can I make it click-able?

Here is my test code:
public class ActiveTable extends JFrame {
public ActiveTable() {
RecordModel model = new RecordModel();
model.addRecord(new Record());
JTable table = new JTable(model);
EditorAndRenderer editorAndRenderer = new EditorAndRenderer();
table.setDefaultRenderer(Object.class, editorAndRenderer);
table.setDefaultEditor(Object.class, editorAndRenderer);
table.setRowHeight(38);
add(new JScrollPane(table));
setPreferredSize(new Dimension(600, 400));
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Active Table");
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ActiveTable();
}
});
}
class RecordModel extends AbstractTableModel {
private final List<Record> records = new ArrayList<Record>();
@Override
public int getColumnCount() {
return 1;
}
@Override
public int getRowCount() {
return records.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return records.get(rowIndex);
}
public void addRecord(Record r) {
records.add(r);
fireTableRowsInserted(records.size()-1, records.size()-1);
}
}
class Record {
private int count = 1;
public int getCount() { return count; }
public void increase() { count = count + 1; }
}
class CellPanel extends JPanel {
private Record record;
private final JTextField field = new JTextField(8);
private final Action increaseAction = new AbstractAction("+") {
public void actionPerformed(ActionEvent e) {
record.increase();
field.setText(record.getCount()+"");
JTable table = (JTable) SwingUtilities.getAncestorOfClass(JTable.class, (Component) e.getSource());
table.getCellEditor().stopCellEditing();
}
};
private final JButton button = new JButton(increaseAction);
public CellPanel() {
add(field);
add(button);
}
public void setRecord(Record r) {
record = r;
field.setText(record.getCount()+"");
}
public Record getRecord() {
return record;
}
}
class EditorAndRenderer extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
private final CellPanel renderer = new CellPanel();
private final CellPanel editor = new CellPanel();
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
renderer.setRecord((Record) value);
return renderer;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
editor.setRecord((Record) value);
return editor;
}
@Override
public Object getCellEditorValue() {
return editor.getRecord();
}
@Override
public boolean isCellEditable(EventObject ev) {
return true;
}
@Override
public boolean shouldSelectCell(EventObject ev) {
return false;
}
}
}
Source: (StackOverflow)
What's the difference between JTable.getModel().getColumnName()
and JTable.getColumnModel().getColumn(index).getHeaderValue()
? The two don't seem to share any data. My guess is that TableModel.getColumnName()
indicates the textual representation of a column while TableColumn.getHeaderValue()
and TableColumn.getHeaderRenderer()
determine what the column looks like (it doesn't need to be plain text).
What guarantees that the two are kept in sync? What happens if the two conflict?
Source: (StackOverflow)
Basically, I have a JTable containing columns with right-aligned cells but left-aligned headers which looks really bad. I would like to right-align the headers of these columns without altering the "Look and Feel" of the headers.
Thanks
Source: (StackOverflow)
I have made one swing GUI which have JTable with some rows and Columns.How should I add a button to row in a JTable ?
Source: (StackOverflow)
I'm not aware of how to align the values of cells in JTable.
For Ex,The Jtable shows,
Name Salary
Mr.X 100000.50
XXXX 234.34
YYYy 1205.50
I want to align the "Salaries" in the following format.
Name Salary
Mr.X 100000.50
XXXX 234.34
YYYy 1205.50
How to align as above the JTable
Source: (StackOverflow)
Here is the screenshot of what I want to do :

What's happening there is the JButton shows correctly but nothing happens when I click on it.
After some search, I've found that the Object
returned by table.getValueAt()
is a String instead of a JButton...
Here is the code :
tblResult = new JTable(data,cols) {
public TableCellRenderer getCellRenderer( int row, int column ) {
return new ClientsTableRenderer();
}
};
I use this for populating at run-time the JTable :
(tblResult
is now Clients.rblResult
)
SwingUtilities.invokeLater( new Runnable() {
public void run() {
DefaultTableModel aModel = new DefaultTableModel() {
//setting the jtable read only
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
String[] cols = {"N°","Société", "TVA", "CP", "Ville", ""};
aModel.setColumnIdentifiers(cols);
Object[] temp = new Object[6];
for(int i=0;i<result.length;i++) {
temp[0] = result[i].custNumber;
temp[1] = result[i].name;
temp[2] = result[i].tva;
temp[3] = result[i].cp;
temp[4] = result[i].city;
temp[5] = "Consulter";
aModel.addRow(temp);
}
Clients.tblResult.setModel(aModel);
Clients.tblResult.addMouseListener(new JTableButtonMouseListener(Clients.tblResult));
}}
);
Here the ClientsTableRenderer
class
public class ClientsTableRenderer extends JPanel implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent( final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setBackground(Color.WHITE);
if(column < 5) {
JLabel label = new JLabel(value.toString());
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,0,9));
panel.setBackground(Color.WHITE);
panel.add(label);
this.add( panel);
} else {
JButton button = new JButton(value.toString());
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Clicked !");
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,0,3));
panel.setBackground(Color.WHITE);
panel.add(button);
this.add(panel);
}
return this;
}
}
And finaly, the JTableButtonMouseListener() :
public class JTableButtonMouseListener extends MouseAdapter {
private final JTable table;
public JTableButtonMouseListener(JTable table) {
this.table = table;
}
@Override public void mouseClicked(MouseEvent e) {
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
System.out.println("Col :"+column + "row:"+row);
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
System.out.println("Value :"+value.getClass().getName());
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
I'm kindly new to Java, help would be very much appreciated :)
Thanks in advance !
Source: (StackOverflow)
I am curious as to how to call valueChanged
overridden method only if a row in JTable
has been double clicked. For now the below code snippet achieves one click action or event arrow key to navigate through a list of people and would adjust JLabel
accordingly. What I'm trying to do is something similar just like I did for one click, but this time IF and ONLY IF a row has been double clicked dto
would change else nothing happens. How do I do this :(
class ListDataUI {
public void addListSelectionListener(ListSelectionListener listSelectionListener) {
summaryTable.getSelectionModel().addListSelectionListener(listSelectionListener);
public T getSelectedDTO() {
final int selectedRowIndex = summaryTable.getSelectedRow();
if (selectedRowIndex != -1) {
return data.get(summaryTable.convertRowIndexToModel(selectedRowIndex));
} else {
return null;
}
}
}
}
class MainMenu extends javax.swing.JFrame {
private void initListeners() {
searchTable.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
AcademicDTO dto = (AcademicDTO) searchTable.getSelectedDTO();
acImgLabel.setIcon(new ImageIcon());
label_name.setText(dto.getTitle() + " " + dto.getForename() + " " + dto.getSurname());
label_role.setText("Role: " + dto.getRole());
label_phone.setText("Phone: " + dto.getPhone());
label_room.setText("Room: " + dto.getRoom());
label_hours.setText("Hours: " + dto.getHours());
label_mobile.setText("Mobile: " + dto.getMobile());
if (dto.getImage() != null) {
acImgLabel.setIcon(new ImageIcon(dto.getImage()));
}
}
}
});
}
}
private void initListeners() {
contactTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ContactDTO dto = (ContactDTO) contactTable.getSelectedDTO();
if (e.getClickCount() == 2) {
System.out.println(dto.getForename());
} else {
}
}
});
}
not sure of the rest above...
Source: (StackOverflow)
The high level: I have a JTable that the user can use to edit data.
Whenever the user presses Enter or Tab to finish editing, the data is saved (I'm asusming that "saved" really means "the TableModel's setValueAt() method is called".)
If the user leaves the cell in any other way after making an edit, the new data is not saved and the value stays the way it was. So, for example, if the user changes a value and then clicks on some other widget on the screen, the change doesn't "stick."
I believe that this is the default behavior for a JTable full of Strings, yes?
For a variety of reasons, the desired behavior is for the cell to save any and all edits whenever the user leaves the cell. What's the best/right way to get Swing to do this?
Source: (StackOverflow)
I googled the whole day and no luck. I call getnPrintAllData()
method after pressing OK button. So the code is:
public class DatabaseSQLiteConnection {
Connection conn = null;
PreparedStatement statement = null;
ResultSet res = null;
public DatabaseSQLiteConnection(){
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.sqlite");
statement = conn.prepareStatement("SELECT * from product_info;");
}
catch(Exception e){
e.printStackTrace();
}
}
public void getnPrintAllData(){
String name, supplier, id;
DefaultTableModel dtm = new DefaultTableModel();
Window gui = new Window(); //My JPanel class
try{
res = statement.executeQuery();
testResultSet(res);
ResultSetMetaData meta = res.getMetaData();
int numberOfColumns = meta.getColumnCount();
while (res.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = res.getObject(i+1);
}
dtm.addRow(rowData);
}
gui.jTable1.setModel(dtm);
dtm.fireTableDataChanged();
//////////////////////////
}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
finally{
try{
res.close();
statement.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void testResultSet(ResultSet res){
try{
while(res.next()){
System.out.println("Product ID: "+ res.getInt("product_id"));
System.out.println("Product name: "+ res.getString("product_name"));
System.out.println("Supplier: "+ res.getString("supplier"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
My testResultSet()
method is working properly.
Now, how to change my code so that it works, or what is the most simple code to make DefaultTableModel
from ResultSet
?
Thanks in advance.
Edit: I am reciving java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state
error.
Source: (StackOverflow)
I'm using a second JTable in the Viewport of a JScrollPane to build a RowHeader for a main table.
DragAndDrop on the main table is disabled. On the rowheader table DnD is enabled.
If a Drag on the rowheader is started by the user, I want to extend the painted rowheader dropline (the black line in the image) over the main table (like the green line in the image).

Does anybody have an advice for me?
Here's the SSCCE:
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.DropMode;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
public class DNDLinePainterExampleMain extends JFrame {
public DNDLinePainterExampleMain() {
JTable mainTable = new JTable(4, 3);
mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTable rowTable = new RowHeaderTable(mainTable);
rowTable.setAutoscrolls(true);
rowTable.setDragEnabled(true);
rowTable.setTransferHandler(new RowHeaderTransferHandler());
rowTable.setDropMode(DropMode.INSERT_ROWS);
JScrollPane scrollPane = new JScrollPane(mainTable);
scrollPane.setRowHeaderView(rowTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER,
rowTable.getTableHeader());
this.add(scrollPane);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new DNDLinePainterExampleMain();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
});
}
/*
* Use a JTable as a renderer for row numbers of a given main table. This
* table must be added to the row header of the scrollpane that contains the
* main table. from:
* http://tips4java.wordpress.com/2008/11/18/row-number-table/
*/
public class RowHeaderTable extends JTable implements ChangeListener,
PropertyChangeListener {
private final JTable table;
public RowHeaderTable(JTable table) {
this.table = table;
table.addPropertyChangeListener(this);
setFocusable(false);
setAutoCreateColumnsFromModel(false);
updateRowHeight();
updateModel();
updateSelectionModel();
TableColumn column = new TableColumn();
column.setHeaderValue("");
addColumn(column);
column.setCellRenderer(new RowNumberRenderer());
getColumnModel().getColumn(0).setPreferredWidth(50);
setPreferredScrollableViewportSize(getPreferredSize());
getTableHeader().setReorderingAllowed(false);
}
@Override
public void addNotify() {
super.addNotify();
Component c = getParent();
// Keep scrolling of the row table in sync with the main table.
if (c instanceof JViewport) {
JViewport viewport = (JViewport) c;
viewport.addChangeListener(this);
}
}
/*
* Delegate method to main table
*/
@Override
public int getRowCount() {
return table.getRowCount();
}
@Override
public int getRowHeight(int row) {
return table.getRowHeight(row);
}
/*
* This table does not use any data from the main TableModel, so just return
* a value based on the row parameter.
*/
@Override
public Object getValueAt(int row, int column) {
return Integer.toString(row + 1);
}
/*
* Don't edit data in the main TableModel by mistake
*/
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
// implements ChangeListener
@Override
public void stateChanged(ChangeEvent e) {
// Keep the scrolling of the row table in sync with main table
JViewport viewport = (JViewport) e.getSource();
JScrollPane scrollPane = (JScrollPane) viewport.getParent();
scrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y);
}
// implements PropertyChangeListener
@Override
public void propertyChange(PropertyChangeEvent e) {
// Keep the row table in sync with the main table
if ("rowHeight".equals(e.getPropertyName()))
updateRowHeight();
if ("selectionModel".equals(e.getPropertyName()))
updateSelectionModel();
if ("model".equals(e.getPropertyName()))
updateModel();
}
private void updateRowHeight() {
setRowHeight(table.getRowHeight());
}
private void updateModel() {
setModel(table.getModel());
}
private void updateSelectionModel() {
setSelectionModel(table.getSelectionModel());
}
/*
* Borrow the renderer from JDK1.4.2 table header
*/
private class RowNumberRenderer extends DefaultTableCellRenderer {
public RowNumberRenderer() {
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
}
if (isSelected) {
setFont(getFont().deriveFont(Font.BOLD));
}
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
}
}//class RowNumberRenderer
}//class RowHeaderTable
public class RowHeaderTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(c.getName());
}
@Override
public boolean canImport(TransferSupport supp) {
return true;
}
}//class RowHeaderTransferHandler
}//class DNDLinePainterExampleMain
Source: (StackOverflow)