How to remove redundant column in tableviewer? - java

I created tableviewer .
The columns are created dynamically.
The problem that I always have another column in the table.
I checked the names of the columns and I didn't get any empty column.
Maybe it could be a configuration of the tableviewer .
Do you have any idea why I always have another column ?
//The gridViewer Class
public class MyGridViewer extends TableViewer {
public MyGridViewer (Composite parent) {
super(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
final Table table = this.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
this.setContentProvider(new MyModelProvider());
}
}
#Override
protected void inputChanged(Object input, Object oldInput) {
removeColumn();
tableCol = new TableViewerColumn(this, SWT.NONE);
column = tableCol.getColumn();
column.setText(dataColumnHeader.getName());
column.setWidth(100);
column.setResizable(true);
column.setMoveable(true);
tableCol.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
DataRow r = (DataRow) element;
DataCell c = r.getDataCellByName(dataColumnHeader.getName());
if (c != null && c.getValue() != null) {
return c.getValue().toString();
}
return null;
}
#Override
public Image getImage(Object element) {
//Add my imgae
}
});
editingSupport = new StringCellEditingSupport(this, dataColumnHeader);
tableCol.setEditingSupport(editingSupport);
super.inputChanged(input, oldInput);
}

I don't know exactly what "redundant" column you're reffering to, but maybe you haven't disposed it properly (if you're saying they are created dynamically).
If I were you, I would add them differently.
private void createColumns()
{
// First, dipose any previously created columns
for (TableColumn column : table.getColumns())
column.dispose();
// Then recreate them
for (MyColumnPO col : getColumns())
{
TableColumn newCol = new TableColumn(table, SWT.NONE);
newCol.setText( col.text );
newCol.setWidth( col.width );
}
}
MyColumnPO would be a POJO which stands for "My Column Presentation Object". This contains info about your columns (text, width, tooltip).
Now, in the getColumns() method, you add/create/delete/update desired columns, instantiating MyColumnPO objects, and adding them to a List which you will return.
Each time you need to re-create the columns dynamically, you call createColumns().

Related

How to trigger EditingSupport on TableViewer

I'm currently writing an application where I use a JFace TableViewer. There's a Button next to the table that adds a new item to it. The TableViewer has only one column in this example, but this column has an EditingSupport assigned to it.
That all works as expected. A new item is added to the table when I click the button and it's also selected automatically.
However, what I want to achieve is that the EditingSupport of this column is triggered for the new item, i.e. when a new item is added, the cell within the new row should automatically show the text input that shows up when you use the editing support.
How would I achieve that? Do I need to fake up a mouse event or is there something in the API that I'm missing?
Here's some example code that roughly shows the current state of the table
public static void main(String[] args)
{
final Display d = new Display();
Shell s = new Shell(d);
s.setLayout(new FillLayout());
List<Project> projects = new ArrayList<>();
Table table = new Table(s, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
table.setHeaderVisible(true);
TableViewer viewer = new TableViewer(table);
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setInput(projects);
TableViewerColumn nameColumn = new TableViewerColumn(viewer, SWT.NONE);
nameColumn.getColumn().setText("Project name");
nameColumn.setLabelProvider(new ColumnLabelProvider()
{
#Override
public String getText(Object element)
{
Project p = (Project) element;
return p.name;
}
});
// Add the editing support
nameColumn.setEditingSupport(new ProjectNameEditingSupport(viewer));
// Button to add new item
Button add = new Button(s, SWT.PUSH);
add.setText("Add");
add.addListener(SWT.Selection, e -> {
// Create the new item
Project project = new Project("Project");
projects.add(project);
// Refresh the table
viewer.refresh();
// Select the item
viewer.setSelection(new StructuredSelection(project), true);
// TODO: Trigger editing support
});
for (TableColumn c : viewer.getTable().getColumns())
c.pack();
s.pack();
s.open();
s.setSize(300, 400);
while (!s.isDisposed())
{
if (!d.readAndDispatch())
d.sleep();
}
d.dispose();
}
private static class Project
{
private String name;
public Project(String name)
{
this.name = name;
}
}
public static class ProjectNameEditingSupport extends EditingSupport
{
private final TableViewer viewer;
private final CellEditor editor;
public ProjectNameEditingSupport(TableViewer viewer)
{
super(viewer);
this.viewer = viewer;
this.editor = new TextCellEditor(viewer.getTable());
}
#Override
protected CellEditor getCellEditor(Object element)
{
return editor;
}
#Override
protected boolean canEdit(Object element)
{
return true;
}
#Override
protected Object getValue(Object element)
{
return ((Project) element).name;
}
#Override
protected void setValue(Object element, Object userInputValue)
{
((Project) element).name = String.valueOf(userInputValue);
viewer.update(element, null);
}
}
IIRC you can use ColumnViewer::editElement in order to activate the editing control. The first method argument is the element that should be edited, the second argument is the index of the column on which the editor should be opened.
For example:
viewer.editElement( project, 0 );

Eclipse RCP tableViewer not displaying correctly

I have two jface TableViewers in my view, both defined two occupy the same amount of space vertically, or in other words, both defined to grab the Excess vertical space and to FILL the vertical alignment.
This way, the view is correctly displayed, in a small screen the table with more input gets more space, however, in a bigger screen both tables get the same amount of space, that's fine:
However, since the input from the bottom table is the same everytime, what I really want is to make the bottom table to get only the amount of space necessary to display that input.. But I can't do it, I set the bottom table to not grab the excess vertical alignement, but what it does is this:
And then.. When I resize the window.. BAM, it displays correctly:
I can't understand this behavior.. Can somebody help?
This is my code:
private void createTableViewers(Composite parent) {
// TABLE 1
Composite compositeTableImpostos = new Composite(parent, SWT.NONE);
compositeTableImpostos.setLayout(new FillLayout());
compositeTableImpostos.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
tableImpostos = createTableViewer(compositeTableImpostos,
InterfaceVARS.REGISTOCOLABORADORES_TABLEVIEWER_COLUMNSTYLE,
LabelVARS.REGISTOCOLABORADORES_TABLEVIEWER_COLUMN_TITLES,
InterfaceVARS.REGISTOCOLABORADORES_TABLEVIEWER_COLUMNSIZE,
InterfaceVARS.STYLE_TABLE_SINGLE);
tableImpostos.setContentProvider(contentProvider = new ImpostosContentProvider(tableImpostos));
tableImpostos.setLabelProvider(new ImpostosLabelProvider());
// TABLE 2
Composite compositeTableLinhasDespesa = new Composite(parent, SWT.NONE);
compositeTableLinhasDespesa.setLayout(new FillLayout());
final GridData gridData2 = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
compositeTableLinhasDespesa.setLayoutData(gridData2);
tableLinhasDespesa = createTableViewer(compositeTableLinhasDespesa,
InterfaceVARS.REGISTODESPESAS_TABLEVIEWER_COLUMNSTYLE,
LabelVARS.REGISTODESPESA_TABLEVIEWER_COLUMN_TITLES,
InterfaceVARS.REGISTODESPESAS_TABLEVIEWER_COLUMNSIZE,
InterfaceVARS.STYLE_TABLE_MULTI);
tableLinhasDespesa.setContentProvider(linhasContentProvider = new LinhasDespesaContentProvider(tableLinhasDespesa, contentProvider));
tableLinhasDespesa.setLabelProvider(new LinhasDespesaLabelProvider());
}
public class CustomTableViewer {
//Viewer
private TableViewer tableViewer;
private TableColumnLayout tableViewerLayout;
//Columns
private String titles[];
private int columnSize[];
private int columnStyle[];
public CustomTableViewer(Composite composite, int[] columnStyle, String titles[], int[] columnSize, int STYLE){
this.titles = titles;
this.columnStyle = columnStyle;
this.columnSize = columnSize;
tableViewerLayout = new TableColumnLayout();
Composite compositeTable = new Composite(composite, SWT.NONE);
compositeTable.setLayout(tableViewerLayout);
tableViewer = new TableViewer(compositeTable, STYLE);
Table table = tableViewer.getTable();
table.setLinesVisible(true);
table.setHeaderVisible(true);
addTableViewerColumns();
addTableViewerListeners();
}
private void addTableViewerColumns() {
for(int index=0 ; index<titles.length ; index++)
createTableColumn(columnStyle[index], titles[index], columnSize[index], columnSize[index], true, true);
}
private TableViewerColumn createTableColumn(int STYLE, String title, int weight, int minWidth, boolean moveable, boolean resizable) {
TableViewerColumn viewerColumn = new TableViewerColumn(tableViewer, STYLE);
TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setMoveable(moveable);
tableViewerLayout.setColumnData(column, new ColumnWeightData(weight, minWidth, resizable));
return viewerColumn;
}
public void addTableViewerListeners() {
tableViewer.getTable().addControlListener(new ResizeListener(tableViewer));
}
public TableViewer getTableViewer(){
return tableViewer;
}
public class ResizeListener implements ControlListener {
private TableViewer tableViewer;
public ResizeListener(TableViewer tableViewer) {
this.tableViewer = tableViewer;
}
#Override
public void controlMoved(ControlEvent e) {
}
#Override
public void controlResized(ControlEvent e) {
TableColumn[] colunas = tableViewer.getTable().getColumns();
for(int i=0; i<colunas.length; i++) {
tableViewerLayout.setColumnData(colunas[i], new ColumnWeightData(
columnSize[i],columnSize[i],
true));
}
}
}
}
Calling the method layout(new Control[] {tableViewer2.getControl()}) in the parent composite of the tables after setInput() was called did the job!

how to select entire tableviewer row when checkbox clicked (first column of the table has checkboxes in each row)

am beginner to SWT, anyone please help,
my problem is:
i have a table, which has 10 Columns,
the first column has Check box and the rest of the column are filled from Database,
when i check the checkbox i want that perticular row to be selected,
i am pasting my table code below,
public static void main(String arg[])
{
// shell and display declared here
mainTable = new TableViewer(content, SWT.H_SCROLL| SWT.V_SCROLL | SWT.BORDER |SWT.DM_FILL_BACKGROUND|SWT.FULL_SELECTION);
mainTable .getTable().setHeaderVisible(true);
mainTable .getTable().setLinesVisible(true);
mainTable .setContentProvider(new ArrayContentProvider());
// COLUM FOR PLACING THE CHECK BOXES
TableColumn columncOL=new TableColumn(mainTable .getTable(),SWT.NONE);
columncOL.setText("");
columncOL.setWidth(40);
TableViewerColumn columnaC=new TableViewerColumn(mainTable ,columncOL);
columnaC.setLabelProvider(new ColumnLabelProvider(){
Map<Object, Button> buttons = new HashMap<Object, Button>();
#Override
public void update(ViewerCell cell) {
TableItem item = (TableItem) cell.getItem();
Button button;
if(buttons.containsKey(cell.getElement()))
{
button = buttons.get(cell.getElement());
}
else
{
button = new Button((Composite) cell.getViewerRow().getControl(),SWT.CHECK);
String s = "Item 1";
button.setData(s, "Some other info or object here");
s = "Item 2";
button.setData(s, "This is item two");
//buttons.put(cell.getElement(), button);
}
TableEditor editor = new TableEditor(item.getParent());
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(button , item, cell.getColumnIndex());
editor.layout();
}
});
// CREATING 1st COLUMNS
TableColumn column1Head=new TableColumn(mainTable.getTable(),SWT.NONE);
column1Head.setText("col1");
column1Head.setWidth(200);
// setting column input
TableViewerColumn column1=new TableViewerColumn(mainTable,column1Head);
column1.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
Student ap=(Student )Element;
return ap.col1();
}
});
}
like this am creating remaing 8 columns
i want to select the entire row when a perticluar check box checked .
any one pleeeease help me As early as possible....
Use CheckboxTableViewer to show a table with check boxes:
mainTable = CheckboxTableViewer.newCheckList(content, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
To select the line when a check box is ticked you will need to use addCheckStateListener to select the checked row, something like:
mainTable.addCheckStateListener(new ICheckStateListener()
{
#Override
public void checkStateChanged(CheckStateChangedEvent event)
{
if (event.getChecked())
mainTable.setSelection(new StructuredSelection(event.getObject()));
}
});
Easy way :first column of the table has checkboxes in each row can
selected or not
CheckboxTableViewer tableViewer = CheckboxTableViewer.newCheckList(parent, SWT.BORDER | SWT.FULL_SELECTION);
Table table = tableViewer.getTable();
table.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event e) {
Table table = (Table) e.widget;
TableItem item = table.getItem(table.getSelectionIndex());
for (int col = 0; col < table.getColumnCount(); col++)
{
//Table_Column Checked or Not
if(item.getChecked())
//return true
//all ready checked(true) to change unchecked(false)
item.setChecked(false);
else
//unchecked(false) to checked(true) each row
item.setChecked(true);
}
}
}
this is useful for you....thanks

Listening to many JTextFields and calculate value sum in a Row

I have an application that gets input from user;
it has 8 rows of JTextFields with 3 columns:
+-----------+-----------+-----------+
| Field 1-1 | Field 1-2 | Field 1-3 |
+-----------+-----------+-----------+
| Field 2-1 | Field 2-2 | Field 2-3 |
+-----------+-----------+-----------+
| Field 3-1 | Field 3-2 | Field 3-3 |
+-----------+-----------+-----------+
In each row while user changes first or second field the sum of new values must be written in third field.
For example when user changes Filed 1-1 & Field 1-2 sum of them must be calculated and shown in Field 1-3 and so on for other rows.
I wrote a Class that implements DocumentListener and and named it listenerClass & called .getDocument().addDocumentListener(new listenerClass) for all of JTextFields in column 1 & 2 ;
Now in listenerClass I need to know which JTextField called listenerClass to be able determine wich fields must be added and result must be written in which JTextField.
How Can I find out which JTextField called DocumentListener ?
Is there any better method to do this?
Thanks
You have two options here:
brute force: just one listener instance that will compute 8 sums and update 8 text fields
smart: pass to your listener class constructor 3 text fields and then instantiate a differente listener for each row
put a property with putClientProperty method on each JTextField. You can use that property as an id, and get it back inside the listener.
For example:
JTextField 1_1 = new JTextField();
1_1.putClientProperty("id", "1_1");
EDIT:
Sorry, I was forgetting that you don't have a reference to source object inside listener. SO it's better also do:
JTextField 1_1 = new JTextField();
1_1.getDocument.putProperty("source", 1_1);
the from inside the listener you can do:
public void insertUpdate(DocumentEvent documentEvent) {
//source
Object source = documentEvent.getDocument().getProperty("source");
if (source instanceof JTextField){
JTextField field = (JTextField)source;
String id = field.getClientProperty("id");
}
}
I asked a similar question some months ago: have a look here.
consider using JTable instead of plenty of JTextFields or JFormattedTextFields and listening by some of Listeners
from code
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);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
#Override
public void tableChanged(TableModelEvent e) {
System.out.println(e.getSource());
if (e.getType() == TableModelEvent.UPDATE) {
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);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TableProcessing frame = new TableProcessing();
}
});
}
}
Use yourTextField.setName("Alice"), then in your DocumentListener implementation retrieve the name with with getName() and check for "Alice".
These methods belong to the java.awt.Component class. Every swing JComponent extends from it.

How can I put a "(de)select all" check box in an SWT Table header?

I have an SWT Table that I'm instantiating with the SWT.CHECK style in order to display a check box next to every row. My users have requested another check box in the header row of the table in order to allow them to select/deselect all the rows with one click.
I can't see any obvious way to do it, and I've only found Swing/JTable examples through Google. Does anyone know how to do this? I'm hoping it's possible without re-implementing Table or falling back on a header context menu.
Just create two images of check box. First one without a tick and second one having a tick.Now add the first image to the tableColumn header. After that add listener to tableColumn in such a way that when you click button for the first time, table.selectALL() method should be fired along with changing the tableColumn header image to second one. When you click button again call table.deSelectAll() method and replace the tableColumn header with the first image.
You can use this condition:
When the checkbox(image) is clicked, use a for loop to check whether,
any of the checkboxes in the table is checked. if anyone is found
checked then fire table.deSelectAll() method , else fire
table.selectAll() method.
There will not be any problem for the "checkbox" during table/widow resizing.
tableColumn0.addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
// TODO Auto-generated method stub
boolean checkBoxFlag = false;
for (int i = 0; i < table.getItemCount(); i++) {
if (table.getItems()[i].getChecked()) {
checkBoxFlag = true;
}
}
if (checkBoxFlag) {
for (int m = 0; m < table.getItemCount(); m++) {
table.getItems()[m].setChecked(false);
tableColumn0.setImage(new Image(Display.getCurrent(),
"images/chkBox.PNG"));
table.deselectAll();
}
} else {
for (int m = 0; m < table.getItemCount(); m++) {
table.getItems()[m].setChecked(true);
tableColumn0.setImage(new Image(Display.getCurrent(),
"images/chkBox2.PNG"));
table.selectAll();
}
}
}
});
You could use a FormLayout to allow stacking objects, then add a checkbox on top of the table as follows:
FormData fd = new FormData();
fd.left = new FormAttachment(table, 5, SWT.LEFT);
fd.top = new FormAttachment(table, 5, SWT.TOP);
checkbox.setLayoutData(fd);
checkbox.moveAbove(table);
You might find it useful for correctly aligning the checkbox to obtain the height of the table header row with table.getHeaderHeight().
Fully describe this code :: de)select all” check box in an SWT Table
header
public class TaskView extends ViewPart {
public static TableItem std_item;
public static List<Student> std=new ArrayList<Student>();
public static Table table;
private TableColumn col_name_add;
private TableColumn col_image_add;
static int countcheck;
static int staticno=1;
static int check=0,uncheck=0;
public TaskView() {
setTitleImage(ResourceManager.getPluginImage("RCP_Demo", "icons/Tasksview.png"));
}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(null);
////////// Table Create
table = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION|SWT.CHECK|SWT.CENTER);
////SWT.CHECK: Display first column check box
table.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
TableItem item = table.getItem(table.getSelectionIndex());
for(int col=1;col<table.getColumnCount();col++)
{
//Table_Column Checked or Not
if(item.getChecked())
item.setChecked(false);
else
item.setChecked(true);
/////////First column value get
if(col==1)
{
System.out.println(item.getText(col));
}
TableItem[] itemCheck = table.getItems();
for(int i=0;i<table.getItemCount();i++)
{
if(itemCheck[i].getChecked())
++check;
else
++uncheck;
}
if(check==table.getItemCount())
//Change column image:Checkbox checked
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/check.png"));
else
//Change column image:Checkbox Unchecked
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/uncheck.png"));
//System.out.println("Check:"+check+"uncheck"+uncheck);
check=0;
uncheck=0;
}
}
});
table.setBounds(10, 10, 343, 297);
table.setHeaderVisible(true);
table.setLinesVisible(true);
////// SWT Table header Column
col_image_add = new TableColumn(table, SWT.LEFT);
col_image_add.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//All Row selected or Not
//column Icon change checked(selected) or not
System.out.println("Total Row Count:"+table.getItemCount());
TableItem item[] = table.getItems();
if(staticno==1)
{
for(int i=0;i<table.getItemCount();i++)
{
item[i].setChecked(true);
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/check.png"));
}
staticno=0;
}else
{
for(int i=0;i<table.getItemCount();i++)
{
item[i].setChecked(false);
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/uncheck.png"));
}
staticno=1;
}
}
}
});
col_image_add.setMoveable(true);
col_image_add.setToolTipText("Click");
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/uncheck.png"));
col_image_add.setWidth(36);
//Dynamic column Name add
String[] Col_names={"Stud_id","Stud_Name","Stud_Gender"};
for(int i=0;i<Col_names.length;i++)
{
col_name_add = new TableColumn(table,SWT.CENTER);
col_name_add.setWidth(100);
col_name_add.setText(Col_names[i]);
}
}
public TableViewer getViewer() {
return null;
}
}
thanks....

Categories