JavaSwing add multiple JTable to JFrame - java

I am working on java swing application.I have to browse multiple CSV data files and display them into JFrame using JTable.I am trying to add multiple(non static) JTable into JFrame.All (N) JTable i want to include inside a JSrollPane.At this moment i can display only 1 table to JScrollPane.
Thanks in advance!
if (e.getSource() == jbtreadbrowsefile) {
try {
for(int k=0;k<file_locations.length;k++) {
String currentLocation=file_locations[k];
inputList = new ArrayList();
File inputF = new File(currentLocation);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
inputList = br.lines().collect(Collectors.toList());
br.close();
int count = inputList.size();
if(count>0)
{
data = new String[count - 1][8];
for (int i = 0; i < count - 1; i++) {
String[] arrOfStr = inputList.get(i + 1).toString().split(",");
String test1= arrOfStr[0];
String test2= arrOfStr[1];
String test3= arrOfStr[2];
String test4 = arrOfStr[3];
String test5= arrOfStr[4];
String test6= arrOfStr[5];
String test7= arrOfStr[6];
data[i][0] = "" + (i + 1);
data[i][1] = test1;
data[i][2] = test2;
data[i][3] = test3;
data[i][4] = test4;
data[i][5] = test5;
data[i][6] = test6;
data[i][7] = test7;
}
j = new JTable(data, columnNames);
TableColumnModel tcm = j.getColumnModel();
tcm.getColumn(0).setPreferredWidth(40);
tcm.getColumn(1).setPreferredWidth(220);
tcm.getColumn(2).setPreferredWidth(120);
tcm.getColumn(3).setPreferredWidth(80);
tcm.getColumn(4).setPreferredWidth(80);
tcm.getColumn(5).setPreferredWidth(80);
tcm.getColumn(6).setPreferredWidth(80);
tcm.getColumn(7).setPreferredWidth(80);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
j.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int i = 0; i < j.getRowCount(); i++) {
j.setRowHeight(i, 20);
}
j.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 15));
j.getTableHeader().setReorderingAllowed(false);
j.repaint();
JScrollPane sp = new JScrollPane(j);
sp.setBounds(10, 200, 780, 440);
add(sp);
}
else
{
JOptionPane.showMessageDialog(this,"No Data Found in the File");
}
}

JScrollPane sp = new JScrollPane(j);
sp.setBounds(10, 200, 780, 440);
add(sp);
Don't use setBounds(). It is the job of the layout manager to determine the size/location of a component.
At this moment i can display only 1 table to JScrollPane.
Correct. A JScrollPane is designed to display a single JTable. The header of the JTable will be displayed at the header view of the scroll pane and the table will be displayed in the center of the scroll pane. You may then also see scrollbars in the scroll pane depending on the data in the table.
If you want to "merge" data from multiple files into the same table, then you need to update the TableModel with the data from each file instead of creating a new table each time.
You can dynamically add data to the model by using the addRow(…) method of the DefaultTableModel.

For displaying each JTable into JFrame,i added all JTable into a JPanel and added this JPanel into JScrollPane.After displaying each JTable the problem was that we can not display each JTable header.I added to another JPanel each JTable header and it's shows up.
if (e.getSource() == jbtreadbrowsefile) {
GridLayout grid = new GridLayout(0, 1, 30, 20);
jpaneltable=new JPanel(grid);
try {
for(int k=0;k<file_locations.length;k++) {
String currentLocation=file_locations[k];
inputList = new ArrayList();
File inputF = new File(currentLocation);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
inputList = br.lines().collect(Collectors.toList());
br.close();
int count = inputList.size();
if(count>0)
{
data = new String[count - 1][8];
for (int i = 0; i < count - 1; i++) {
String[] arrOfStr = inputList.get(i + 1).toString().split(",");
String test1= arrOfStr[0];
String test2= arrOfStr[1];
String test3= arrOfStr[2];
String test4= arrOfStr[3];
String test5= arrOfStr[4];
String test6= arrOfStr[5];
String test7= arrOfStr[6];
data[i][0] = "" + (i + 1);
data[i][1] = test1;
data[i][2] = test2;
data[i][3] = test3;
data[i][4] = test4;
data[i][5] = test5;
data[i][6] = test6;
data[i][7] = test7;
}
j = new JTable(data, columnNames);
TableColumnModel tcm = j.getColumnModel();
tcm.getColumn(0).setPreferredWidth(40);
tcm.getColumn(1).setPreferredWidth(220);
tcm.getColumn(2).setPreferredWidth(120);
tcm.getColumn(3).setPreferredWidth(80);
tcm.getColumn(4).setPreferredWidth(80);
tcm.getColumn(5).setPreferredWidth(80);
tcm.getColumn(6).setPreferredWidth(80);
tcm.getColumn(7).setPreferredWidth(80);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
j.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int i = 0; i < j.getRowCount(); i++) {
j.setRowHeight(i, 20);
}
j.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 15));
j.getTableHeader().setReorderingAllowed(false);
j.getTableHeader().setPreferredSize(new Dimension(0,HEADER_HEIGHT));
j.repaint();
jpaneltable.add(j.getTableHeader(),BorderLayout.NORTH);
jpaneltable.add(j, BorderLayout.CENTER);
}
else
{
JOptionPane.showMessageDialog(this,"No Data Found in the File");
}
}
JScrollPane sp = new JScrollPane(jpaneltable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp.setBounds(10, 200, 780, 440);
add(sp);
}

Related

FormLayout displays everything in one cell

I am trying to create a grid using FormLayout but it seems it displays every new element above the others. I guess the problem is with CellContraints and FormLayout. Note that CityPanel extends Panel.
public class MapPanel extends JPanel {
public MapPanel() {
drawMap(5, 5);
}
private void drawMap(columns, rows) {
ColumnSpec[] columnSpec = new ColumnSpec[columns];
for(int i = 0; i < columns; i++)
columnSpec[i] = FormSpecs.DEFAULT_COLSPEC;
RowSpec[] rowSpec = new RowSpec[rows];
for(int i = 0; i < rows; i++)
rowSpec[i] = FormSpecs.DEFAULT_ROWSPEC;
FormLayout layout = new FormLayout(columnSpec, rowSpec);
this.setLayout(layout);
CellConstraints cc = new CellConstraints(columns, rows);
//draw the grid
for (City city : gameMap.getCities().values()) {
Dimension dimension = new Dimension(100, 100);
CityPanel cityPanel = new CityPanel(city, dimension);
//this code put the cityPanel in a cell. It's confirmed by the println()
this.add(cityPanel, cc.xy(mapGrid.getColumn(city), mapGrid.getRow(city), CellConstraints.CENTER, CellConstraints.CENTER));
System.out.println(city.getName() + " -> (" + mapGrid.getColumn(city) + "," + mapGrid.getRow(city) + ")" );
}
}
}

Update Jtable content in the gui without reinitating the method to redraw the table?

The method I've provided here is supposed to create a new table, perform the recall, and then update the table with the message that is received by the person contacted. It all works fine, except for the received message. I can even click the button again that initiates the recall and it then updates the table to include the message that was received, but nothing I add to the code seems to update the table automatically. As you can see here I've even tried completely redrawing the table and that doesn't work either. The only thing that actually makes the message show up is by re initiating the recall.
I've tried re validate and repaint but those don't seem to work.
public void doRecall() throws Exception {
newFrame = new JFrame("Recall Initiated Awaiting Replies");
newFrame.setSize(600, 300);
newFrame.setIconImage(img);
Member con = new Member();
String columnNames[] = { "First Name", "Last Name", "Phone No.",
"Response" };
Object[][] data = new Object[v.size()][4];
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
data[j][0] = con.getFName();
data[j][1] = con.getLName();
data[j][2] = con.getPhoneNo();
data[j][3] = con.getResponse();
k++;
}
k = 0;
abtable = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(abtable);
abtable.setPreferredScrollableViewportSize(new Dimension(500, 370));
JPanel pane = new JPanel();
JLabel label = new JLabel("Members Currently In The Recall Roster");
pane.add(label);
newFrame.getContentPane().add(pane, BorderLayout.SOUTH);
newFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
newFrame.setLocation(screenWidth / 4, screenHeight / 4);
newFrame.setVisible(true);
String customMessage = getMessage();
k = 0;
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
try {
String toPhoneNumber = con.getPhoneNo();
customMessage = customMessage.replaceAll("\\s+", "+");
System.out.println(customMessage);
String requestUrl = ("http://cloud.fowiz.com/api/message_http_api.php?username=&phonenumber=+"
+ toPhoneNumber + "&message=" + customMessage + "&passcode=");
URL url = new URL(requestUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
System.out.println(uc.getResponseMessage());
String reply = uc.getResponseMessage();
if (reply.equalsIgnoreCase("ok")) {
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
k++;
}
k = 0;
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
boolean phoneCheck = false;
while (phoneCheck != true) {
for (int j1 = 0; j1 < v.size(); j1++) {
con = (Member) v.elementAt(k);
mR2 = new MailReader();
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "";// change
// accordingly
String password = "";// change accordingly
MailReader.check(host, mailStoreType, username, password);
if (MailReader.searchForPhone(con.getPhoneNo()) == true) {
con.setResponse(MailReader.getReply(con.getPhoneNo()));
newFrame.addNotify();
System.out.println("IT WORKED");
newFrame.remove(scrollPane);
JTable abctable = new JTable(data, columnNames);
JScrollPane scrollPane2 = new JScrollPane(abctable);
newFrame.getContentPane().add(scrollPane2,
BorderLayout.CENTER);
abtable.repaint();
newFrame.repaint();
newFrame.revalidate();
phoneCheck = true;
}
}
}
}
}
When interacting with the data of the table, we want to use the TableModel of the table. The TableModel is what actually holds the data, and allows us to easily manipulate the data in the table.
You can either implement your own AbstractTableModel or use the DefaultTableModel, which already provides an implementation, that comes equipped with method for adding row and other goodies.
With DefaultTableModel, you can simply call the method addRow(Object[]) or addRow(Vector) to add a row dynamically at runtime. For example:
String columnNames[] = {
"First Name", "Last Name", "Phone No.", "Response" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0):
JTable table = new JTable(model);
...
// dynamically add a row
Object[] row = { data1, data2, data2, data4 };
model.addRow(row);
The DefaultTableModel implementation will fire the necessary updates to call for a repainting of the table.
See the DefaultTableModel API for other useful methods and constructors. Add see How to Use Tables for general information on using tables.

Problems on .JAR file with JTable and DefaultTableModel

i'm developing a desktop app. When i execute my .jar file on another computers, the jframe where i load data into a datatable is not workign correctly. The jre is the same on both computers. The jar works fine on my computer.
Here is the code:
public int cargarClaseEnVentanaResultados(ConjuntoResultados conjunto, ControladorVentanaResultados cont){
ArrayList<JPanel> jpArray= new ArrayList<>();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
String tipoExperimento = new String();
int contadorVariables = 0;
if (!conjunto.getConjuntoResultados().isEmpty()){
for (int i=0;i<conjunto.getConjuntoResultados().size();i++){
JTable jtable = new JTable(){
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
jtable.setRowSelectionAllowed(true);
jtable.setColumnSelectionAllowed(true);
jtable.setCellSelectionEnabled(true);
JPanel jpanel = new JPanel();
jpanel.setLayout(new GridBagLayout());
String[] columnNames ={"Variable","Valor"};
Object[][] data={};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
String nombreConjunto = conjunto.getConjuntoResultados().get(i).getNombreResultado();contadorVariables++;
jpanel.setName(nombreConjunto);
for (int j=0;j<conjunto.getConjuntoResultados().get(i).getResultados().size();j++){
Object[] o = new Object[2];
String nombreVar = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getNombre().replace(nombreConjunto+"_", "");
o[0] = nombreVar;
if (conjunto.getConjuntoResultados().get(i).getResultados().get(j).getCadena()!=null){
o[1] = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getCadena();
}else if (conjunto.getConjuntoResultados().get(i).getResultados().get(j).getDoble()!=null){
o[1] = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getDoble();
}else if (conjunto.getConjuntoResultados().get(i).getResultados().get(j).getEntero()!=null){
o[1] = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getEntero();
}
model.addRow(o);
}
jtable.setModel(model);
jtable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
JScrollPane tableContainer = new JScrollPane(jtable);
jpanel.setPreferredSize(new Dimension(cont.getVentanaResultados().getjTabbedPane2().getWidth()-50,contadorVariables*altoVentana));
jpanel.add(tableContainer, c);
jpArray.add(jpanel);
}
for (int k=0;k<jpArray.size();k++){
aniadirScrollpane(jpArray.get(k), tipoExperimento, cont);
}
this.getVentanaResultados().getjTabbedPane2().getSelectedIndex();
}
return contadorVariables;
}
The only reason i could imagine was the java jre but it's the same. Is there any reason the table wont load? It only shows the headers and it's only loading the last tab.
Thanks!

Strings not being, correctly, written to JTextField/Area on selection of row in JList

I'm using a vector to store the information displayed in the JList and I want to use the index of the selected index to copy the data of that row into the JTextField and JTextArea. I am having some issues where the selected item isn't be shown in the JTextField/Area but instead showing the data of a previous selected index. Every second index has an issue of showing the wrong data, 2, 4, 6, 8, 10 and then 11. Each of them will only show the right data if you select first when the program has just been executed. The print lines that I have added to the ListSelectionEvent listener shows the correct data of the selected index but it doesn't correctly copy it into the JTextArea/JTextField.
Selected right after the program was executed.
I selected a few other indices then tried to select it again
code:
public class EditFlashcardGui implements ListSelectionListener {
private JFrame frame;
private JPanel listPanel;
private Vector<Vector> flashcardMasterVector = new Vector<Vector>();
private JList list;
private JPanel tablePanel, dataPanel, textFieldPanel;
private JButton submitButton, cancelButton;
private JTextField frontTextField;
private JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JLabel frontTextLabel, reverseTextLabel;
Vector<Vector> masterVector = new Vector<Vector>();
public EditFlashcardGui() {
frame = new JFrame("Edit / Delete Flashcards");
frame.setSize(500, 200);
Container con = frame.getContentPane();
con.setLayout(new BorderLayout());
listPanel = new JPanel(new BorderLayout());
Vector<String> columnNames = new Vector<String>();
columnNames.add("id");
columnNames.add("front text");
columnNames.add("reverse text");
list = new JList(populateList());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
Font font1 = new Font("SansSerif", Font.BOLD, 20);
list.setFont(font1);
tablePanel = new JPanel();
tablePanel.add(list);
JScrollPane scrollPane = new JScrollPane(list);
con.add(scrollPane, BorderLayout.NORTH);
// south panel
gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
textFieldPanel = new JPanel(gridBagLayout);
// cancelButton = new JButton("Cancel");
// dataPanel.add(cancelButton, BorderLayout.SOUTH);
frontTextLabel = new JLabel("Front Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(frontTextLabel, constraints);
textFieldPanel.add(frontTextLabel);
frontTextField = new JTextField();
frontTextField.setColumns(30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 1;
gridBagLayout.setConstraints(frontTextField, constraints);
textFieldPanel.add(frontTextField);
reverseTextLabel = new JLabel("Reverse Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 2;
gridBagLayout.setConstraints(reverseTextLabel, constraints);
textFieldPanel.add(reverseTextLabel);
reverseTextArea = new JTextArea(3, 30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 3;
gridBagLayout.setConstraints(reverseTextArea, constraints);
textFieldPanel.add(reverseTextArea);
submitButton = new JButton("Submit");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 4;
gridBagLayout.setConstraints(submitButton, constraints);
textFieldPanel.add(submitButton);
con.add(textFieldPanel, BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public Vector<Vector> populateList() {
//flashcardMasterVector = flashcardDB.getList();
//Vector<String> flashcardVector = new Vector<String>();
Integer temp = 0;
for(int i = 0; i <= 20; i++) {
Vector<String> flashcardVector = new Vector<String>();
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
masterVector.add(i, flashcardVector);
temp++;
}
return masterVector;
}
public static void main(String[] args) {
EditFlashcardGui gui = new EditFlashcardGui();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (! e.getValueIsAdjusting())
{
System.out.print("id : " );
System.out.println(masterVector.get(list.getSelectedIndex()).get(0));
System.out.print("front text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(1));
frontTextField.setText(masterVector.get(e.getFirstIndex())
.get(1).toString());
System.out.print("reverse text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(2));
reverseTextArea.setText(masterVector.get(e.getFirstIndex())
.get(2).toString());
}
}
}
have to read Oracles tutorial about How to Use JList
you can't put Vector<Vector> to the JList directly,
put value and to use XxxListModel only, but in this case have to create crazy workaround for AbstractListModel, use simple array instead
JList is based on one dimensional array have to use Vector<Object (or String or Double...)>
don't complicate simple things put this array to the JTable (to the XxxTableModel), remove all synchronizations columns, remove JTableHeader if required, then output to the GUI looks like as JList
JTable.removeColumn remove only column from view, all data are still presented and stored into XxxTableModel without any changes
then selected (have to test for -1 == none of row is selected) row (have to convertViewToModel in the case that JTable is sorted or filtered) returns all required data from XxxTableModel
Use list.getSelectedIndex() instead of e.getFirstIndex() method.
Code :
frontTextField.setText( masterVector.get(list.getSelectedIndex() ).get(1).toString() );
reverseTextArea.setText(masterVector.get( list.getSelectedIndex()).get(2).toString() );
Clean Code:
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
Vector masterVec = masterVector.get( list.getSelectedIndex() );
System.out.print("id : ");
System.out.println(masterVec.get(0));
System.out.print("front text : ");
System.out.println(masterVec.get(1));
System.out.print("reverse text : ");
System.out.println(masterVec.get(2));
frontTextField.setText(masterVec.get(1).toString());
reverseTextArea.setText(masterVec.get(2).toString());;
}
}

Scroll a JScrollPane to a specific row on a JTable [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JTable Scrolling to a specified row index
I have a JTable and I programmatically need to select a row by using this code:
myTable.setRowSelectionInterval(i, j);
(where i and j are valid row and column numbers respectively).
The problem is, when you jump to a row, the JScrollPane does not move.
In this case, the table is quite long, and often the "selected row" is not visible on the screen, so the user has to stay scrolling up/down manually to find it. I would like to know how I can make the JScrollPane automatically jump to the specific location of the row.
Edit: Found this one liner which can do it:
table.scrollRectToVisible(table.getCellRect(row,0, true));
just extends post by #Eng.Fouad +1, no works as I exactly expected (with kind help by StanislavL from another Java Swing forum)
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 200));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 200));
sp2.setViewportView(jTable2);
final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 200));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
TableSelectionGood tableSelection = new TableSelectionGood();
}
}
I used this in my old project:
public static void scrollToVisible(JTable table, int rowIndex, int vColIndex)
{
if (!(table.getParent() instanceof JViewport)) return;
JViewport viewport = (JViewport)table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x-pt.x, rect.y-pt.y);
viewport.scrollRectToVisible(rect);
}
Reference: http://www.exampledepot.com/egs/javax.swing.table/Vis.html

Categories

Resources