JTable readonly / single selection
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.util.UUID;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class JTableFrame extends JFrame {
public JTableFrame() {
// TODO Auto-generated constructor stub
getContentPane().setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model) {
@Override
public boolean isCellEditable(int row, int column) {
// set table column uneditable
return false;
}
};
// set table single row selectable
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// set column move disabled
table.getTableHeader().setReorderingAllowed(false);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
// row selection changed
if (e.getValueIsAdjusting()) {
System.out.println(e.getFirstIndex());
}
}
});
model.addColumn("No.");
table.getColumnModel().getColumn(0).setMaxWidth(100);
model.addColumn("UUID");
for (int i = 1; i < 51; i++) {
model.addRow(new Object[] { i, UUID.randomUUID() });
}
JScrollPane spane = new JScrollPane();
spane.setViewportView(table);
getContentPane().add(spane, BorderLayout.CENTER);
// if content value is changed, try invoke :
// table.revalidate();
// spane.revalidate();
setSize(400, 300);
Dimension sc = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(new Point((sc.width - getWidth()) / 2, (sc.height - getHeight()) / 2));
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new JTableFrame();
}
}