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.
Related
I have two elements in a horizontal RowLayout.
I am able to specify a (minimal) with for the second element (e.g. 200 px). Furthermore...
a) If the total width of the shell is too small, the second element wraps to a new line. That works fine with the RowLayout.
b) If the total with is "large", the second (=last) element should grab the excess horizontal space.
Is b) possible with the RowLayout? Or do I need to use a GridLayout and implement the wrapping on my own (e.g. use one or two columns in the grid layout, depending on the size of the elements)?
public class RowLayoutDemo {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new RowLayout());
Text firstElement = new Text(shell, SWT.NONE);
firstElement.setText("firstElement");
Text secondElement = new Text(shell, SWT.NONE);
secondElement.setText("secondElement");
secondElement.setBackground(new Color(null, 200, 0, 0));
int minWidth = 200;
RowData rowData = new RowData();
rowData.width = minWidth;
secondElement.setLayoutData(rowData);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
The RowLayout does not support what you are looking for. I recommend using a GridLayout with a resize listener as you suggested or implement your own layout.
I first tried to write a custom layout which turned out to be be hard. The second strategy based on GridLayout was easier. Here is a first draft for a custom Composite that switches the number of columns of its GridLayout to have one or two columns, depending on the size of its children.
(I still have an issues with flickering when resizing my Sections.)
package org.treez.core.adaptable.composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
/**
* A row composite for only two children. If the children are too large for a single line, the second child is wrapped
* on a second line. The second child always grabs excess horizontal space. This composite automatically sets the
* LayoutData of its children. Therefore the LayoutData of the children should not be set manually.
*/
public class GrabbingRowComposite extends Composite {
//#region ATTRIBUTES
private int widthHintForFirstChild = 80;
private int minWidthForSecondChild = 200;
private boolean isSingleLine = true;
//#end region
//#region CONSTRUCTORS
public GrabbingRowComposite(Composite parent) {
super(parent);
super.setLayout(createLayout());
if (parent.getLayout() instanceof GridLayout) {
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
setLayoutData(gridData);
}
}
//#end region
//#region METHODS
private GridLayout createLayout() {
//create default layout for single line
GridLayout gridLayout = new GridLayout(2, false);
//change layout to use several lines if required
this.addControlListener(new ControlAdapter() {
#Override
public void controlResized(ControlEvent e) {
adaptLayout();
}
});
return gridLayout;
}
private void adaptLayout() {
int totalWidth = this.getBounds().width;
Control[] children = getChildren();
if (children.length < 2) {
return;
}
Control firstChild = children[0];
Control secondChild = children[1];
int firstChildWidth = children[0].getBounds().width;
setWidthHintForFirstChild(firstChild);
setGrapHorizontalSpaceForSecondChild(secondChild);
boolean isTooSmallForOneLine = totalWidth < firstChildWidth + minWidthForSecondChild;
if (isTooSmallForOneLine) {
setTwoLineLayout();
} else {
setSingleLineLayout();
}
}
private void setTwoLineLayout() {
if (isSingleLine) {
super.setLayout(new GridLayout(1, false));
updateLayoutOfParentAndGrandParent();
isSingleLine = false;
}
}
private void setSingleLineLayout() {
if (!isSingleLine) {
super.setLayout(new GridLayout(2, false));
updateLayoutOfParentAndGrandParent();
isSingleLine = true;
}
}
private void setWidthHintForFirstChild(Control firstChild) {
GridData firstGridData = new GridData();
firstGridData.widthHint = widthHintForFirstChild;
firstChild.setLayoutData(firstGridData);
}
private static void setGrapHorizontalSpaceForSecondChild(Control secondChild) {
GridData secondGridData = new GridData(SWT.FILL, SWT.FILL, true, false);
secondChild.setLayoutData(secondGridData);
}
private void updateLayoutOfParentAndGrandParent() {
Composite parent = getParent();
if (parent != null) {
parent.layout(true);
Composite grandParent = parent.getParent();
if (grandParent != null) {
grandParent.layout(true);
}
}
}
//#end region
//#region ACCESSORS
#Override
public void setLayout(Layout layout) {
throw new IllegalStateException("The layout of this composite must not be changed");
}
//#end region
}
Example usage
package org.treez.core.adaptable.composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.Section;
public class GrabbingRowCompositeDemo {
public static void main(String[] args) {
Shell shell = createShell();
shell.setSize(500, 300);
Section section = createSection(shell);
Composite parentComposite = createParentComposite(section);
createRow(parentComposite, "first");
createRow(parentComposite, "second");
createRow(parentComposite, "third");
section.clientVerticalSpacing = 0;
showUntilClosed(shell);
}
private static Shell createShell() {
Display display = new Display();
Shell shell = new Shell(display);
GridLayout shellGridLayout = new GridLayout(1, false);
shell.setLayout(shellGridLayout);
return shell;
}
private static Section createSection(Shell shell) {
Section section = new Section(
shell,
ExpandableComposite.TWISTIE | //
ExpandableComposite.EXPANDED | //
ExpandableComposite.TITLE_BAR | //
ExpandableComposite.CLIENT_INDENT);
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
section.setLayoutData(gridData);
return section;
}
private static Composite createParentComposite(Section section) {
Composite parentComposite = new Composite(section, SWT.NONE);
section.setClient(parentComposite);
parentComposite.setBackground(new Color(null, 0, 0, 255));
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
parentComposite.setLayoutData(gridData);
GridLayout gridLayout = new GridLayout(1, false);
parentComposite.setLayout(gridLayout);
return parentComposite;
}
private static Composite createRow(Composite parent, String text) {
GrabbingRowComposite row = new GrabbingRowComposite(parent);
row.setBackground(new Color(null, 255, 255, 255));
Label label = new Label(row, SWT.NONE);
label.setText(text);
Button checkBox = new Button(row, SWT.CHECK);
checkBox.setBackground(new Color(null, 255, 0, 0));
return row;
}
private static void showUntilClosed(Shell shell) {
shell.open();
Display display = Display.getCurrent();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
I have been told to design a Tree , clicking on Node should give detail about a person and should display an Image. I used If-Else statement to do this and was told that it is not a standard of coding, how can i make it really efficient so that it follows coding standards.
This is my code for a Eclipse RCP View.. It would display the content in table and image of the person when a node with a person is selected.
RCP Application Output here
package com.cerner.imagetagger.view;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.part.ViewPart;
public class JViewer extends ViewPart{
public JViewer() {}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout(SWT.HORIZONTAL));
final Tree tree = new Tree(parent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
Label labelImg = new Label(parent,SWT.NONE);
Table table = new Table(parent, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
final ImageLoader loader = new ImageLoader();
loader.load(getClass().getClassLoader().getResourceAsStream("icons/default.png"));
final Image image = new Image(Display.getCurrent(), loader.data[0]);
labelImg.setImage(image);
table.setLinesVisible(true);
table.setHeaderVisible(true);
TreeItem item0 = new TreeItem(tree, 0);
item0.setText("Designation");
TreeItem item1 = new TreeItem(item0, 0);
item1.setText("Software Engineer");
TreeItem item2 = new TreeItem(item1, 0);
item2.setText("Tansheet Izhad");
TreeItem item21 = new TreeItem(item1, 0);
item21.setText("Nikhil Gautam");
String[] titles = {"Name", "Age"};
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(titles[i]);
}
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, "");
item.setText(1, "");
for (int i=0; i<titles.length; i++) {
table.getColumn (i).pack ();
}
tree.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
String treeNode = "";
String resultwb= "";
String result="";
TreeItem[] selection = tree.getSelection();
for (int i = 0; i < selection.length; i++)
treeNode += selection[i] + " ";
resultwb = treeNode.replaceAll("[{}]", "");
result=resultwb.replace("TreeItem ","");
if(result.matches("(.*)Tansheet Izhad(.*)"))
{
item.setText(0, "TI");
item.setText(1, "23");
loader.load(getClass().getClassLoader().getResourceAsStream("icons/tansheet.png"));
final Image image = new Image(Display.getCurrent(), loader.data[0]);
labelImg.setImage(image);
}
else
{
item.setText(0, "NULL");
item.setText(1, "NULL");
loader.load(getClass().getClassLoader().getResourceAsStream("icons/default.png"));
final Image image = new Image(Display.getCurrent(), loader.data[0]);
labelImg.setImage(image);
}
}
});
tree.getItems()[0].setExpanded(true);
}
#Override
public void setFocus() {}
}
Any suggestions?
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 am working on a wizard, which should have an error composite showed on the top of controls if an error occurs. This composite contains a Text listing all errors and two Labels: above and below this component. The Label below the error list can be omitted. Dependent on the amount of errors the height of the error list should vary. However it should not exceed the height of the parent composite. If the errors don't fit into the Text with the full height, a scroll bar should be shown.
Here's a minimized snippet of what I reached till now:
package de.dannylo.issues;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
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.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class TestWizardPage
extends WizardPage
{
private static final String PLUGIN_ID = "de.dannylo.issues.TestPlugin";
private Composite mainComposite;
private Composite stackComposite;
private StackLayout stackLayout;
private Composite defaultMessageComposite;
private Text idText;
private static Wizard wizard;
public TestWizardPage()
{
super("portalAppWizardMavenPage");
setTitle("TestWizard");
setDescription("Testing...");
}
#Override
public void createControl(Composite parent)
{
mainComposite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
mainComposite.setLayout(layout);
layout.numColumns = 1;
layout.verticalSpacing = 15;
// source folder
Composite idComposite = new Composite(mainComposite, SWT.NONE);
idComposite.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
idComposite.setLayout(new GridLayout(2, false));
Label label = new Label(idComposite, SWT.NONE);
label.setText("ID:");
idText = new Text(idComposite, SWT.BORDER | SWT.SINGLE);
idText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
label = new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
stackComposite = new Composite(mainComposite, SWT.NONE);
GridData layoutData = new GridData(SWT.FILL, SWT.NONE, true, false);
layoutData.heightHint = 250; // For testing purposes in the real GUI
// there are several components filling
// this composite
stackComposite.setLayoutData(layoutData);
stackLayout = new StackLayout();
stackComposite.setLayout(stackLayout);
defaultMessageComposite = new Composite(stackComposite, SWT.NONE);
defaultMessageComposite.setLayout(new GridLayout());
stackLayout.topControl = defaultMessageComposite;
label = new Label(defaultMessageComposite, SWT.NONE);
label.setText("Enter \"1\", \"2\" or \"3\" into the text field above.");
idText.addModifyListener(new ModifyListener()
{
#Override
public void modifyText(ModifyEvent e)
{
if ("1".equals(idText.getText()))
showErrorComposite("You entered id 1", "Nice job!", createTestStatusList(4));
else if ("2".equals(idText.getText()))
showErrorComposite("You entered id 2", "Oops", createTestStatusList(20));
else if ("3".equals(idText.getText()))
showErrorComposite("You entered id 3", null, createTestStatusList(20));
else
{
stackLayout.topControl = defaultMessageComposite;
stackComposite.layout();
}
}
});
setControl(mainComposite);
}
private static List<IStatus> createTestStatusList(int amount)
{
List<IStatus> toRet = new ArrayList<IStatus>();
for (int i = 0; i < amount; i++)
{
toRet.add(new Status(IStatus.ERROR, PLUGIN_ID, "Error message " + i + ": " + toRet.hashCode()));
}
return toRet;
}
private void showErrorComposite(String topMessage, String bottomMessage, List<IStatus> statusList)
{
final Composite errorComposite = new Composite(stackComposite, SWT.BORDER);
final GridLayout layout = new GridLayout();
layout.verticalSpacing = 20;
errorComposite.setLayout(layout);
errorComposite.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
final Label topLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
topLabel.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
topLabel.setText(topMessage);
final Text errorList = new Text(errorComposite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL
| SWT.BORDER);
final GridData gd_errorList = new GridData(SWT.FILL, SWT.NONE, true, false);
gd_errorList.horizontalIndent = 20;
errorList.setLayoutData(gd_errorList);
for (int i = 0; i < statusList.size(); i++)
{
IStatus status = statusList.get(i);
errorList.append("\u2022 " + status.getMessage());
if (i != statusList.size() - 1)
errorList.append("\n\n");
}
final Label bottomLabel;
if (bottomMessage != null)
{
bottomLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
bottomLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
bottomLabel.setText(bottomMessage);
}
else
bottomLabel = null;
final Listener scrollBarListener = new Listener()
{
#Override
public void handleEvent(Event event)
{
errorList.removeListener(SWT.Resize, this);
int marginHeight = ((GridLayout)errorComposite.getLayout()).marginHeight;
int stackCompositeHeight = stackComposite.getClientArea().height;
int topLabelHeight = topLabel.getSize().y;
int verticalSpacing = layout.verticalSpacing;
int bottomLabelHeight = bottomLabel == null ? 0 : bottomLabel.getSize().y;
int spaceAboveErrorList = marginHeight + topLabelHeight + verticalSpacing;
int spaceBelowErrorList = bottomLabel == null ? marginHeight + 15 : verticalSpacing
+ bottomLabelHeight
+ marginHeight + 15;
int hHint = stackCompositeHeight - spaceAboveErrorList - spaceBelowErrorList;
Rectangle errorListClientArea = errorList.getClientArea();
Point errorListSize = errorList.computeSize(errorListClientArea.x, SWT.DEFAULT, true);
if (stackCompositeHeight < spaceAboveErrorList + errorListSize.y + spaceBelowErrorList)
{
gd_errorList.heightHint = hHint;
errorList.getVerticalBar().setVisible(true);
}
else
{
gd_errorList.heightHint = errorListSize.y;
errorList.getVerticalBar().setVisible(false);
}
errorComposite.layout();
errorList.addListener(SWT.Resize, this);
}
};
errorList.addListener(SWT.Resize, scrollBarListener);
stackLayout.topControl = errorComposite;
stackComposite.layout();
}
public static void main(String[] args)
{
Display.getDefault().syncExec(new Runnable()
{
#Override
public void run()
{
wizard = new Wizard()
{
#Override
public void addPages()
{
addPage(new TestWizardPage());
}
#Override
public boolean performFinish()
{
MessageDialog.openInformation(getShell(), "Bye!", "Thanks for testing!");
return true;
}
};
}
});
new WizardDialog(wizard.getShell(), wizard).open();
}
}
I have a problem with the ID2. In this case the height of the Text is maximum and the bottomLabel should be shown. Unfortunately this label doesn't appear as it's composite appears, but rather it appears only after the width of the window changes. It seems to be some problem with layouting. I already tried to use errorComposite.layout(true, true) (and even getShell().layout(true, true)) to flush the cache and redraw the children but this didn't help. Any ideas on how to fix that issue?
I solved your issue by entirely removing the scrollBarListener and fixing your layout a bit.
The showErrorComposite(...) method now looks like this:
private void showErrorComposite(String topMessage, String bottomMessage, List<IStatus> statusList)
{
final Composite errorComposite = new Composite(stackComposite, SWT.BORDER);
final GridLayout layout = new GridLayout();
layout.verticalSpacing = 20;
errorComposite.setLayout(layout);
errorComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Label topLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
topLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
topLabel.setText(topMessage);
final Text errorList = new Text(errorComposite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL
| SWT.BORDER);
final GridData gd_errorList = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_errorList.horizontalIndent = 20;
errorList.setLayoutData(gd_errorList);
for (int i = 0; i < statusList.size(); i++)
{
IStatus status = statusList.get(i);
errorList.append("\u2022 " + status.getMessage());
if (i != statusList.size() - 1)
errorList.append("\n\n");
}
errorList.setTopIndex(0);
final Label bottomLabel;
if (bottomMessage != null)
{
bottomLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
bottomLabel.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
bottomLabel.setText(bottomMessage);
}
else
bottomLabel = null;
stackLayout.topControl = errorComposite;
stackComposite.layout();
}
It now looks like this:
UPDATE
Ok, in your particular case, leave your code as it is and just add this line at the end of your showErrorComposite(...) method:
scrollBarListener.handleEvent(null);