Solved

getting a object returned from a row selection on a JTable

Posted on 2011-09-21
11
215 Views
Last Modified: 2012-05-12
I've built a jTable and added records to it from an custom object that i've built which all seems to work fine.

Here is the thing i want to show some values in the table not all of them, but when the user selects the row they want i want to get the full object back and display in a series of text, checkboxes and such the rest of the values. now when i have the whole list showing i can use the selection index and match it up to the original collection but when i add a filter the selection index doesn't match the original collection any more.

The first example is the setup of the table

the second is the Abstractdatamodel that i'm using

and the third is the listener and record change code i've got

Thanks
OccupationTableModel model = new OccupationTableModel(occupationList);
occupationTable = new JTable(model);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
occupationTable.setRowSorter(sorter);

Open in new window

package dataTypes;

import javax.swing.table.AbstractTableModel;

@SuppressWarnings("serial")
public class OccupationTableModel extends AbstractTableModel {
	Occupation[] occupations;

	public OccupationTableModel(Occupation[] occipationList) {
		occupations = occipationList;
	}

	public int getColumnCount() {
		return 5;
	}

	@Override
	public String getColumnName(int column) {
		switch (column) {
		case 0:
			return "ANZIC";
		case 1:
			return "Business Discription";
		case 2:
			return "General Acceptence";
		default:
			return "Unknown";
		}
	}

	@Override
	public int getRowCount() {
		return occupations.length;
	}

	@Override
	public Object getValueAt(int row, int col) {
		switch (col) {
		case 0:
			return occupations[row].getANZIC();
		case 1:
			return occupations[row].getbusinessDiscription();
		case 2:
			return occupations[row].getgeneralAcceptence();
		default:
			return " - ";
		}

	}

	public Object getObjectAt(int row) {
		Occupation aOcuppation = occupations[row];
		return aOcuppation;
	}
}

Open in new window

ListSelectionModel rowSM = occupationTable.getSelectionModel();
		rowSM.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				if (e.getValueIsAdjusting())
					return; // if you don't want to handle intermediate
							// selections
				ListSelectionModel rowSM = (ListSelectionModel) e.getSource();
				int selectedIndex = rowSM.getMinSelectionIndex();
				// do something with selected index
				//System.out.print(selectedIndex + " ");
				//System.out.println(occupationList[selectedIndex].getbusinessDiscription());
				recordChange(selectedIndex);
				
			}
		});

private void recordChange(int selectedIndex) {
		//This will be called when a new record is selected from the table. 
		NumberFormat nf = NumberFormat.getCurrencyInstance();
		nf.setMaximumFractionDigits(0);
		
		
		
		txtOccupationName.setText(occupationList[selectedIndex].getbusinessDiscription());
		txtGeneralAcceptence.setText(occupationList[selectedIndex].getgeneralAcceptence());
		txtPolicyWording.setText(occupationList[selectedIndex].getpolicyWording());
		chkLiabilityAllowed.setSelected((boolean) occupationList[selectedIndex].getliabilityAllowed());
		
		if (occupationList[selectedIndex].getfireSIBIC()==0) {
			txtFireSI.setText("N/A");
		} else {
			txtFireSI.setText(nf.format(occupationList[selectedIndex].getfireSIBIC()));
		}
		
		if (occupationList[selectedIndex].getliabilitySIBIC()==0) {
			txtLiabilitySI.setText("N/A");
		} else {
			txtLiabilitySI.setText(nf.format(occupationList[selectedIndex].getliabilitySIBIC()));
		}
		
		txtSurveyHazard.setText(Byte.toString(occupationList[selectedIndex].getSurveyHazard()));
		txtIndustry.setText(occupationList[selectedIndex].getIndustry());
	}

Open in new window

0
Comment
Question by:CloudStrife209
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
11 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36578308
Well, when you do the filter you can maintain HashMap which will map the new numbers to the original ones
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36578316
And if you filter your objects and have a new list of the remaining objects - in order to show the remaining fields - why do you need
to have original index ? First you show some fileds of the object then you show the remianing fields of the same object when the user selects it - don't see
why that would be a problem
0
 

Author Comment

by:CloudStrife209
ID: 36578326
"First you show some fileds of the object then you show the remianing fields of the same object when the user selects it"

that would be my problem as i'm not doing that right, only way i could figure out how to only show some fields and show the others when the user selected it was to match up the records to the original collection.
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 47

Expert Comment

by:for_yan
ID: 36578353

Why is that a problem?

manitain ArrayList of your objects and put that  ArrayList as the basis of your TableModel

then you filter your ArrayList to a shorter ArrayList but the idea remains the same - tthe new ArrayList will be the basis
of the TableModel

If you could paste some code that would be slef-standing and I could compile it - I couyld try
to understand it in a more concrete way - otherwise it is difficult to understand extensive
blocks of code by sightreading
0
 

Author Comment

by:CloudStrife209
ID: 36578370
i'm not sure if this is a problem but its not an arraylist it's simply an array of the object
package dataTypes;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.sql.*;

import system.SQLConnection;

public class Occupation {
	private String ANZIC;
	private String businessDiscription;
	private String generalAcceptence;
	private String policyWording;
	private int fireSIBIC;
	private int liabilitySIBIC;
	private boolean liabilityAllowed;
	private byte surveyHazard;
	private boolean BISreferral;
	private String primaryActivity;
	private String industry;
	private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
			this);

	public void addPropertyChangeListener(String propertyName,
			PropertyChangeListener listener) {
		propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
	}

	public void removePropertyChangeListener(PropertyChangeListener listener) {
		propertyChangeSupport.removePropertyChangeListener(listener);
	}

	public Occupation(String ANZIC, String businessDiscription,
			String generalAcceptence, String policyWording, int fireSIBIC,
			int liabilitySIBIC, boolean liabilityAllowed, byte surveyHazard,
			boolean BISreferral, String primaryActivity) {

		super();
		this.ANZIC = ANZIC;
		this.businessDiscription = businessDiscription;
		this.generalAcceptence = generalAcceptence;
		this.policyWording = policyWording;
		this.fireSIBIC = fireSIBIC;
		this.liabilitySIBIC = liabilitySIBIC;
		this.liabilityAllowed = liabilityAllowed;
		this.surveyHazard = surveyHazard;
		this.BISreferral = BISreferral;
		this.primaryActivity = primaryActivity;
	}

	public Occupation() {
		super();
		this.ANZIC = "";
		this.businessDiscription = "";
		this.generalAcceptence = "";
		this.policyWording = "";
		this.fireSIBIC = 0;
		this.liabilitySIBIC = 0;
		this.liabilityAllowed = false;
		this.surveyHazard = 0;
		this.BISreferral = false;
		this.primaryActivity = "";
	}

	public void setANZIC(String ANZIC) {
		propertyChangeSupport.firePropertyChange("ANZIC", this.ANZIC,
				this.ANZIC = ANZIC);
	}

	public void setbusinessDiscription(String businessDiscription) {
		propertyChangeSupport.firePropertyChange("businessDiscription",
				this.businessDiscription,
				this.businessDiscription = businessDiscription);
	}

	public void setgeneralAcceptence(String generalAcceptence) {
		propertyChangeSupport.firePropertyChange("generalAcceptence",
				this.generalAcceptence,
				this.generalAcceptence = generalAcceptence);
	}

	public void setpolicyWording(String policyWording) {
		propertyChangeSupport.firePropertyChange("policyWording",
				this.policyWording, this.policyWording = policyWording);
	}

	public void setfireSIBIC(int fireSIBIC) {
		propertyChangeSupport.firePropertyChange("fireSIBIC", this.fireSIBIC,
				this.fireSIBIC = fireSIBIC);
	}

	public void setliabilitySIBIC(int liabilitySIBIC) {
		propertyChangeSupport.firePropertyChange("liabilitySIBIC",
				this.liabilitySIBIC, this.liabilitySIBIC = liabilitySIBIC);
	}

	public void setliabilityAllowed(boolean liabilityAllowed) {
		propertyChangeSupport
				.firePropertyChange("liabilityAllowed", this.liabilityAllowed,
						this.liabilityAllowed = liabilityAllowed);
	}

	public void setsurveyHazard(byte surveyHazard) {
		propertyChangeSupport.firePropertyChange("surveyHazard",
				this.surveyHazard, this.surveyHazard = surveyHazard);
	}

	public void setBISreferral(boolean BISreferral) {
		propertyChangeSupport.firePropertyChange("BISreferral",
				this.BISreferral, this.BISreferral = BISreferral);
	}

	public void setprimaryActivity(String primaryActivity) {
		propertyChangeSupport.firePropertyChange("primaryActivity",
				this.primaryActivity, this.primaryActivity = primaryActivity);
	}

	public void setIndustry(String industry) {
		propertyChangeSupport.firePropertyChange("industry", this.industry,
				this.industry = industry);
	}

	public String getANZIC() {
		return ANZIC;
	}

	public String getbusinessDiscription() {
		return businessDiscription;
	}

	public String getgeneralAcceptence() {
		return generalAcceptence;
	}

	public String getpolicyWording() {
		return policyWording;
	}

	public int getfireSIBIC() {
		return fireSIBIC;
	}

	public int getliabilitySIBIC() {
		return liabilitySIBIC;
	}

	public boolean getliabilityAllowed() {
		return liabilityAllowed;
	}

	public byte getSurveyHazard() {
		return surveyHazard;
	}

	public boolean getBISreferral() {
		return BISreferral;
	}

	public String getPrimaryActivity() {
		return primaryActivity;
	}
	
	public String getIndustry() {
		return industry;
	}

	public static Occupation[] loadOccupationList() {
		int i = 0;
		Occupation[] occupationList;

		Connection conn = SQLConnection.getConnection();

		if (conn != null) {
			try {
				Statement st = conn.createStatement(
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY);

				// Change the SQL statement below to change the collected data
				ResultSet rs = st.executeQuery("SELECT * FROM tblBusinessList");

				occupationList = new Occupation[SQLConnection.getRowCount(rs)];

				rs.first();

				// Put the data into the array need to check the next after the
				// addition
				do {
					occupationList[i] = new Occupation();

					occupationList[i].setANZIC(rs.getString("ANZICCode"));
					occupationList[i].setbusinessDiscription(rs.getString("BusDiscription"));
					occupationList[i].setgeneralAcceptence(rs.getString("GeneralAcceptence"));
					occupationList[i].setpolicyWording(rs.getString("PolicyWording"));
					occupationList[i].setfireSIBIC(rs.getInt("FireSI"));
					occupationList[i].setliabilitySIBIC(rs.getInt("LiabilitySI"));
					occupationList[i].setliabilityAllowed(rs.getBoolean("LiabilityAllowed"));
					occupationList[i].setsurveyHazard(rs.getByte("SurveyHazard"));
					occupationList[i].setBISreferral(rs.getBoolean("ReferToBIS"));
					occupationList[i].setprimaryActivity(rs.getString("PrimaryActivity"));
					occupationList[i].setIndustry(rs.getString("Industry"));

					i++;
				} while (rs.next());

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				occupationList = null;
			}

		} else {
			occupationList = null;
		}

		return occupationList;
	}
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36578408
In general ArrayList' s are more convenient than arrays, but in this respect it should not be that different -
just create TableModel around the array of your objects.
When you filter this array to another array - set this new array at the basis of TableModel
(say make the method setArray.. or something)

Your Occupation class is good, but still i cannot compile the whole thing,
but try to do it this way - I see no reason why you cannot do it the way I mentioned

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36578811
What is the primary key (compound or otherwise) of Occupation? You could use that
0
 

Author Comment

by:CloudStrife209
ID: 36583783
Primary key for occupation is ANZIC
0
 

Author Comment

by:CloudStrife209
ID: 36583960
i needed the following line of code to do the conversion for me

table.convertRowIndexToModel(viewRow);
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36584002

I guess, you can use TableRowSorter

http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableRowSorter.html

and it looks like provides such functionality

Id still think that to filter your data and change underlying model will be simpler
at least for not too long tables
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 36585111
This is an example of using TableRowFilter
from
http://www.java2s.com/Tutorial/Java/0240__Swing/Tablerowfilerandsortkey.htm
which I modified adding mouse listener and checking how convertRowIndexToModel is working.
Looks nicely.

You may filter, by letters "C", "G" or orring  them, like "C|G"
and then see how original and view indexes are different  

Hope it could help you.



import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class NewFilterTable extends JFrame implements MouseListener {
     JTable table;
  public NewFilterTable() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    String[] columns = { "ID", "Des", "Date", "Fixed" };
    Object[][] rows = { { 1, "C", new Date(), new Date() }, { 2, "G", new Date(), new Date() },
        { 5, "F", new Date(), new Date() } };

    TableModel model = new DefaultTableModel(rows, columns);
     table = new JTable(model);
      table.addMouseListener(this);
    final TableRowSorter<TableModel> sorter;
    sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);
    getContentPane().add(new JScrollPane(table));

    JPanel pnl = new JPanel();
    pnl.add(new JLabel("Filter expression:"));
    final JTextField txtFE = new JTextField(25);
    pnl.add(txtFE);
    JButton btnSetFE = new JButton("Set Filter Expression");
    ActionListener al;
    al = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String expr = txtFE.getText();
        sorter.setRowFilter(RowFilter.regexFilter(expr));
        sorter.setSortKeys(null);
      }
    };
    btnSetFE.addActionListener(al);
    pnl.add(btnSetFE);
    getContentPane().add(pnl, BorderLayout.SOUTH);

    setSize(750, 150);
    setVisible(true);
  }

public void mouseEntered(MouseEvent me){}
  public void mousePressed(MouseEvent me){}
    public void mouseReleased(MouseEvent me){}
    public void mouseExited(MouseEvent me){}
    public void mouseClicked(MouseEvent me){

         System.out.println("view index: " + table.rowAtPoint(me.getPoint()));
         System.out.println("orig index: " + table.convertRowIndexToModel(table.rowAtPoint(me.getPoint())));
        
    }



  public static void main(String[] args) {
    new NewFilterTable();
  }
}

Open in new window

0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question