Want to select multiple item in Ccombo box In Tree Editor in SWT - autocomplete

In a Tree Viewer, I have five Columns and in this columns except first I am using CCombo Box with the help of tree editor. Now in CCombo box I need to select all items. How is it possible? Please find the below code implementation of CCombo box in my view:
final CCombo comboForRunOn = new CCombo(remoteTable, SWT.READ_ONLY);
comboForRunOn.setItems(remoteComputerIPs);
/*Exe Type - WINDOWS, ANDROID*/
final CCombo comboForExeType = new CCombo(remoteTable, SWT.READ_ONLY);
comboForExeType.setItems(exeTypes.toArray(new String[exeTypes.size()]));
comboForExeType.select(exeTypes.indexOf(tsTCGson.tcParams.get(1).tcparamValue));
/*Exe Type - Firefox, IE, Chrome*/
final CCombo comboForExePlatform = new CCombo(remoteTable, SWT.READ_ONLY);
comboForExePlatform.setItems(exePlatform.toArray(new String[exePlatform.size()]));
comboForExePlatform.select(exePlatform.indexOf(tsTCGson.tcParams.get(0).tcparamValue));
TreeEditor editorForRunOn = new TreeEditor(remoteTable);
TreeEditor editorForExeType = new TreeEditor(remoteTable);
TreeEditor editorForExePlatform = new TreeEditor(remoteTable);
editorForRunOn.setEditor(comboForRunOn, trtmTestcases, 3);
editorForExeType.setEditor(comboForExeType, trtmTestcases, 2);
editorForExePlatform.setEditor(comboForExePlatform, trtmTestcases, 1);
editorForRunOn.horizontalAlignment = SWT.LEFT;
editorForRunOn.grabHorizontal = true;
editorForExeType.horizontalAlignment = SWT.LEFT;
editorForExeType.grabHorizontal = true;
editorForExePlatform.horizontalAlignment = SWT.LEFT;
editorForExePlatform.grabHorizontal = true;

To overcome this issue i have create MultiSectionCombo.java class, find the below code,
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;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.wb.swt.SWTResourceManager;
public class MultiSelectionCombo extends Composite {
Shell shell = null;
List list = null;
Text txtCurrentSelection = null;
String[] textItems = null;
int[] currentSelection = null;
TreeItem treeItem = null;
public MultiSelectionCombo(Composite parent,TreeItem tItem, String[] items, int[] selection, int style) {
super(parent, style);
currentSelection = selection;
textItems = items;
treeItem = tItem;
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;
GridLayout gridLayout = new GridLayout();
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
setLayout(gridLayout);
txtCurrentSelection = new Text(this, SWT.READ_ONLY);
txtCurrentSelection.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
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 = 0;
gl.marginTop = 0;
gl.marginRight = 0;
gl.marginLeft = 0;
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());
treeItem.setText(1, sb.toString());
}
else {
txtCurrentSelection.setText("");
treeItem.setText(1,"");
}
}
public int[] getSelections() {
return this.currentSelection;
}
}
and Its working fine in code.

Related

org.eclipse.core.runtime.AssertionFailedException: assertion failed:

I am trying to create a table with ComboBoxCellEditor column. When I set value that time below exception is coming.
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/............/
public class Test {
public static void main(String[] args) {
Shell shell = new Shell();
shell.setText("TableViewer Example");
GridLayout layout = new GridLayout();
shell.setLayout(layout);
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
composite.setLayout(new GridLayout(1, false));
Table testTable = new Table(composite, SWT.BORDER);
testTable.setLinesVisible(true);
testTable.setHeaderVisible(true);
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, false);
tableData.heightHint = 300;
testTable.setLayoutData(tableData);
TableViewerColumn columnViewer = null;
String[] columnNames = { "Name", "Laptops" };
TableViewer testTableViewer = new TableViewer(testTable);
for (int i = 0; i < columnNames.length; i++) {
columnViewer = new TableViewerColumn(testTableViewer, SWT.LEFT);
columnViewer.getColumn().setText(columnNames[i]);
if (columnNames[i].equals("Name")) {
columnViewer.getColumn().setWidth(200);
} else if (columnNames[i].equals("Laptops")) {
columnViewer.getColumn().setWidth(300);
}
columnViewer.getColumn().setResizable(true);
columnViewer.getColumn().setMoveable(true);
columnViewer.setLabelProvider(new TestColumnLabelProvider(i));
}
testTableViewer.setContentProvider(new TestContentProvider());
testTableViewer.setColumnProperties(columnNames);
TestBean[] testBeans = new TestBean[5];
for (int i = 0; i < 5; i++) {
TestBean bean = new TestBean();
TableViewerColumn[] getTableViewerColumns =
getTableViewerColumns(testTableViewer);
for (int j = 0; j < getTableViewerColumns.length; j++) {
getTableViewerColumns[j].setEditingSupport(new
TestEditingSuport(testTableViewer, j, bean.getListOfLaptop));
}
bean.setName("Debasish" + i);
bean.setLaptop(bean.getListOfLaptop[i]);
testBeans[i] = bean;
}
testTableViewer.setInput(testBeans);
shell.open();
Display display = shell.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
public static TableViewerColumn[] getTableViewerColumns(TableViewer
tableViewer) {
TableColumn[] columns = tableViewer.getTable().getColumns();
TableViewerColumn[] viewerColumns = new TableViewerColumn[columns.length];
for (int i = 0; i < columns.length; i++) {
TableColumn tableColumn = columns[i];
viewerColumns[i] = (TableViewerColumn) tableColumn.getData(Policy.JFACE +
".columnViewer");
}
return viewerColumns;
}
}
/............./
class TestBean {
private String name;
private String laptop;
public String[] getListOfLaptop = { "Acer", "HP", "Lenovo", "Dell", "Benq"
};
//getter and setter method
}
/..................../
class TestEditingSuport extends EditingSupport {
private int m_column;
private CellEditor m_editor;
public TestEditingSuport(ColumnViewer viewer, int column,
String[] listOfTestBean) {
super(viewer);
m_column = column;
// Create the correct editor based on the column index
switch (column) {
case 0:
case 1:
m_editor = new ComboBoxCellEditor(
((TableViewer) viewer).getTable(), listOfTestBean);
break;
default:
}
}
#Override
protected CellEditor getCellEditor(Object element) {
return m_editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
TestBean bean = (TestBean) element;
Object value = null;
switch (m_column) {
case 0:
value = bean.getName();
break;
case 1:
value = bean.getLaptop();
break;
default:
}
return value;
}
#Override
protected void setValue(Object element, Object value) {
TestBean bean = (TestBean) element;
switch (m_column) {
case 0:
if (valueChanged(bean.getName(), (String) value)) {
bean.setName((String) value);
}
getViewer().update(bean, null);
break;
case 1:
int index = (Integer) value;
String laptop = bean.getListOfLaptop[index];
if (valueChanged(bean.getLaptop(), laptop)) {
bean.setLaptop(laptop);
}
getViewer().update(bean, null);
break;
default:
}
}
private boolean valueChanged(String previousValue, String currentValue) {
boolean changed = false;
if ((previousValue == null) && (currentValue != null)) {
changed = true;
} else if ((previousValue != null) && (currentValue != null) && (!previousValue.equals(currentValue))) {
changed = true;
}
return changed;
}
}
/............../
class TestContentProvider implements IStructuredContentProvider {
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
}
/........................./
class TestColumnLabelProvider extends ColumnLabelProvider {
private int m_column;
public TestColumnLabelProvider(int column) {
this.m_column = column;
}
public String getText(Object element) {
String text = null;
if (element instanceof TestBean) {
TestBean testBean = (TestBean) element;
switch (m_column) {
case 0:
text = testBean.getName();
break;
case 1:
text = testBean.getLaptop();
break;
default:
}
}
return text;
}
}
/....................../
ComboCellEditor values are integer indexes in to the list of values you give it in the constructor.
Your getValue method of your EditingSupport class must return an Integer index in to the values list.
The setValue method of your EditingSupport class will be given an Integer containing the selected index.

how to create a table by using Nattable and add value into its column

I have to create a Nat Table with three column and add value in the column.please help me. thanks in Advance
hope this helps. For the details of the layer you can refer the http://www.vogella.com/tutorials/NatTable/article.html link which is quite apt.
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.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
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.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.LabelStack;
import org.eclipse.nebula.widgets.nattable.layer.cell.IConfigLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.style.Style;
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Nat_explore {
private BodyLayerStack bodyLayer ;
private int statusColumn;
private int statusRejected;
private int statusInProgress;
private boolean check = false;
private NatTable nattable;
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 Nat_explore();
}
public Nat_explore() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
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 = (int) 24;
gridData.widthHint = (int) 110;
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 columnData = new DefaultColumnHeaderDataProvider(properties);
ColumnHeaderLayerStack columnlayer = new ColumnHeaderLayerStack(columnData);
//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, columnlayer);
GridLayer gridlayer = new GridLayer(bodyLayer, columnlayer, rowlayer, cornerLayer);
nattable = new NatTable(shell, gridlayer,false);
// Change for paint
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
//#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
public void configureRegistry(IConfigRegistry configRegistry) {
Style cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR,GUIHelper.COLOR_YELLOW);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle,DisplayMode.NORMAL, FOO_LABEL);
cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR,GUIHelper.COLOR_RED);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle,DisplayMode.NORMAL, CELL_LABEL);
}
});
nattable.setLayoutData(gridData);
nattable.setConfigRegistry(configRegistry);
nattable.configure();
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("Column"+columnIndex+" Row"+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,Nat_explore.this.bodyLayer, Nat_explore.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,Nat_explore.this.bodyLayer, Nat_explore.this.bodyLayer.getSelectionLayer());setUnderlyingLayer(rowHeaderLayer);
}
}
}

how dynamically adjust size of controls in TitleAreaDialog

I have TitleAreaDialog that can have n numbers of Tree, each tree has its own composite. If I have just 2 trees the dialog looks great, but if number of trees grows the content of the trees are being truncated.
I think I missed something small..
Here is the code:
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TreeItem;
public class testTitleDialog extends TitleAreaDialog {
private static final String DIALOG_TITLE = "TITLE AREA DIALOG";
Composite area;
public testTitleDialog(Shell parentShell) {
super(parentShell);
}
#Override
public void create() {
super.create();
setTitle("TITLE WILL BE HERE");
}
#Override
protected Control createDialogArea(final Composite parent) {
this.area = (Composite) super.createDialogArea(parent);
parent.getShell().setText(DIALOG_TITLE);
Composite area = (Composite) super.createDialogArea(parent);
Composite contents = (Composite) super.createDialogArea(area);
contents.setLayout(new GridLayout());
contents.setLayoutData(new GridData(GridData.FILL_BOTH));
contents.addDisposeListener(new DisposeListener(){
public void widgetDisposed(DisposeEvent e) {
}
});
createMapperComposite(contents);
return this.dialogArea;
}
private void createMapperComposite(Composite composite) {
Composite main = new Composite(composite, SWT.NONE);
main.setLayout(new GridLayout());
main.setLayoutData(new GridData(GridData.FILL_BOTH));
treeMapper(main);
}
private Composite treeMapper(Composite main) {
SashForm sashForm = new SashForm(main, SWT.HORIZONTAL);
Composite composite = new Composite(sashForm, SWT.NONE);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setBackground(ColorConstants.white);
//i is number of trees
for (int i = 0; i < 10; i++) {
Label lbl = new Label(composite, SWT.NONE);
lbl.setText("Tree " + i);
// Add content to scrolled composite
Composite scrolledContent = new Composite(composite, SWT.NONE);
scrolledContent.setLayout(new GridLayout());
GridData gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.verticalAlignment = SWT.FILL;
gridData.grabExcessVerticalSpace = true;
scrolledContent.setLayoutData(gridData);
final TreeViewer tree = new TreeViewer(scrolledContent);
for(int loopIndex0 = 0; loopIndex0 < 10; loopIndex0++) {
TreeItem treeItem0 = new TreeItem(tree.getTree(), 0);
treeItem0.setText("Level 0 Item "+ loopIndex0);
for(int loopIndex1 = 0; loopIndex1 < 10; loopIndex1++) {
TreeItem treeItem1 = new TreeItem(treeItem0, 0);
treeItem1.setText("Level 1 Item "+ loopIndex1);
for(int loopIndex2 = 0; loopIndex2 < 10; loopIndex2++) {
TreeItem treeItem2 = new TreeItem(treeItem1, 0);
treeItem2.setText("Level 2 Item "+ loopIndex2);
}
}
}
tree.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
}
new TreeViewer(sashForm);
return main;
}
#Override
protected boolean isResizable() {
return true;
}
#Override
protected void okPressed() {
super.okPressed();
}
public static void main(final String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
new testTitleDialog(shell).open();
}
}
You are not doing anything to deal with the dialog being too big from the display. You must use something like ScrolledComposite to deal with this:
#Override
protected Control createDialogArea(final Composite parent) {
Composite area = (Composite) super.createDialogArea(parent);
parent.getShell().setText(DIALOG_TITLE);
ScrolledComposite scrolled = new ScrolledComposite(area, SWT.V_SCROLL | SWT.H_SCROLL);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.heightHint = 500;
scrolled.setLayoutData(data);
scrolled.setExpandHorizontal(true);
scrolled.setExpandVertical(true);
createMapperComposite(scrolled);
return area;
}
private void createMapperComposite(ScrolledComposite composite) {
Composite main = new Composite(composite, SWT.NONE);
main.setLayout(new GridLayout());
main.setLayoutData(new GridData(GridData.FILL_BOTH));
treeMapper(main);
composite.setContent(main);
composite.setMinSize(main.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
Note: You have to choose a height for the dialog (see data.heightHint = 500) to make this work.
Your code called super.createDialogArea three times - this must be called exactly once. You also returned this.dialogArea - you should return the value returned by super.createDialogArea.

Place unknown amount of nodes in GridPane

I am making a maze from a text file. The text file contains two integers on separate lines. These decide a number of rows and columns. Then the text file forms a maze by the use of '#' for walls, ' ' for passage, '*' for the players start position and '-' for the exit. When I start the program, I am able to select the file but the nodes won't align up nicely in rows and columns. Seems like they all ends up in a pile in the same place. Any tips?
package application;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javafx.application.Application;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
public class Main extends Application {
LabyrintRute[][] Labyrint;
int X;
int Y;
int startx;
int starty;
Spiller spilleren;
#Override
public void start(Stage primaryStage) {
try {
GridPane root = new GridPane();
Scene scene = new Scene(root, X*100, Y*100, Color.BLACK);
Spiller spilleren = new Spiller(startx, starty);
filLeser();
root.add(spilleren.getUtseende(), spilleren.getxPossisjon(), spilleren.getyPossisjon());
for(int x = 1; x<X; x++){
for(int y = 1; y<Y; y++){
root.add(Labyrint[x][y].getUtseende(), Labyrint[x][y].getxKoordinat(), Labyrint[x][y].getyKoordinat());
}
}
scene.setOnKeyPressed(new FilLytter(this));
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("Labyrintspill");
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public void filLeser() {
String teksten = "";
File fila;
FileChooser filvelger = new FileChooser();
filvelger.setTitle("Åpne en tekstfil");
filvelger.getExtensionFilters().add(new ExtensionFilter("Text Files", "*.txt"));
fila = filvelger.showOpenDialog(null);
try (Scanner filleser = new Scanner(fila)) {
X = filleser.nextInt();
Y = filleser.nextInt();
teksten = filleser.nextLine();
Labyrint = new LabyrintRute [X][Y];
while (filleser.hasNext()) {
teksten = filleser.nextLine();
for (int i = 1;i< X;i++) {
for (int rad = 1; rad < Y; rad++){
char tegn = teksten.charAt(i);
switch (tegn) {
case '#':
Labyrint[i][rad] = new Vegg(i, rad);
break;
case ' ':
Labyrint[i][rad] = new Gang(i, rad);
break;
case '-':
Labyrint[i][rad] = new Utgang(i, rad);
break;
case '*':
Labyrint[i][rad] = new Gang(i, rad);
startx = i;
starty = rad;
break;
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Kan ikke åpne fila!");
e.printStackTrace();
}
}
public void flyttSpiller(int deltax, int deltay) {
int nyx = spilleren.getxPossisjon() + deltax;
int nyy = spilleren.getyPossisjon() + deltay;
Labyrint[nyx][nyy].flyttHit(spilleren);
}
public static void main(String[] args) {
launch(args);
}
}
The is the "Vegg"(wall), "Gang"(passage) and "Utgang"(exit) methods are all extensions of the "Labyrintrute" method:
package application;
import javafx.scene.Node;
public abstract class LabyrintRute {
private int xKoordinat;
private int yKoordinat;
public LabyrintRute(int xKoordinat, int yKoordinat) {
this.xKoordinat = xKoordinat;
this.yKoordinat = yKoordinat;
}
public int getxKoordinat() {
return xKoordinat;
}
public int getyKoordinat() {
return yKoordinat;
}
public abstract void flyttHit(Spiller spilleren);
public abstract Node getUtseende();
}
The "vegg"(wall), "gang"(passage) and "utgang"(exit) methods are all pretty similiar. So I'm just posting one of them:
package application;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Utgang extends LabyrintRute {
private Node utseende;
public Utgang(int xKoordinat, int yKoordinat) {
super(xKoordinat, yKoordinat);
utseende = new Rectangle(10, 10, Color.BLACK);
}
#Override
public void flyttHit(Spiller spilleren) {
spilleren.setxPossisjon(getxKoordinat());
spilleren.setyPossisjon(getyKoordinat());
JFrame ramme = new JFrame();
JOptionPane.showMessageDialog(ramme, "Gratulerer! Du fant veien ut :D");
System.exit(0);
}
#Override
public Node getUtseende() {
return utseende;
}
}

Google maps API v2 Android, not drawing polygon when offline

I have a test application that I draw a Polygon using google maps API.
The problem is that, when I have no cache of any maps (new installed application) the Polygon does not draw.
Its not a problem not having the maps loaded, but I do need the Polygons drawn in my screen.
Is there a way I can do that?
Sry for my bad english
Heres the code I have:
package ngvl.testegmaps_v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import ngvl.testegmaps_v2.VO.GeoPosicionamento;
import ngvl.testegmaps_v2.VO.Layer;
import ngvl.testegmaps_v2.VO.Secao;
import ngvl.testegmaps_v2.VO.Talhao;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends FragmentActivity {
private List<Secao> secoes;
private List<Polygon> poligonos = new ArrayList<Polygon>();
private HashMap<String,Object[]> informacoes = new HashMap<String,Object[]>();
private GoogleMap map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fragment.getMap();
map.getUiSettings().setRotateGesturesEnabled(false);
// Setting a click event handler for the map
LatLng latLng = new LatLng(-20.9957152, -47.3241304);
// map.addMarker(new
// MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title("Av. Paulista").snippet("São Paulo"));
configuraPosicao(map, latLng);
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
}
private void configuraPosicao(GoogleMap map, LatLng latLng) {
/*
* 3D map.moveCamera( CameraUpdateFactory.newLatLngZoom(latLng, 15));
* map.animateCamera( CameraUpdateFactory.zoomTo(10), 2000, null);
*
* CameraPosition cameraPosition = new CameraPosition.Builder()
* .target(latLng) .zoom(17) .bearing(90) .tilt(45) .build();
*
* map.animateCamera( CameraUpdateFactory.newCameraPosition(
* cameraPosition));
*/
map.setMapType(GoogleMap.MAP_TYPE_NONE);
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
try {
String json = readFileAsString("geo.json");
Gson gson = new Gson();
this.secoes = gson.fromJson(json, new TypeToken<List<Secao>>() {
}.getType());
json = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
escrevePoligons(map);
}
private String readFileAsString(String fileName) throws IOException {
InputStream is = getAssets().open(fileName);
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
private void escrevePoligons(GoogleMap map) {
float stroke = (float) 1.5;
for (Secao secao : secoes) {
for (Talhao talhao : secao.getTalhoes()) {
for (Layer layer : talhao.getLayers()) {
// PolygonOptions rectOptions = new PolygonOptions();
List<LatLng> latlngs = new ArrayList<LatLng>();
for (GeoPosicionamento geoPosicionamento : layer.getGeoPosicionamentos()) {
latlngs.add(new LatLng(geoPosicionamento.getLatitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue(), geoPosicionamento
.getLongitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue()));
}
int color = 0x1F00FF00;
int color2 = 0x5F000000;
PolygonOptions polygonOptions = new PolygonOptions()
.fillColor(color).addAll(latlngs)
.strokeColor(color2).strokeWidth(stroke);
Polygon p = map.addPolygon(polygonOptions);
poligonos.add(p);
informacoes.put( p.getId(), new Object[]{ secao, talhao , layer } );
//System.out.println(polygonOptions.getPoints());
polygonOptions = null;
latlngs = null;
}
}
}
this.secoes = null;
// String mUrl =
// "https://khms0.google.com.br/kh/v=124&src=app&z={z}&x={x}&y={y}";
// MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256,
// mUrl);
// mTileProvider.tilesRange();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
//String mUrl = "http://a.tile.openstreetmap.org/{z}/{x}/{y}.png";
//MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256, mUrl);
//map.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
// TileProvider tileProvider = TileProviderFactory.getTileProvider();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(tileProvider));
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
// LatLng(-20.9957152, -47.3241304), 15));
map.setOnMapClickListener(new OnMapClickListener()
{
public void onMapClick(LatLng point)
{
Polygon p = isPointInPolygon(point);
if( p != null){
p.setFillColor(getRandomColor());
Object[] clicado = informacoes.get( p.getId() );
Secao secao_clicada = (Secao) clicado[0];
Talhao talhao_clicada = (Talhao) clicado[1];
Layer layer_clicada = (Layer) clicado[2];
//System.out.println(secao_clicada);
//System.out.println(talhao_clicada);
//System.out.println(layer_clicada);
//System.out.println("=======================");
StringBuilder texto = new StringBuilder();
texto.append("Seção: " + secao_clicada.getDesc() + "\n");
texto.append("Talhão: " + talhao_clicada.getTalhao() + "\n");
texto.append("Variedade: " + talhao_clicada.getVariedade() + " - " + talhao_clicada.getDescVariedade() + "\n");
texto.append("Layer: " + layer_clicada.getSequencia() + "\n");
//Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
addMarker(point,texto);
}//else
//Toast.makeText(MainActivity.this,"Clicou fora da Área de um Poligono", Toast.LENGTH_LONG).show();
}
});
}
public void addMarker(LatLng point, StringBuilder texto) {
/*map.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.title("Caracteristicas: ")
.snippet( texto );
*/
Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
}
private Polygon isPointInPolygon(LatLng tap) {
for( Polygon p : poligonos){
int intersectCount = 0;
List<LatLng> vertices = p.getPoints();
for(int j=0; j<vertices.size()-1; j++) {
if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
intersectCount++;
}
}
if(((intersectCount % 2) == 1)){
return p;
}
}
return null;// odd = inside, even = outside;
}
private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
}
double m = (aY-bY) / (aX-bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
}
};
public int getRandomColor() {
int color;
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
return color;
}
}
Setting map type to MAP_TYPE_NONE like example above does not solve the problem
I will this as marked solved by using Maps Forge Open Source API
If someone did with Google Maps Api please share and I would change the answer.
The answer I found is that its impossible to render or access anything without rendering the map first (online or via cache)
This is actually a bug of GoogleMaps Api v2 for Android.
It is referenced here:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5017
Star it if you want to accelerate the bug fix!