Related
I have a VerticalTextPainter for my column headers.
I would like to set the column header height to the maximum of all column heights.
If I set setCalculateByTextHeight(true) and setCalculateByTextLength(true) it will resize the columns as I scroll to the maximum of what is currently displayed. Instead I would like it to resize to the maximum of all columns and allow the user to change the widths/heights after.
Is it possible to get the maximum height of all column headers?
Update
I've tried removing calculating using text height/lengths and adding InitializeAutoResizeColumnsCommand. This makes the column header height be very small and only show "...".
this is the NatTable.
for (int i = 0; i < getColumnCount(); i++) {
InitializeAutoResizeColumnsCommand columnCommand = new InitializeAutoResizeColumnsCommand(this, i,
getConfigRegistry(), new GCFactory(this));
doCommand(columnCommand);
}
for (int i = 0; i < getRowCount(); i++) {
InitializeAutoResizeRowsCommand rowCommand = new InitializeAutoResizeRowsCommand(this, i,
getConfigRegistry(), new GCFactory(this));
doCommand(rowCommand);
}
Full Example (With a composite layer for columns)
I've created an example with a VerticalTextPainter for the column headers. I added a listener to resize the columns when the table is first painted.
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.convert.DefaultDisplayConverter;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DummyBodyDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayerTransform;
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.LabelStack;
import org.eclipse.nebula.widgets.nattable.layer.cell.IConfigLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.painter.cell.CellPainterWrapper;
import org.eclipse.nebula.widgets.nattable.painter.cell.ICellPainter;
import org.eclipse.nebula.widgets.nattable.painter.cell.TextPainter;
import org.eclipse.nebula.widgets.nattable.painter.cell.VerticalTextPainter;
import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.CustomLineBorderDecorator;
import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.LineBorderDecorator;
import org.eclipse.nebula.widgets.nattable.painter.cell.decorator.PaddingDecorator;
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
import org.eclipse.nebula.widgets.nattable.resize.MaxCellBoundsHelper;
import org.eclipse.nebula.widgets.nattable.resize.command.MultiRowResizeCommand;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.style.BorderStyle;
import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum;
import org.eclipse.nebula.widgets.nattable.style.Style;
import org.eclipse.nebula.widgets.nattable.style.VerticalAlignmentEnum;
import org.eclipse.nebula.widgets.nattable.util.GCFactory;
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class ExampleNatTable {
private BodyLayerStack bodyLayer;
private int statusColumn;
private int statusRejected;
private int statusInProgress;
private boolean check = false;
private NatTable nattable;
private String[] summaryProperties;
private String[] properties;
private static final String FOO_LABEL = "FOO";
private static final String CELL_LABEL = "Cell_LABEL";
public static void main(String[] args) {
new ExampleNatTable();
}
public ExampleNatTable() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
summaryProperties = new String[3];
for (int i = 0; i < summaryProperties.length; i++) {
summaryProperties[i] = "s" + i;
}
properties = new String[3];
for (int i = 0; i < properties.length; i++) {
properties[i] = "Column" + i;
}
// Setting the data layout layer
GridData gridData = new GridData();
gridData.heightHint = 1;
gridData.widthHint = 1;
IConfigRegistry configRegistry = new ConfigRegistry();
// Body Data Provider
IDataProvider dataProvider = new DataProvider(properties.length, 55);
bodyLayer = new BodyLayerStack(dataProvider);
// datalayer.addConfiguration(new
// Column Data Provider
DefaultColumnHeaderDataProvider columnSummaryData = new DefaultColumnHeaderDataProvider(summaryProperties);
DefaultColumnHeaderDataProvider columnData = new DefaultColumnHeaderDataProvider(properties);
ColumnHeaderLayerStack columnSummaryLayer = new ColumnHeaderLayerStack(columnSummaryData);
ColumnHeaderLayerStack columnlayer = new ColumnHeaderLayerStack(columnData);
/**
* Composite layer
*/
final CompositeLayer columnCompositeLayer = new CompositeLayer(1, 2);
columnCompositeLayer.setChildLayer("SUMMARY_REGION", columnSummaryLayer, 0, 0);
columnCompositeLayer.setChildLayer("COLUMNS", columnlayer, 0, 1);
// Row Data Provider
DefaultRowHeaderDataProvider rowdata = new DefaultRowHeaderDataProvider(dataProvider);
RowHeaderLayerStack rowlayer = new RowHeaderLayerStack(rowdata);
// Corner Data Provider
DefaultCornerDataProvider cornerdata = new DefaultCornerDataProvider(columnData, rowdata);
DataLayer cornerDataLayer = new DataLayer(cornerdata);
CornerLayer cornerLayer = new CornerLayer(cornerDataLayer, rowlayer, columnCompositeLayer);
GridLayer gridlayer = new GridLayer(bodyLayer, columnCompositeLayer, rowlayer, cornerLayer);
nattable = new NatTable(shell, gridlayer, false);
// Change for paint
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
// #Override
#Override
public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) {
int columnIndex = bodyLayer.getColumnIndexByPosition(columnPosition);
int rowIndex = bodyLayer.getRowIndexByPosition(rowPosition);
if (columnIndex == 2 && rowIndex == 45) {
configLabels.addLabel(FOO_LABEL);
} else if ((columnIndex == statusColumn) && (rowIndex == statusRejected) && (check == true)) {
configLabels.addLabel(CELL_LABEL);
}
}
};
bodyLayer.setConfigLabelAccumulator(cellLabelAccumulator);
// nattable.addConfiguration(new DefaultNatTableStyleConfiguration());
nattable.addConfiguration(new AbstractRegistryConfiguration() {
// #Override
#Override
public void configureRegistry(IConfigRegistry configRegistry) {
/**
* Column Header
*/
final Style columnHeaderStyle = new Style();
columnHeaderStyle.setAttributeValue(CellStyleAttributes.VERTICAL_ALIGNMENT,
VerticalAlignmentEnum.BOTTOM);
columnHeaderStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT,
HorizontalAlignmentEnum.CENTER);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, columnHeaderStyle,
DisplayMode.NORMAL, GridRegion.COLUMN_HEADER);
final VerticalTextPainter columnHeaderPainter = new VerticalTextPainter(false, true, false);
Display display = Display.getCurrent();
Color blue = display.getSystemColor(SWT.COLOR_BLUE);
final CellPainterWrapper columnHeaderDecorator = new CustomLineBorderDecorator(
new PaddingDecorator(columnHeaderPainter, 3, 0, 3, 0),
new BorderStyle(1, blue, BorderStyle.LineStyleEnum.SOLID));
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, columnHeaderDecorator,
DisplayMode.NORMAL, GridRegion.COLUMN_HEADER);
/**
* Cells
*/
final Color bgColor = GUIHelper.COLOR_WHITE;
final Color fgColor = GUIHelper.COLOR_BLACK;
final Color gradientBgColor = GUIHelper.COLOR_WHITE;
final Color gradientFgColor = GUIHelper.getColor(136, 212, 215);
final Font font = GUIHelper.DEFAULT_FONT;
final HorizontalAlignmentEnum hAlign = HorizontalAlignmentEnum.CENTER;
final VerticalAlignmentEnum vAlign = VerticalAlignmentEnum.MIDDLE;
final BorderStyle borderStyle = null;
final ICellPainter cellPainter = new LineBorderDecorator(new TextPainter(false, true, 5, true));
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, cellPainter);
Style cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, bgColor);
cellStyle.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, fgColor);
cellStyle.setAttributeValue(CellStyleAttributes.GRADIENT_BACKGROUND_COLOR, gradientBgColor);
cellStyle.setAttributeValue(CellStyleAttributes.GRADIENT_FOREGROUND_COLOR, gradientFgColor);
cellStyle.setAttributeValue(CellStyleAttributes.FONT, font);
cellStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, hAlign);
cellStyle.setAttributeValue(CellStyleAttributes.VERTICAL_ALIGNMENT, vAlign);
cellStyle.setAttributeValue(CellStyleAttributes.BORDER_STYLE, borderStyle);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle);
configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER,
new DefaultDisplayConverter());
}
});
nattable.setLayoutData(gridData);
nattable.setConfigRegistry(configRegistry);
nattable.configure();
nattable.addListener(SWT.Paint, new Listener() {
boolean resized = false;
#Override
public void handleEvent(Event arg0) {
if (resized) {
return;
}
resized = true;
int[] gridRowHeights = MaxCellBoundsHelper.getPreferredRowHeights(nattable.getConfigRegistry(),
new GCFactory(nattable), nattable, new int[] {
0
});
if (gridRowHeights != null) {
nattable.doCommand(new MultiRowResizeCommand(nattable, new int[] {
0
}, gridRowHeights));
nattable.doCommand(new MultiRowResizeCommand(columnlayer, new int[] {
0
}, gridRowHeights));
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public class DataProvider extends DummyBodyDataProvider {
public DataProvider(int columnCount, int rowCount) {
super(columnCount, rowCount);
}
#Override
public int getColumnCount() {
return properties.length;
}
#Override
public Object getDataValue(int columnIndex, int rowIndex) {
return new String("" + columnIndex + ":" + rowIndex);
}
#Override
public int getRowCount() {
return 55;
}
#Override
public void setDataValue(int arg0, int arg1, Object arg2) {
}
}
public class BodyLayerStack extends AbstractLayerTransform {
private SelectionLayer selectionLayer;
public BodyLayerStack(IDataProvider dataProvider) {
DataLayer bodyDataLayer = new DataLayer(dataProvider);
ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(bodyDataLayer);
ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
this.selectionLayer = new SelectionLayer(columnHideShowLayer);
ViewportLayer viewportLayer = new ViewportLayer(this.selectionLayer);
setUnderlyingLayer(viewportLayer);
}
public SelectionLayer getSelectionLayer() {
return this.selectionLayer;
}
}
public class ColumnHeaderLayerStack extends AbstractLayerTransform {
public ColumnHeaderLayerStack(IDataProvider dataProvider) {
DataLayer dataLayer = new DataLayer(dataProvider);
ColumnHeaderLayer colHeaderLayer = new ColumnHeaderLayer(dataLayer, ExampleNatTable.this.bodyLayer,
ExampleNatTable.this.bodyLayer.getSelectionLayer());
setUnderlyingLayer(colHeaderLayer);
}
}
public class RowHeaderLayerStack extends AbstractLayerTransform {
public RowHeaderLayerStack(IDataProvider dataProvider) {
DataLayer dataLayer = new DataLayer(dataProvider, 50, 20);
RowHeaderLayer rowHeaderLayer = new RowHeaderLayer(dataLayer, ExampleNatTable.this.bodyLayer,
ExampleNatTable.this.bodyLayer.getSelectionLayer());
setUnderlyingLayer(rowHeaderLayer);
}
}
}
It sounds like you need an initial auto resize instead of the automatic size configuration.
Have a look at our FAQ section how you can trigger an auto resize. Then of course you need to disable the painter calculate mechanism.
https://www.eclipse.org/nattable/documentation.php?page=faq
For the column header the described mechanism does not work, as the InitializeAutoResizeRowsCommandHandler is registered on the SelectionLayer and for the column header there is no SelectionLayer.
With the 1.6 API you could simply execute this to auto resize the column header row:
this.nattable.doCommand(new AutoResizeRowsCommand(this.nattable, 0));
With an older API you will need to copy the implementation code, as there is no way to avoid the position transformation, and therefore things won't work:
int[] gridRowHeights = MaxCellBoundsHelper.getPreferredRowHeights(
this.nattable.getConfigRegistry(),
new GCFactory(this.nattable),
this.nattable,
new int[] { 0 });
if (gridRowHeights != null) {
this.nattable.doCommand(
new MultiRowResizeCommand(this.nattable, new int[] { 0 }, gridRowHeights, true));
}
In a composition the solution for versions < 1.6 the resize command needs to be calculated and triggered for each row, as the command needs to be transported to the lowest layer in the stack. For the above example it should look like this:
int[] gridRowHeights1 = MaxCellBoundsHelper.getPreferredRowHeights(
ExampleNatTable.this.nattable.getConfigRegistry(),
new GCFactory(ExampleNatTable.this.nattable),
ExampleNatTable.this.nattable,
new int[] { 0 });
int[] gridRowHeights2 = MaxCellBoundsHelper.getPreferredRowHeights(
ExampleNatTable.this.nattable.getConfigRegistry(),
new GCFactory(ExampleNatTable.this.nattable),
ExampleNatTable.this.nattable,
new int[] { 1 });
if (gridRowHeights1 != null) {
ExampleNatTable.this.nattable.doCommand(
new MultiRowResizeCommand(
ExampleNatTable.this.nattable,
new int[] { 0 },
gridRowHeights1));
}
if (gridRowHeights2 != null) {
ExampleNatTable.this.nattable.doCommand(
new MultiRowResizeCommand(
ExampleNatTable.this.nattable,
new int[] { 1 },
gridRowHeights2));
}
I am using saveState method of viewPart to save my view state.Below is my code for saving data in my viewPart.
package view;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import tutogef.model.Connection;
import tutogef.model.Node;
import tutogef.model.Service;
import tutogef.xml.ThreatTypeXMLToObject;
public class Theartview extends ViewPart implements Serializable {
private static final long serialVersionUID = -3033215443267698138L;
public static String ID = "TutoGEF.theartview_id";
public static String ID1 = "TutoGEF.theartview_id1";
private Table table;
private String Theart_Name;
private String Category_Name;
private String Status_Name;
private String Priority_Name;
private String Descrption_Name;
private String Justification_Name;
private static Node sourceNode;
private static Node targetNode;
private static String connectionType;
private String shortDescription;
private String category;
private String description;
private ThreatTypeXMLToObject threattypexmltoobject;
private Connection conn;
private Text text_1, text_2, text_3, text_4;
private ArrayList<String> list1 = new ArrayList<>();
private HashMap<Integer, String> list2 = new HashMap<>();
// HashMap<Integer, String> list3 = new HashMap<>();
private static Integer a = 0;
private IMemento memento;
// String Key = "Key";
// String Key1 = "Key1";
// String Key2 = "Key2";
// String Key3 = "Key3";
// String Key4 = "Key4";
// String Key5 = "Key5";
// String Key6 = "Key6";
String[] keyValues = { "KeyValue1", "KeyValue2", "KeyValue3", "KeyValue4",
"KeyValue5", "KeyValue6" };
#SuppressWarnings("static-access")
public void getDataOfConnection(Node sourceNode, Node targetNode,
String connectionType1) {
this.sourceNode = sourceNode;
this.targetNode = targetNode;
this.connectionType = connectionType1;
}
public Theartview() {
}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(10, false));
table = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 10, 1));
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = { "Theart Name", "Category", "Satus", "Priority",
"Description", "Justification" };
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setWidth(150);
column.setText(titles[i]);
}
if (memento != null) {
System.out.println("Entering Restore State");
restoreState(memento);
}
memento = null;
}
void restoreState(IMemento memento) {
System.out.println("Restore State Entered");
IMemento[] mems = memento.getChildren(ID1);
System.out.println(mems);
for (int q = 0; q < mems.length; q+=3) {
System.out.println("Enter: -----------------------------");
IMemento mem = mems[q];
System.out.println(mems.length);
System.out.println(q);
System.out.println(mem);
TableItem item = new TableItem(table, SWT.NONE);
// for Theart_Name
TableEditor editor = new TableEditor(table);
Text text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 0);
text.setText(mem.getString(keyValues[q]));
Theart_Name = text.getText().toString().trim();
// For Category_Name
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 1);
text.setText(mem.getString(keyValues[q + 1]));
Category_Name = text.getText().toString().trim();
// For Status_Name
editor = new TableEditor(table);
final Combo Status_Combo = new Combo(table, SWT.READ_ONLY);
Status_Combo.add("Mitigated");
Status_Combo.add("Not Applicable");
Status_Combo.add("Not Started");
Status_Combo.add("Needs Investigation");
editor.grabHorizontal = true;
editor.setEditor(Status_Combo, item, 2);
Status_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
}
});
// For Priority_Name
editor = new TableEditor(table);
final Combo priority_Combo = new Combo(table, SWT.NONE);
priority_Combo.add("High");
priority_Combo.add("Medium");
priority_Combo.add("Low");
editor.grabHorizontal = true;
editor.setEditor(priority_Combo, item, 3);
priority_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
}
});
// For Descrption_Name
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 4);
text.setText(mem.getString(keyValues[q + 2]));
Descrption_Name = text.getText().toString().trim();
// For justification
editor = new TableEditor(table);
text = new Text(table, SWT.MULTI | SWT.BORDER | SWT.WRAP
| SWT.V_SCROLL);
editor.grabHorizontal = true;
editor.setEditor(text, item, 5);
Justification_Name = text.getText().toString().trim();
}
}
#SuppressWarnings("static-access")
public void fillTableRoWData() {
if (Connection.Number_Of_Connection != 0) {
// item = new TableItem(table, SWT.NONE);
if (Service.class.isInstance(sourceNode)) {
String id = "S1";
shortDescription = threattypexmltoobject.shortdescription(id,
sourceNode.getName(), targetNode.getName(), null);
category = "Spoofing";
description = threattypexmltoobject.longdescription(id,
sourceNode.getName(), targetNode.getName(), null);
fillRows(shortDescription, category, description);
}
if (Service.class.isInstance(sourceNode)
&& (connectionType == Connection.CONNECTION_DESIGN)) {
String id = "T1";
System.out.println(conn.getConnectionDesign());
shortDescription = threattypexmltoobject.shortdescription(id,
sourceNode.getName(), targetNode.getName(),
conn.getConnectionDesign());
category = "Tampering";
description = threattypexmltoobject.longdescription(id,
sourceNode.getName(), targetNode.getName(),
conn.getConnectionDesign());
fillRows(shortDescription, category, description);
}
}
System.out.println("Hash Map" + list2);
System.out.println("List : []" + list1);
}
#Override
public void setFocus() {
}
private void fillRows(String shortdesc, String categ, String descp) {
TableItem item = new TableItem(table, SWT.NONE);
// for Threat_Name
TableEditor editor = new TableEditor(table);
text_1 = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text_1, item, 0);
text_1.setText(shortdesc);
text_1.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent e) {
System.out.println("Modify Text");
Text text = (Text) e.widget;
System.out.println(text.getText());
}
});
Theart_Name = text_1.getText().toString().trim();
list1.add(Theart_Name);
list2.put(a, Theart_Name);
// For Category_Name
editor = new TableEditor(table);
text_2 = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text_2, item, 1);
text_2.setText(categ);
Category_Name = text_2.getText().toString().trim();
list1.add(Category_Name);
list2.put(++a, Category_Name);
// For Status_Name
editor = new TableEditor(table);
final Combo Status_Combo = new Combo(table, SWT.READ_ONLY);
Status_Combo.add("Mitigated");
Status_Combo.add("Not Applicable");
Status_Combo.add("Not Started");
Status_Combo.add("Needs Investigation");
editor.grabHorizontal = true;
editor.setEditor(Status_Combo, item, 2);
Status_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
list1.add(Status_Name);
list2.put(++a, Status_Name);
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(Status_Combo.getText());
Status_Name = Status_Combo.getText();
}
});
// For Priority_Name
editor = new TableEditor(table);
final Combo priority_Combo = new Combo(table, SWT.NONE);
priority_Combo.add("High");
priority_Combo.add("Medium");
priority_Combo.add("Low");
editor.grabHorizontal = true;
editor.setEditor(priority_Combo, item, 3);
priority_Combo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
list1.add(Priority_Name);
list2.put(++a, Priority_Name);
}
public void widgetDefaultSelected(SelectionEvent e) {
System.out.println(priority_Combo.getText());
Priority_Name = priority_Combo.getText();
}
});
// For Descrption_Name
editor = new TableEditor(table);
text_3 = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text_3, item, 4);
text_3.setText(descp);
Descrption_Name = text_3.getText().toString().trim();
list1.add(Descrption_Name);
list2.put(++a, Descrption_Name);
// For justification
editor = new TableEditor(table);
text_4 = new Text(table, SWT.MULTI | SWT.BORDER | SWT.WRAP
| SWT.V_SCROLL);
editor.grabHorizontal = true;
editor.setEditor(text_4, item, 5);
Justification_Name = text_4.getText().toString().trim();
list1.add(Justification_Name);
list2.put(++a, Justification_Name);
}
#Override
public void saveState(IMemento memento) {
super.saveState(memento);
System.out.println("Save State Called");
IMemento mem = memento.createChild(ID1);
for (int i = 0; i < 6; i++) {
mem.putString(keyValues[i], list2.get(i));
System.out.println("Hash Map Values: [" + i + "] " + list2.get(i));
System.out.println(mem);
}
}
#Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
this.memento = memento;
System.out.println("Intialize the view");
}
}
Following problem occurs
1) When memento is initialized for the first time the code works properly. But when I open up my viewPart again without changing any data the error occurs.
2) I have stored all my values in hashmap. When I restore data I only get the first 3 values rest of the values does not appear. If I use numbers than all the data comes properly. Any solutions for that?
3) In my fillTableRoWData() method when the two if conditions are executed all my listeners stand at the second conditions only. How to move the listeners between two if conditions.
Use the org.eclipse.ui.elementFactories extension point and implement the createElement method of the IElementFactory interface which takes an IMemento object.
If you want to make the view Saveable then make the viewpart implement ISaveablePart
I want to have checkboxes in a combo(Drop down) so that I can select more than one elements of combo at once. Can this be done? If yes, can you please explain or provide any link if possible.
Thank you.
Original poster asked for a drop down list with multi-selection support as an alternative. Custom implementation of MultiSelectionCombo can serve this purpose.
Selected items are displayed in text field:
Drop down with multi-selection support http://s12.postimg.org/7ee1y6j5n/Multi_Selection_Combo.png
Keep Ctrl pressed to select multiple items:
Select multiple items in drop down http://s3.postimg.org/ufkezh99t/Items_selected.png
Get indices of selected items:
Get selected items http://s11.postimg.org/8n9fa7fb5/Get_selected_items.png
Implementation and demo of MultiSelectionCombo:
import java.util.Arrays;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class MultiSelectionCombo extends Composite {
Shell shell = null;
List list = null;
Text txtCurrentSelection = null;
String[] textItems = null;
int[] currentSelection = null;
public MultiSelectionCombo(Composite parent, String[] items, int[] selection, int style) {
super(parent, style);
currentSelection = selection;
textItems = items;
init();
}
private void init() {
GridLayout layout = new GridLayout();
layout.marginBottom = 0;
layout.marginTop = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginWidth = 0;
layout.marginHeight = 0;
setLayout(new GridLayout());
txtCurrentSelection = new Text(this, SWT.BORDER | SWT.READ_ONLY);
txtCurrentSelection.setLayoutData(new GridData(GridData.FILL_BOTH));
displayText();
txtCurrentSelection.addMouseListener(new MouseAdapter() {
#Override
public void mouseDown(MouseEvent event) {
super.mouseDown(event);
initFloatShell();
}
});
}
private void initFloatShell() {
Point p = txtCurrentSelection.getParent().toDisplay(txtCurrentSelection.getLocation());
Point size = txtCurrentSelection.getSize();
Rectangle shellRect = new Rectangle(p.x, p.y + size.y, size.x, 0);
shell = new Shell(MultiSelectionCombo.this.getShell(), SWT.NO_TRIM);
GridLayout gl = new GridLayout();
gl.marginBottom = 2;
gl.marginTop = 2;
gl.marginRight = 2;
gl.marginLeft = 2;
gl.marginWidth = 0;
gl.marginHeight = 0;
shell.setLayout(gl);
list = new List(shell, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
for (String value: textItems) {
list.add(value);
}
list.setSelection(currentSelection);
GridData gd = new GridData(GridData.FILL_BOTH);
list.setLayoutData(gd);
shell.setSize(shellRect.width, 100);
shell.setLocation(shellRect.x, shellRect.y);
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseUp(MouseEvent event) {
super.mouseUp(event);
currentSelection = list.getSelectionIndices();
if ((event.stateMask & SWT.CTRL) == 0) {
shell.dispose();
displayText();
}
}
});
shell.addShellListener(new ShellAdapter() {
public void shellDeactivated(ShellEvent arg0) {
if (shell != null && !shell.isDisposed()) {
currentSelection = list.getSelectionIndices();
displayText();
shell.dispose();
}
}
});
shell.open();
}
private void displayText() {
if (currentSelection != null && currentSelection.length > 0) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < currentSelection.length; i++) {
if (i > 0)
sb.append(", ");
sb.append(textItems[currentSelection[i]]);
}
txtCurrentSelection.setText(sb.toString());
}
else {
txtCurrentSelection.setText("");
}
}
public int[] getSelections() {
return this.currentSelection;
}
// Main method to showcase MultiSelectionCombo
// (can be removed from productive code)
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
shell.setText("MultiSelectionCombo Demo");
// Items and pre-selected items in combo box
String[] items = new String[] { "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa" };
int[] selection = new int[] { 0, 2 };
// Create MultiSelectCombo box
final MultiSelectionCombo combo = new MultiSelectionCombo(shell, items, selection, SWT.NONE);
combo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
((GridData)combo.getLayoutData()).widthHint = 300;
// Add button to print current selection on console
Button button = new Button(shell, SWT.NONE);
button.setText("What is selected?");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
System.out.println("Selected items: " + Arrays.toString(combo.getSelections()));
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
screenshot
https://github.com/lawhcd/SWTMultiCheckSelectionCombo
For anyone who is looking for a widget that allows user to select multiple options from a list of check box style options.
It is based on user1438038's idea and extended to provide nearly all of the api required of a widget similar to Combo.
This isn't possible with the SWT Combo (or CCombo).
The Eclipse Nebula project TableCombo supports a Table shown as a Combo, so you may be able to use an SWT.CHECK style table with this.
There is no such control in SWT on default. However, you can extend either Combo or CCombo to implement checkboxes yourself.
A Table with SWT.CHECK style might be a better option, though:
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
public class TableCheckBoxCell {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Table table = new Table(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
for (int i = 0; i < 12; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText("Item " + i);
}
table.setSize(100, 100);
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Source: Table With CheckBox Cell
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.
I am trying to create a browse button with FileDialog and composite in Java SWT. (Composite because, I am use CTabFolder and CTabItem. I felt to add components to CTabItem composite is good enough)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.custom.CBanner;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.wb.swt.SWTResourceManager;
public class DemoShell extends Shell {
protected Composite composite;
private Text filename;
private Table table;
protected Shell shell;
public static void main(String args[]) {
try {
Display display = Display.getDefault();
DemoShell shell = new DemoShell(display);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean parseFile(Table table, String filename) {
try {
BufferedReader br = new BufferedReader( new FileReader(filename) );
String line = "";
StringTokenizer token = null, subtoken = null;
int tokenNum = 1;
while((line = br.readLine()) != null) {
// lineNum++;
// break comma separated file line by line
token = new StringTokenizer(line, ";");
String sno = null;
while(token.hasMoreTokens()) {
subtoken = new StringTokenizer(token.nextToken().toString(), ",");
sno = "";
sno = Integer.toString(tokenNum);
TableItem item = new TableItem (table, SWT.NONE);
item.setText (0, sno );
item.setText (1, subtoken.nextToken());
item.setText (2, subtoken.nextToken());
item.setText (3, subtoken.nextToken());
item.setText (4, subtoken.nextToken());
item.setText (5, subtoken.nextToken());
tokenNum++;
System.out.println("S.No # " + tokenNum + token.nextToken());
}
tokenNum = 0;
}
br.close();
return true;
} catch(Exception e) {
System.err.println("Parse Error: " + e.getMessage());
return false;
}
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
filename.setText(files[i]);
filename.setEditable(false);
}
}
/**
* Create the shell.
* #param display
*/
public DemoShell(Display display) {
super(display, SWT.SHELL_TRIM);
TabFolder tabFolder = new TabFolder(this, SWT.NONE);
tabFolder.setBounds(10, 10, 462, 268);
TabItem re_item = new TabItem(tabFolder, SWT.NONE);
re_item.setText("Road Network");
TabItem ttable_item = new TabItem(tabFolder, SWT.NONE);
ttable_item.setText("Time Table");
createContents_tt(tabFolder, ttable_item );
}
/**
* Create contents of the shell.
*/
protected void createContents_tt(TabFolder tabFolder, TabItem ttable_item) {
setText("SWT Application");
setSize(530, 326);
//Table declaration
table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
table.setBounds(10, 153, 450, 107);
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = {"S.No", "Route", "Transport #", "Cross Point", "Start Time", "End Time"};
for (int i=0; i<titles.length; i++) {
TableColumn column = new TableColumn (table, SWT.NONE);
column.setText (titles [i]);
}
for (int i=0; i<titles.length; i++) {
table.getColumn (i).pack ();
}
Composite composite = new Composite(tabFolder, SWT.NONE);
composite.setLayout(new FillLayout());
Group group_1 = new Group(shell, SWT.NONE);
group_1.setBounds(10, 10, 450, 127);
filename = new Text(group_1, SWT.BORDER);
filename.setBounds(31, 95, 377, 21);
filename.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
Group group = new Group(group_1, SWT.NONE);
group.setBounds(81, 46, 245, 43);
Label lblEitherBrowseFor = new Label(group_1, SWT.NONE);
lblEitherBrowseFor.setBounds(10, 19, 430, 21);
lblEitherBrowseFor.setText("Either Browse for a file or Try to upload the time table data through Manual entry");
Button btnManual = new Button(group, SWT.NONE);
btnManual.setBounds(162, 10, 75, 25);
btnManual.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
btnManual.setText("Manual");
Button btnBrowser = new Button(group, SWT.NONE);
btnBrowser.setBounds(27, 10, 75, 25);
btnBrowser.setText("Browse");
btnBrowser.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(composite, SWT.NULL);
String path = dialog.open();
if (path != null) {
File file = new File(path);
if (file.isFile())
{
displayFiles(new String[] { file.getAbsolutePath().toString()});
DemoShell.parseFile(table, file.toString());
}
else
displayFiles(file.list());
}
}
});
ttable_item.setControl(composite);
}
#Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
}
I am getting the following error when trying to add in the above manner.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor FileDialog(Composite, int) is undefined
Cannot refer to a non-final variable composite inside an inner class defined in a different method
I request for suggestions/help to clear the bug or re-do with any other way.
You are trying to access composite from within the Listener you define (SelectionAdapter). The notation you use to create the listener implicitly creates a new class. So you are effectively trying to access the variable composite from an inner class, which can only be done if composite is a static field of your outer class or if you make the composite final.
So just do the following:
final Composite composite = new Composite(tabFolder, SWT.NONE);
and it will work.
Moreover, as the error states, there is no constructor that takes a Composite. You have to use a Shell. So just do the following:
FileDialog dialog = new FileDialog(composite.getShell(), SWT.NULL);
This however will give you another exception, since you use the field shell somewhere above that line which is null. Since your class is a Shell, replace all occurences of shell with this and it will work.