TableViewer.refresh not working - java

The two events that I add to the table viewer are not appearing on the screen.
Here is my code to create the table viewer, table, and one column
TableViewer tableViewer = new TableViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
fd_btnNewButton.left = new FormAttachment(table, 6);
FormData fd_table = new FormData();
fd_table.top = new FormAttachment(eventLabel, 6);
fd_table.left = new FormAttachment(0, 10);
fd_table.right = new FormAttachment(100, -100);
fd_table.bottom = new FormAttachment(eventLabel, 387, SWT.BOTTOM);
table.setLayoutData(fd_table);
TableColumn tableColumn = new TableColumn(table,SWT.LEFT);
String[] column_names = new String[]{"Events"};
tableColumn.setText(column_names[0]);
tableViewer.setColumnProperties(column_names);
tableViewer.setLabelProvider(new ContinuousIntegrationLabelProvider());
tableViewer.setContentProvider(new ContinuousIntegrationContentProvider());
The table is being created successfully.. Next, I am setting the inputs and then refreshing the table...
events.add("Build"); //events is an ArrayList<String>
events.add("JUnit Tests");
tableViewer.setInput(events);
tableViewer.refresh();
And here are my provider methods:
/**
* label provider for the table
*/
public class ContinuousIntegrationLabelProvider extends LabelProvider implements ITableLabelProvider {
/**
* image for the column
*/
public Image getColumnImage(Object element, int index){
switch(index){
case 0:
if(model.getJenkinsJob() == null){
return Images.getImage(Images.WARNING);
}
else{
return null;
}
default:
return null;
}
}
/**
* returns the correct value for each column
*/
public String getColumnText(Object element, int index){
switch(index){
case 0:
return (String) element;
default:
return "";
}
}
And here is my content provider:
/**
* content provider for the table
*/
public class ContinuousIntegrationContentProvider implements IStructuredContentProvider {
#SuppressWarnings("unchecked")
public Object[] getElements(Object inputElement) {
ArrayList<String> data = (ArrayList<String>) inputElement;
return data.toArray();
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}

I just needed to set the width on the table column and then everything would show up.
Here is the portion of the code that I changed:
TableColumn tableColumn = new TableColumn(table, SWT.LEFT);
String[] column_names = new String[]{"Events"};
tableColumn.setText(column_names[0]);
tableColumn.setWidth(352);

Related

jFace CheckboxTableViewer and content provider

i am new to jFace. I'm using the following TableViewer Class as an example:
public class AppPersonViewer extends TableViewer
{
public Table table;
public AppPersonViewer(Composite parent, int style)
{
super(parent, style);
table = getTable();
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
table.setLayoutData(gridData);
createColumns();
table.setHeaderVisible(true);
table.setLinesVisible(true);
setContentProvider(new AppContentProvider());
}
private void createColumns()
{
String[] titles = { "First Name", "Second Name", "Age", "Country", "Likes SO" };
int[] bounds = { 150, 150, 100, 150, 100 };
TableViewerColumn column = createTableViewerColumn(titles[0], bounds[0], 0);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ((Person)element).getFirst();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[1], bounds[1], 1);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ((Person)element).getSecond();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[2], bounds[2], 2);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ""+((Person)element).getAge();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[3], bounds[3], 3);
column.setLabelProvider(new ColumnLabelProvider(){
public String getText(Object element) {
if(element instanceof Person)
return ((Person)element).getCountry();
return super.getText(element);
}
});
column = createTableViewerColumn(titles[4], bounds[4], 4);
column.setLabelProvider(new ColumnLabelProvider(){
public Image getImage(Object element) {
return ((Person)element).getImage();
}
public String getText(Object element) {
return null; // no string representation, we only want to display the image
}
});
}
private TableViewerColumn createTableViewerColumn(String header, int width, int idx)
{
TableViewerColumn column = new TableViewerColumn(this, SWT.LEFT, idx);
column.getColumn().setText(header);
column.getColumn().setWidth(width);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(true);
return column;
}
}
The example works great. Now i want to display checkboxes in the first column of each table row. (In native SWT the flag SWT.CHECK does that work).
After some searching i found the class CheckboxTableViewer. So i changed the example to:
public class AppPersonViewer extends CheckboxTableViewer
{
public Table table;
public AppPersonViewer(Composite parent, int style)
{
super(parent, style);
table = getTable();
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
table.setLayoutData(gridData);
createColumns();
table.setHeaderVisible(true);
table.setLinesVisible(true);
setContentProvider(new AppContentProvider());
}
.
.
.
The checkboxes are displayed now, but i have no idea how to use the checkboxes in my content provider. Any idea?
The CheckboxTableViewer uses a separate ICheckStateProvider to set the check boxes.
Set with
viewer.setCheckStateProvider(checkStateProvider);
The provider has two methods isChecked and isGrayed.
The values passed to these methods are the objects from your content provider.
Alternatively CheckboxTableViewer has setChecked, setAllChecked, ... methods.

JTable and custom JComboBox

I want to implement a custom JComboBox as an CellEditor for a JTable. I took the original Java Example and modified it by implementing a Sports class
Please run the source code, click on the JComboBox and you will note that the selected item is not selected anymore when the ComboBox opens.
I want to keep the renderered item in the combobox selection.
Original: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#combobox
public class Sport {
private Integer id;
private String name;
public Sport(String name){
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
public class TableRenderDemo extends JPanel {
private boolean DEBUG = false;
public TableRenderDemo() {
super(new GridLayout(1,0));
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Set up column sizes.
initColumnSizes(table);
//Fiddle with the Sport column's cell editors/renderers.
setUpSportColumn(table, table.getColumnModel().getColumn(2));
//Add the scroll pane to this panel.
add(scrollPane);
}
/*
* This method picks good column sizes.
* If all column heads are wider than the column's cells'
* contents, then you can just use column.sizeWidthToFit().
*/
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer =
table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(
null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues[i],
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith",new Sport("Snowboarding"),
new Integer(5), new Boolean(false)},
{"John", "Doe",
new Sport("Rowing"), new Integer(3), new Boolean(true)},
{"Sue", "Black",
new Sport("Knitting"), new Integer(2), new Boolean(false)},
{"Jane", "White",
new Sport("Speed reading"), new Integer(20), new Boolean(true)},
{"Joe", "Brown",
new Sport("Pool"), new Integer(10), new Boolean(false)}
};
public final Object[] longValues = {"Jane", "Kathy",
"None of the above",
new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Ok I included the following, but still the same problem:
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
JComboBox<Sport> comboBox = new JComboBox();
comboBox.addItem(new Sport("Snowboarding"));
comboBox.addItem(new Sport("Rowing"));
comboBox.addItem(new Sport("Knitting"));
comboBox.addItem(new Sport("Speed reading"));
comboBox.addItem(new Sport("Pool"));
comboBox.addItem(new Sport("None of the above"));
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
// sportColumn.setCellEditor(new MyCellEditor());
}
You also need to override the equals(...) and hashcode(...) methods of the Sport class. Java Collection methods rely on these methods to determine equality of a object instance when doing searches.
#Override
public boolean equals(Object object)
{
Sport sport = (Sport)object;
return this.name.equals( sport.getName() );
}
#Override
public int hashCode()
{
return name.hashCode();
}
Also, read the Object API for more information on these methods.
Your model contains instances of Sport class but the JCombobox contains strings. That's why set selection can't find proper value.
Try to add sports like this
comboBox.addItem(new Sport("Rowing"));
And either override toString() method of Sport class to return the name (easier way). Or add a custom renderer to the sports combo box.

Last column gets oversized in jface

I'm quite new with Jface, and right now I'm facing a problem with the last column in a table. Take a look at the next screenshot:
As you can see, the last column gets oversized when the application is initiated, and I can't fix that, no matter what! Below you can see the View code:
package de.vogella.jface.tableviewer;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import de.vogella.jface.tableviewer.model.CenterImageLabelProvider;
import de.vogella.jface.tableviewer.model.ModelProvider;
import de.vogella.jface.tableviewer.model.Person;
public class View extends ViewPart {
public static final String ID = "de.vogella.jface.tableviewer.view";
private TableViewer viewer;
// static fields to hold the images
private static final Image CHECKED = Activator.getImageDescriptor(
"icons/checked.gif").createImage();
private static final Image UNCHECKED = Activator.getImageDescriptor(
"icons/unchecked.gif").createImage();
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
Label searchLabel = new Label(parent, SWT.NONE);
searchLabel.setText("Search: ");
final Text searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
| GridData.HORIZONTAL_ALIGN_FILL));
createViewer(parent);
}
private void createViewer(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
createColumns(parent, viewer);
final Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
viewer.setContentProvider(new ArrayContentProvider());
// get the content for the viewer, setInput will call getElements in the
// contentProvider
viewer.setInput(ModelProvider.INSTANCE.getPersons());
// make the selection available to other views
getSite().setSelectionProvider(viewer);
// set the sorter for the table
// define layout for the viewer
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
}
public TableViewer getViewer() {
return viewer;
}
// create the columns for the table
private void createColumns(final Composite parent, final TableViewer viewer) {
String[] titles = { "First name", "Last name", "Gender", "Married", "Age" };
int[] bounds = { 100, 100, 100, 100, 100 };
// first column is for the first name
TableViewerColumn col = createTableViewerColumn(titles[0], bounds[0], 0);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getFirstName();
}
});
// second column is for the last name
col = createTableViewerColumn(titles[1], bounds[1], 1);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getLastName();
}
});
// now the gender
col = createTableViewerColumn(titles[2], bounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getGender();
}
});
// now the status married
col = createTableViewerColumn(titles[3], bounds[3], 3);
col.setLabelProvider(new CenterImageLabelProvider() {
#Override
public Image getImage(Object element) {
if (((Person) element).isMarried()) {
return CHECKED;
}
else {
return UNCHECKED;
}
}
});
// now the age
col = createTableViewerColumn(titles[4], bounds[4], 4);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Person p = (Person) element;
return p.getAge().toString();
}
});
}
private TableViewerColumn createTableViewerColumn(String title,
int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
SWT.CENTER);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
public void setFocus() {
viewer.getControl().setFocus();
}
}
How can I fix this?
Your layout on the viewer:
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
says that you want the viewer to use all the available horizontal space, so the viewer has had to resize the last column to make this happen.
Use
gridData.grabExcessHorizontalSpace = false;
gridData.horizontalAlignment = GridData.BEGINNING;
to not grab the extra space.
Alternatively to fill the space available leave the GridData alone and use TableLayout and ColumnWeightData, something like:
TableLayout tableLayout = new TableLayout();
table.setLayout(tableLayout);
...
... don't call column.setWidth replace with:
tableLayout.addColumnData(new ColumnWeightData(nnn));
nnn is a number you choose for each column and is the 'weight' used to calculate the width of the column.

Type of listener for updates to given cells/columns in JTable and incrementing focus

I am trying to use a JTable with the first column predefined. The user enters data into the 2nd column only (Quantity). Then I calculate the final income by multiplying the Service and Quantity columns and display it in the third column, Income.
|Service | Quantity | Income
|$40.00 | X |
|$40.00 | 3 | 120
Here user inputs "3" because she did "3" of service X today at $40 each. The user can only update the Quantity column. The Income column will be calculated by the system.
What type of listener should I use? I was using a TableModelListener but when I want to update Income to 120 by calling setValue = $120 it fires off a TableListenerEvent and hence an infinite loop.
Should I use an ActionEvent, a ColumnListener or something else?
Also, I want the "focus" to increment down the rows, always staying on the second column (the column the user edits).
for Listning changes into TableCell you have to implements TableModelListener for example
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableProcessing extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
private String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
private Object[][] data = {
{"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
{"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
{"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
{"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}};
private TableModelListener tableModelListener;
public TableProcessing() {
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
#Override// Returning the Class of each column will allow different renderers
public Class getColumnClass(int column) { // to be used based on Class
return getValueAt(0, column).getClass();
}
#Override // The Cost is not editable
public boolean isCellEditable(int row, int column) {
int modelColumn = convertColumnIndexToModel(column);
return (modelColumn == 3) ? false : true;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
//http://stackoverflow.com/questions/7188179/jtable-focus-query/7193023#7193023
table.setCellSelectionEnabled(true);
KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
InputMap map = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
map.put(tab, "selectNextRowCell");
//http://stackoverflow.com/questions/7188179/jtable-focus-query/7193023#7193023
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
setTableModelListener();
}
private void setTableModelListener() {
tableModelListener = new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE) {
System.out.println("Cell " + e.getFirstRow() + ", "
+ e.getColumn() + " changed. The new value: "
+ table.getModel().getValueAt(e.getFirstRow(),
e.getColumn()));
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1 || column == 2) {
TableModel model = table.getModel();
int quantity = ((Integer) model.getValueAt(row, 1)).intValue();
double price = ((Double) model.getValueAt(row, 2)).doubleValue();
Double value = new Double(quantity * price);
model.setValueAt(value, row, 3);
}
}
}
};
table.getModel().addTableModelListener(tableModelListener);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TableProcessing frame = new TableProcessing();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Filling data in JTable in netbeans

I want to change default data in JTable at runtime. I am using netbeans. I tried solution given here adding data to JTable when working with netbeans
jTable1.getModel().setValueAt(row, column, value);
but it gives me this error:
If you want to change it at runtime you need to decide when you want it changed and add the code to the proper method/event. As it stands you have a method call in your class definition, which is not valid code.
For instance
public void setTableModel(){
displayTable.getModel().setValueAt(2,4,300);
}
And then call setTableModel() at an appropriate time.
because you wrote this code line out of current Class, you have to wrap these code line(s)
inside Class/void/constructor, for example
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableProcessing extends JFrame implements TableModelListener {
private static final long serialVersionUID = 1L;
private JTable table;
public TableProcessing() {
String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
Object[][] data = {
{"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
{"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
{"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
{"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
model.addTableModelListener(this);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
#Override
public boolean isCellEditable(int row, int column) {
int modelColumn = convertColumnIndexToModel(column);
return (modelColumn == 3) ? false : true;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
#Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE) {
int row = e.getFirstRow();
int column = e.getColumn();
System.out.println(row + " : " + column);
if (column == 1 || column == 2) {
int quantity = ((Integer) table.getModel().getValueAt(row, 1)).intValue();
double price = ((Double) table.getModel().getValueAt(row, 2)).doubleValue();
Double value = new Double(quantity * price);
table.getModel().setValueAt(value, row, 3);
}
}
}
public static void main(String[] args) {
TableProcessing frame = new TableProcessing();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Categories