participate


Swing - JTable getValues help
This question is answered.

<<   Back to Forum  |   Give us Feedback
2 Duke Stars rewarded for this thread
This topic has 6 replies on 1 page.
Manijak
Posts:6
Registered: 11/17/09
JTable getValues help   
Nov 17, 2009 11:14 AM
 
 
I have to make table with two buttons, one for adding a new row, and one that gets values from selected cells and then summing that values. I resolved adding a new row, but can somebody help me with this summing of selected cells values. Here is the code :

 final JTable table=new JTable(model);
		//table.setPreferredScrollableViewportSize(new Dimension(300, 70));
        table.setFillsViewportHeight(true);
        
        
		JScrollPane jsp=new JScrollPane(table);
		
		table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		
		JButton button = new JButton("Summing");
		button.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
			  
			 
			}
		});
		
		add(jsp);	
		add(button);
		
		JTextArea output = new JTextArea(5, 40);
        output.setEditable(false);
        add(new JScrollPane(output));
        
        JButton button1 = new JButton ("Dodaj red");
        button1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				MojTableModel.dodajRed();
				table.updateUI();
			
			}
		});
        add(button1);
        
		
		pack();
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
	}
 
	private static class MojTableModel extends AbstractTableModel {
		 
		String[] columns  = { "1.", "2.", "3.", "4.", "5.", "6.", "7." };
		
		public static ArrayList<ArrayList<String>> redovi;
		
		public MojTableModel(){
			
			redovi = new ArrayList<ArrayList<String>>();
			
			for (int i=0; i<10; i++){
				
				ArrayList<String> red = new ArrayList<String>();
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				redovi.add(red);
				
			}
		}
		
		public int getColumnCount(){
			return columns.length;
		}
		
		public int getRowCount(){
			return redovi.size();
		}
		
		public Object getValueAt(int rowIndex, int columnIndex){
			return redovi.get(rowIndex).get(columnIndex);
		}
		
		public boolean isCellEditable(int rowIndex, int columnIndex){
			return true;
		}
		
		public void setValueAt(Object value, int rowIndex, int columnIndex){
			redovi.get(rowIndex).set(columnIndex, (String) value);
		}
		
		public static void dodajRed(){
			
			ArrayList<String> red=new ArrayList<String>();
			red.add("0");
			red.add("0");
			red.add("0");
			red.add("0");
			red.add("0");
			red.add("0");
			red.add("0");
			MojTableModel.redovi.add(red);
			
		}
	}
 
camickr
Posts:33,025
Registered: 27/02/98
Re: JTable getValues help   
Nov 17, 2009 12:16 PM (reply 1 of 6)  (In reply to original post )
 
 
I resolved adding a new row,

It may work, but it is not done correctly. You should never need to use the updateUI() method for something like this.

The AbstractTableModel provides the fireTableRowsInserted(...) method for this purpose.

In fact there is no need for you to create a custom TableModel because the DefaultTableModel already extend the AbstractTableModel and implements an addRow(...) method.

but can somebody help me with this summing of selected cells values

Read the JTable API for the method that returns the selected rows. You then create a loop an use the getValueAt(...) method to get the values for each selected row and add them together.
 
jdima
Posts:27
Registered: 11/14/09
Re: JTable getValues help   
Nov 17, 2009 12:35 PM (reply 2 of 6)  (In reply to original post )
 
 
Try something like this. add to your button

	protected void bt_sumCells_actionPerformed(ActionEvent e) {
		
		double sum = 0;
 
                        //check if there is selected row
		if (table.getSelectedRow() != -1) {
 
			TableColumnModel colModel = table.getColumnModel();
                                   //iterate throw table columns
			for (int i = 0; i < colModel.getColumnCount(); i++) {
 
                                                //check cell value type. 
				if (table.getModel().getValueAt(table.getSelectedRow(), i).getClass() == Double.class) {//if double then sum
 
                                                            //parse double
					double temp=Double.parseDouble(table.getModel().getValueAt(table.getSelectedRow(),i).toString());
					//sum
					sum+=temp;
					
					
                                                //check cell value type. 
				} else if (table.getModel().getValueAt(table.getSelectedRow(),i).getClass() == Integer.class) {//if int then sum
                                                           //parse int
					int temp=Integer.parseInt(table.getModel().getValueAt(table.getSelectedRow(),i).toString());
					//sum
					sum+=temp;
					
				}else{//else other type (String, Date etc.) do not parse them
					System.err.println("Can no include this value in sum: "+table.getModel().getValueAt(table.getSelectedRow(),
						i).toString());
				}
				
 
			}
 
		}else{//there is no selected row show massage
			JOptionPane.showMessageDialog(this,"There is no selected cells in the table","info",JOptionPane.INFORMATION_MESSAGE);
		}
		
		//finnaly use SUM .
		System.err.println("Final Sum: "+sum);
	}
 
Manijak
Posts:6
Registered: 11/17/09
Re: JTable getValues help   
Nov 17, 2009 2:14 PM (reply 3 of 6)  (In reply to #2 )
 
 
Ok, I added your code, but it doesn't work. When I click on button it only display in text area "Final Sum: 0.0".
And this single interval selection also doesn't work, do you know how to solve that, must it be called from MyTableModel maybe ?

public class Table extends JFrame {
	
	JTextArea area;
 
	public Table(){
		
		this.setTitle("Excel Mocni");
		this.setLayout(new GridBagLayout());
		
		final JTable table=new JTable(new MyTableModel());
		JScrollPane skrol=new JScrollPane(table);
		table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		table.setFillsViewportHeight(true);
		
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.BOTH;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridheight = 4;
		gbc.gridwidth = 1;
		gbc.weightx = 0.6;
		gbc.weighty = 0.6;
		add(skrol, gbc);
 
		final JButton sabiranje = new JButton("Summing");
		sabiranje.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				double sum = 0;
 
				// check if there is selected row
				if (table.getSelectedRow() != -1) {
 
					TableColumnModel colModel = table.getColumnModel();
					// iterate throw table columns
					for (int i = 0; i < colModel.getColumnCount(); i++) {
 
						// check cell value type.
						if (table.getModel().getValueAt(table.getSelectedRow(),i).getClass() == Double.class) {// if double
																// then sum
 
							// parse double
							double temp = Double.parseDouble(table.getModel().getValueAt(table.getSelectedRow(), i).toString());
							// sum
							sum += temp;
 
							// check cell value type.
						} else if (table.getModel().getValueAt(table.getSelectedRow(), i).getClass() == Integer.class) {
							// parse int
							int temp = Integer.parseInt(table.getModel().getValueAt(table.getSelectedRow(), i).toString());
							
							sum += temp;
 
						} else {
							area.setText("Nesto ne radi");
						}
					}
				} else {
					
					area.setText("Can no include some value in sum");
				}
				// finnaly use SUM .
				area.setText("Final Sum: "+sum);
 
				
			}
		
		
	
	
	});
 
		GridBagConstraints gbc1 = new GridBagConstraints();
		gbc1.fill = GridBagConstraints.HORIZONTAL;
		// gbc1.anchor = GridBagConstraints.NORTH;
		gbc1.ipady = 1;
		gbc1.ipadx = 1;
		gbc1.gridx = 1;
		gbc1.gridy = 0;
		gbc1.gridheight = 1;
		gbc1.gridwidth = 1;
		gbc1.insets = new Insets(1, 0, 1, 0);
		gbc1.weightx = 0.6;
		gbc1.weighty = 0.6;
		add(sabiranje, gbc1);
 
		final JButton oduzimanje = new JButton("SubTraction");
		oduzimanje.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				
		
			}
			
		});
 
		GridBagConstraints gbc2 = new GridBagConstraints();
		gbc2.fill = GridBagConstraints.HORIZONTAL;
		gbc2.anchor = GridBagConstraints.NORTH;
		gbc2.gridx = 1;
		gbc2.gridy = 1;
		gbc2.gridheight = 1;
		gbc2.gridwidth = 1;
		gbc2.insets = new Insets(1, 0, 1, 0);
		gbc2.weightx = 0.6;
		gbc2.weighty = 0.6;
		add(oduzimanje, gbc2);
		
		
		final JButton mnozenje = new JButton("Mnozi");
		mnozenje.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		GridBagConstraints gbc6 = new GridBagConstraints();
		gbc6.fill = GridBagConstraints.HORIZONTAL;
		gbc6.gridx = 1;
		gbc6.gridy = 2;
		gbc6.gridheight = 1;
		gbc6.gridwidth = 1;
		gbc6.insets = new Insets(1, 0, 1, 0);
		gbc6.weightx = 0.6;
		gbc6.weighty = 0.6;
		add(mnozenje, gbc6);
 
		final JButton red = new JButton("Dodaj red");
		red.addActionListener(new ActionListener() {
 
			@Override
			public void actionPerformed(ActionEvent e) {
				
				MyTableModel.dodajRed();
				table.updateUI();
 
			}
		});
 
		GridBagConstraints gbc3 = new GridBagConstraints();
		gbc3.fill = GridBagConstraints.HORIZONTAL;
		gbc3.anchor = GridBagConstraints.NORTH;
		gbc3.gridx = 1;
		gbc3.gridy = 3;
		gbc3.gridheight = 1;
		gbc3.gridwidth = 1;
		gbc3.weightx = 0.6;
		gbc3.weighty = 0.6;
		gbc3.insets = new Insets(1, 0, 1, 0);
		add(red, gbc3);
 
		JLabel label = new JLabel("Rezultat: ");
		GridBagConstraints gbc5 = new GridBagConstraints();
		gbc5.gridx = 0;
		gbc5.gridy = 4;
		gbc5.gridwidth = 1;
		add(label, gbc5);
 
		area = new JTextArea();
		area.setAutoscrolls(true);
		area.setEditable(false);
		area.setRows(5);
		area.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		GridBagConstraints gbc4 = new GridBagConstraints();
		gbc4.fill = GridBagConstraints.BOTH;
		gbc4.gridx = 0;
		gbc4.gridy = 5;
		gbc4.gridwidth = 1;
		add(area, gbc4);
 
		this.pack();
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		
	}
 
	public static class MyTableModel extends AbstractTableModel {
 
		 String[] columns  = { "1.", "2.", "3.", "4.", "5.", "6.", "7." };
		
		 static ArrayList<ArrayList<String>> rows;
		
		 public MyTableModel(){
				
				rows = new ArrayList<ArrayList<String>>();
				
				for (int i=0; i<10; i++){
					
					ArrayList<String> red = new ArrayList<String>();
					red.add("0");
					red.add("0");
					red.add("0");
					red.add("0");
					red.add("0");
					red.add("0");
					red.add("0");
					rows.add(red);
					
				}
			}
			
			public int getColumnCount(){
				return columns.length;
			}
			
			public int getRowCount(){
				return rows.size();
			}
			
			public Object getValueAt(int rowIndex, int columnIndex){
				return rows.get(rowIndex).get(columnIndex);
			}
			
			public boolean isCellEditable(int rowIndex, int columnIndex){
				return true;
			}
			
			public void setValueAt(Object value, int rowIndex, int columnIndex){
				rows.get(rowIndex).set(columnIndex, (String) value);
			}
			
			public static void dodajRed(){
				
				ArrayList<String> red=new ArrayList<String>();
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				red.add("0");
				MyTableModel.rows.add(red);
				
			}
		
	}
	
	public static void main(String[] args) {
		new Table();
		
	}
}
 
jdima
Posts:27
Registered: 11/14/09
Re: JTable getValues help   
Nov 17, 2009 9:28 PM (reply 4 of 6)  (In reply to #3 )
 
 
ArrayList was inited as String. this summing work on single selected row, to sum multi selected rows modifai for loop.


public class Table extends JFrame {
 
	JTextArea area;
 
	public Table() {
 
		this.setTitle("Excel Mocni");
		this.setLayout(new GridBagLayout());
 
		final JTable table = new JTable(new MyTableModel());
		JScrollPane skrol = new JScrollPane(table);
		table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		table.setFillsViewportHeight(true);
 
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.BOTH;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridheight = 4;
		gbc.gridwidth = 1;
		gbc.weightx = 0.6;
		gbc.weighty = 0.6;
		add(skrol, gbc);
 
		final JButton sabiranje = new JButton("Summing");
		sabiranje.addActionListener(new ActionListener() {
 
			public void actionPerformed(ActionEvent e) {
 
				double sum = 0;
 
				// check if there is selected row
				if (table.getSelectedRow() != -1) {
 
					TableColumnModel colModel = table.getColumnModel();
					// iterate throw table columns
					for (int i = 0; i < colModel.getColumnCount(); i++) {
 
						// check cell value type.
						if (table.getModel().getValueAt(table.getSelectedRow(),
								i).getClass() == Double.class) {// if double
							// then sum
 
							// parse double
							double temp = Double.parseDouble(table.getModel()
									.getValueAt(table.getSelectedRow(), i)
									.toString());
							// sum
							sum += temp;
 
							// check cell value type.
						} else if (table.getModel().getValueAt(
								table.getSelectedRow(), i).getClass() == Integer.class) {
							// parse int
							int temp = Integer.parseInt(table.getModel()
									.getValueAt(table.getSelectedRow(), i)
									.toString());
 
							sum += temp;
 
						} else {
							area.setText("Nesto ne radi");
						}
					}
				} else {
 
					area.setText("Can no include some value in sum");
				}
				// finnaly use SUM .
				area.setText("Final Sum: " + sum);
 
			}
 
		});
 
		GridBagConstraints gbc1 = new GridBagConstraints();
		gbc1.fill = GridBagConstraints.HORIZONTAL;
		// gbc1.anchor = GridBagConstraints.NORTH;
		gbc1.ipady = 1;
		gbc1.ipadx = 1;
		gbc1.gridx = 1;
		gbc1.gridy = 0;
		gbc1.gridheight = 1;
		gbc1.gridwidth = 1;
		gbc1.insets = new Insets(1, 0, 1, 0);
		gbc1.weightx = 0.6;
		gbc1.weighty = 0.6;
		add(sabiranje, gbc1);
 
		final JButton oduzimanje = new JButton("SubTraction");
		oduzimanje.addActionListener(new ActionListener() {
 
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
 
			}
 
		});
 
		GridBagConstraints gbc2 = new GridBagConstraints();
		gbc2.fill = GridBagConstraints.HORIZONTAL;
		gbc2.anchor = GridBagConstraints.NORTH;
		gbc2.gridx = 1;
		gbc2.gridy = 1;
		gbc2.gridheight = 1;
		gbc2.gridwidth = 1;
		gbc2.insets = new Insets(1, 0, 1, 0);
		gbc2.weightx = 0.6;
		gbc2.weighty = 0.6;
		add(oduzimanje, gbc2);
 
		final JButton mnozenje = new JButton("Mnozi");
		mnozenje.addActionListener(new ActionListener() {
 
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
 
			}
		});
 
		GridBagConstraints gbc6 = new GridBagConstraints();
		gbc6.fill = GridBagConstraints.HORIZONTAL;
		gbc6.gridx = 1;
		gbc6.gridy = 2;
		gbc6.gridheight = 1;
		gbc6.gridwidth = 1;
		gbc6.insets = new Insets(1, 0, 1, 0);
		gbc6.weightx = 0.6;
		gbc6.weighty = 0.6;
		add(mnozenje, gbc6);
 
		final JButton red = new JButton("Dodaj red");
		red.addActionListener(new ActionListener() {
 
			public void actionPerformed(ActionEvent e) {
 
				MyTableModel.dodajRed();
				table.updateUI();
 
			}
		});
 
		GridBagConstraints gbc3 = new GridBagConstraints();
		gbc3.fill = GridBagConstraints.HORIZONTAL;
		gbc3.anchor = GridBagConstraints.NORTH;
		gbc3.gridx = 1;
		gbc3.gridy = 3;
		gbc3.gridheight = 1;
		gbc3.gridwidth = 1;
		gbc3.weightx = 0.6;
		gbc3.weighty = 0.6;
		gbc3.insets = new Insets(1, 0, 1, 0);
		add(red, gbc3);
 
		JLabel label = new JLabel("Rezultat: ");
		GridBagConstraints gbc5 = new GridBagConstraints();
		gbc5.gridx = 0;
		gbc5.gridy = 4;
		gbc5.gridwidth = 1;
		add(label, gbc5);
 
		area = new JTextArea();
		area.setAutoscrolls(true);
		area.setEditable(false);
		area.setRows(5);
		area.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		GridBagConstraints gbc4 = new GridBagConstraints();
		gbc4.fill = GridBagConstraints.BOTH;
		gbc4.gridx = 0;
		gbc4.gridy = 5;
		gbc4.gridwidth = 1;
		add(area, gbc4);
 
		this.pack();
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
	}
 
	public static class MyTableModel extends AbstractTableModel {
 
		String[] columns = { "1.", "2.", "3.", "4.", "5.", "6.", "7." };
 
		static ArrayList<ArrayList<Object>> rows;
 
		public MyTableModel() {
 
			rows = new ArrayList<ArrayList<Object>>();
 
			for (int i = 0; i < 10; i++) {
 
				ArrayList<Object> red = new ArrayList<Object>();
				red.add(new Integer(0));
				red.add(new Integer(0));
				red.add(new Integer(0));
				red.add(new Integer(0));
				red.add(new Integer(0));
				red.add(new Integer(0));
				red.add(new Integer(0));
				rows.add(red);
 
			}
		}
 
		public int getColumnCount() {
			return columns.length;
		}
 
		public int getRowCount() {
			return rows.size();
		}
 
		public Object getValueAt(int rowIndex, int columnIndex) {
			return rows.get(rowIndex).get(columnIndex);
		}
 
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return true;
		}
 
		public void setValueAt(Object value, int rowIndex, int columnIndex) {
 
			try {
				rows.get(rowIndex).set(columnIndex,
						(Integer.parseInt(value.toString())));
			} catch (NumberFormatException e) {
				// TODO set as string value
				e.printStackTrace();
				rows.get(rowIndex).set(columnIndex, (value.toString()));
 
			}
 
		}
 
		public static void dodajRed() {
 
			ArrayList<Object> red = new ArrayList<Object>();
			red.add(new Integer(0));
			red.add(new Integer(0));
			red.add(new Integer(0));
			red.add(new Integer(0));
			red.add(new Integer(0));
			red.add(new Integer(0));
			red.add(new Integer(0));
			MyTableModel.rows.add(red);
 
		}
 
	}
 
	public static void main(String[] args) {
		new Table();
 
	}
 
Manijak
Posts:6
Registered: 11/17/09
Re: JTable getValues help   
Nov 18, 2009 11:17 AM (reply 5 of 6)  (In reply to #4 )
 
 
Ok, that's for multi row selected, but there is "table.setCellSelectionEnabled(true);", so I need to sum only sellected cell's values, like here: http://img265.imageshack.us/img265/4729/37979180.png
 
jdima
Posts:27
Registered: 11/14/09
Re: JTable getValues help      
Nov 18, 2009 1:32 PM (reply 6 of 6)  (In reply to #5 )
Helpful
 
init table with this parametrs
	table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	    table.setColumnSelectionAllowed(true);
	    table.setRowSelectionAllowed(true);



and something like this method to scroll over cells and sum values

	private void intSum() {
 
		int sum = 0;
		
		if (table.getSelectedRow() != -1) {
 
			int[] selRows = table.getSelectedRows();
 
			int[] selCols = table.getSelectedColumns();
 
			for (int r = 0; r < selRows.length; r++) {
 
				for (int c = 0; c < selCols.length; c++) {
 
					System.err.println("CELL(cr: " + selRows[r] + " , "
							+ selCols[c]);
 
					sum += Integer.parseInt(table.getModel().getValueAt(
							selRows[r], selCols[c]).toString());
				}
 
			}
 
		} else {
			System.err.println("there is no selected rows");
		}
		
		System.err.println("FINAL SUM: " + sum);
	}
 
This topic has 6 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 25
  • Guests : 132

About Sun forums
  • Oracle Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Oracle Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums