NatTable with checkbox column - check/uncheck not working - java

Used EditableGrid example to create a checkbox column inside my NatTable, however the mouse events to check and uncheck are not getting triggered and hence the state of checkbox doesn't change. Below is the code snippet:
private Control exampleNatTableWithCheckBox(Composite parent) {
final String[] propertyNames = PLAN_PROPERTY_NAMES;
final Map<String, String> propertyToLabelMap = getPropertyToLabelMap();
IRowIdAccessor<ConsoleEntry> rowIdAccessor = new IRowIdAccessor<T>() {
#Override
public Serializable getRowId(T rowObject) {
return rowObject.getRcdIdx();
}
};
ConfigRegistry configRegistry = new ConfigRegistry();
// Body
this.baseEventList = getBaseEventList();
FilterList<T> filterList = new FilterList<T>(baseEventList);
SortedList<T> sortedList = new SortedList<T>(filterList, null);
bodyLayer = new FullFeaturedBodyStackLayer<ConsoleEntry>(sortedList, rowIdAccessor, propertyNames,configRegistry);
this.bodyDataProvider = bodyLayer.getBodyDataProvider();
registerConfigCells(configRegistry);
registerCheckBoxEditor(configRegistry);
// Column header
FullFeaturedColumnHeaderLayerStack<T> columnHeaderLayer = new FullFeaturedColumnHeaderLayerStack<T>(sortedList, filterList, propertyNames, propertyToLabelMap, bodyLayer, bodyLayer.getSelectionLayer(),
configRegistry);
// Row header
final DefaultRowHeaderDataProvider rowHeaderDataProvider = new DefaultSummaryRowHeaderDataProvider(
this.bodyDataProvider);
DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
rowHeaderDataLayer.setDefaultColumnWidth(50);
ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, bodyLayer, bodyLayer.getSelectionLayer());
// Corner
final DefaultCornerDataProvider cornerDataProvider = new DefaultCornerDataProvider(
columnHeaderLayer.getColumnHeaderDataProvider(), rowHeaderDataProvider);
DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, columnHeaderLayer);
// Grid
GridLayer gridLayer = new GridLayer(bodyLayer, columnHeaderLayer, rowHeaderLayer, cornerLayer);
this.natTable = new NatTable(parent, gridLayer, false);
this.natTable.setConfigRegistry(configRegistry);
this.natTable.addConfiguration(new StyledRowHeaderConfiguration());
this.natTable.addConfiguration(new StyledColumnHeaderConfiguration());
this.natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
// Popup menu
this.natTable.addConfiguration(new HeaderMenuConfiguration(this.natTable) {
#Override
protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
return super.createColumnHeaderMenu(natTable).withColumnChooserMenuItem();
}
});
this.natTable.addConfiguration(new SingleClickSortConfiguration());
// Editing
ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(
bodyLayer.getBodyDataLayer());
bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(columnLabelAccumulator);
columnLabelAccumulator.registerColumnOverrides(0, COLUMN_BOOKMARK_LABEL);
this.natTable.addConfiguration(editableGridConfiguration(columnLabelAccumulator, this.bodyDataProvider));
this.natTable.addConfiguration(filterRowConfiguration());
bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(getConfigLabelAccumulator(bodyLayer.getBodyDataLayer()));
// Preserve selection on updates and sort
final SelectionLayer selectionLayer = bodyLayer.getSelectionLayer();
final RowSelectionModel<ConsoleEntry> rowSelectionModel = new RowSelectionModel<ConsoleEntry>(selectionLayer,
this.bodyDataProvider, rowIdAccessor);
selectionLayer.setSelectionModel(rowSelectionModel);
// Select complete rows
RowOnlySelectionConfiguration<ConsoleEntry> selectionConfig = new RowOnlySelectionConfiguration<ConsoleEntry>();
selectionLayer.addConfiguration(selectionConfig);
// this.natTable.addConfiguration(new RowOnlySelectionBindings());
rowSelectionProviderNatTable = new RowSelectionProvider<ConsoleEntry>(selectionLayer,
this.bodyDataProvider);
if (this.bodyDataProvider.getList() != null && this.bodyDataProvider.getList().size() > 0) {
rowSelectionProviderNatTable.setSelection(new StructuredSelection(this.bodyDataProvider.getList().get(0)));
}
LayerListenerFixture listener = new LayerListenerFixture();
// we register the listener to the SelectionLayer because for some cases
// like clearing a collection, the selection change is not propagated
// the layer stack upwards as it gets stopped on layer conversion
selectionLayer.addLayerListener(listener);
// Column chooser
DisplayColumnChooserCommandHandler columnChooserCommandHandler = new DisplayColumnChooserCommandHandler(
selectionLayer, bodyLayer.getColumnHideShowLayer(), columnHeaderLayer.getColumnHeaderLayer(),
columnHeaderLayer.getColumnHeaderDataLayer(), null, null);
bodyLayer.registerCommandHandler(columnChooserCommandHandler);
this.natTable.configure();
return this.natTable;
}
Here is the code to registeryCheckBoxEditor & editableGridConfiguration
private void registerCheckBoxEditor(IConfigRegistry configRegistry) {
// make checkbox cells editable
configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE,
DisplayMode.EDIT, COLUMN_BOOKMARK_LABEL);
configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new CheckBoxCellEditor(),
DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);
final CheckBoxPainter checkBoxCellPainter = new CheckBoxPainter();
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, checkBoxCellPainter,
DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);
configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER,
new DefaultBooleanDisplayConverter(), DisplayMode.NORMAL, COLUMN_BOOKMARK_LABEL);
}
public AbstractRegistryConfiguration editableGridConfiguration(
final ColumnOverrideLabelAccumulator columnLabelAccumulator, final IDataProvider dataProvider) {
return new AbstractRegistryConfiguration() {
#Override
public void configureRegistry(IConfigRegistry configRegistry) {
columnLabelAccumulator.registerColumnOverrides(0, COLUMN_BOOKMARK_LABEL);
registerCheckBoxEditor(configRegistry, new CheckBoxPainter(), new CheckBoxCellEditor());
configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE,
IEditableRule.ALWAYS_EDITABLE, DisplayMode.EDIT, COLUMN_BOOKMARK_LABEL);
}
};
}
I have done all the settings similar to Example code but trigger mouse events are not working. Any pointer or help is really appreciated. TIA.

Related

java.lang.IllegalStateException: Can't move a node from one state tree to another - Vaadin

Why does I get this error when I close the tab in my web browser and go back to the same URL page again?
Error:
java.lang.IllegalStateException: Can't move a node from one state tree to another. If this is intentional, first remove the node from its current state tree by calling removeFromTree
Cause:
In this case, it's about Vaadin 14 where I'm using the AppLayout class to set its components.
HorizontalLayout firstRow = new HorizontalLayout(loggerId, calibration, alarm, showSamples, samplingTime);
HorizontalLayout secondRow = new HorizontalLayout(do0SliderLayout, do1SliderLayout, do2SliderLayout, do3SliderLayout);
HorizontalLayout thirdRow = new HorizontalLayout(updatePlot, loggingActivate);
thirdRow.setAlignItems(Alignment.CENTER);
VerticalLayout layout = new VerticalLayout(firstRow, secondRow, thirdRow, apexChart);
setContent(layout);
Suggestion:
I think I need to clean up the content before I can set the layout again?
Question:
Do you know how to remove the node from state tree to another?
How to reproduce the error:
Copy over this to your IDE and run the code with Vaadin 14. Access the route, then close your web browser. Open your web browser again and access the route again. This code is a minimal example. I have removed so much I can.
The you will have this error:
#Route("")
#CssImport("./styles/shared-styles.css")
#CssImport(value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field")
#Push
#PreserveOnRefresh
public class MainView extends AppLayout {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String START_LOGGING = "Start logging";
public static final String STOP_LOGGING = "Stop logging";
static public Boolean selectedUpdatePlot = false;
static public Integer selectedShowSamples = 10; // Minimum
static public Integer selectedSamplingTime = 0;
static public Long selectedAID = 0L;
static public Long selectedCID = 0L;
static public Long selectedLoggerId = 0L;
static public ApexCharts apexChart;
static public PaperSlider do0Slider;
static public PaperSlider do1Slider;
static public PaperSlider do2Slider;
static public PaperSlider do3Slider;
static public AtomicBoolean loggingNow;
static public ControlThread control;
#PostConstruct
public void init() {
// Set the top and the tabs
Top top = new Top();
top.setTopAppLayout(this);
// Set the chart
if(apexChart == null)
apexChart = new Graf().getApexChart();
// Create layout for slider 0
if(do0Slider == null) {
do0Slider = new PaperSlider(4095);
}
// Create layout for slider 1
if(do1Slider == null) {
do1Slider = new PaperSlider(4095);
}
// Create layout for slider 2
if(do2Slider == null) {
do2Slider = new PaperSlider(4095);
}
// Create layout for slider 3
if(do3Slider == null) {
do3Slider = new PaperSlider(4095);
}
// This variable controls the logging thread
if(loggingNow == null) {
loggingNow = new AtomicBoolean();
}
// Create control panel
updateControlPanel();
// Start the tread
if(control == null) {
control = new ControlThread(UI.getCurrent());
control.start();
}
}
private void updateControlPanel() {
// Set the logger ids
List<UserLogg> userLoggers = new ArrayList<Long>();
Select<Long> loggerId = new Select<>();
ArrayList<Long> loggerIds = new ArrayList<Long>();
loggerIds.add(selectedLoggerId);
for(int i = 0; i < userLoggers.size(); i++) {
loggerIds.add(userLoggers.get(i).getLoggerId());
}
loggerId.setItems(loggerIds);
loggerId.setValue(selectedLoggerId);
loggerId.addValueChangeListener(e -> {
selectedLoggerId = loggerId.getValue();
});
// Set the calibration id
List<CalibrationLogg> calibrationsLoggers = new ArrayList<Long>();
Select<Long> calibration = new Select<>();
ArrayList<Long> CIDs = new ArrayList<Long>();
CIDs.add(selectedCID);
for(int i = 0; i < calibrationsLoggers.size(); i++) {
CIDs.add(calibrationsLoggers.get(i).getCID());
}
calibration.setItems(CIDs);
calibration.setValue(selectedCID);
calibration.addValueChangeListener(e -> {
selectedCID = calibration.getValue();
});
// Set the alarm id
List<AlarmLogg> alarmsLoggers = new ArrayList<Long>();
Select<Long> alarm = new Select<>();
ArrayList<Long> AIDs = new ArrayList<Long>();
AIDs.add(selectedAID);
for(int i = 0; i < alarmsLoggers.size(); i++) {
AIDs.add(alarmsLoggers.get(i).getAID());
}
alarm.setItems(AIDs);
alarm.setValue(selectedAID);
alarm.addValueChangeListener(e -> {
selectedAID = alarm.getValue();
});
// Slider 0
VerticalLayout do0SliderLayout = new VerticalLayout(new Label("DO0"), do0Slider);
do0SliderLayout.setAlignItems(Alignment.CENTER);
do0Slider.setEnabled(false);
// Slider 1
VerticalLayout do1SliderLayout = new VerticalLayout(new Label("DO1"), do1Slider);
do1SliderLayout.setAlignItems(Alignment.CENTER);
do1Slider.setEnabled(false);
// Slider 2
VerticalLayout do2SliderLayout = new VerticalLayout(new Label("DO2"), do2Slider);
do2SliderLayout.setAlignItems(Alignment.CENTER);
do2Slider.setEnabled(false);
// Slider 3
VerticalLayout do3SliderLayout = new VerticalLayout(new Label("DO3"), do3Slider);
do3SliderLayout.setAlignItems(Alignment.CENTER);
do3Slider.setEnabled(false);
// Sampling time for the thread
IntegerField samplingTime = new IntegerField();
samplingTime.setValue(selectedSamplingTime);
samplingTime.addValueChangeListener(e -> {
if(e.getValue() < 10) {
samplingTime.setValue(10);
selectedSamplingTime = 10;
}
selectedSamplingTime = samplingTime.getValue();
});
// Show amount of samples at the plot
Select<Integer> showSamples = new Select<Integer>();
showSamples.setItems(new Integer[] {10, 20, 30, 40, 50});
showSamples.setValue(selectedShowSamples);
showSamples.addValueChangeListener(e -> {
selectedShowSamples = showSamples.getValue();
});
// Check box if we want to show the plot or not
Checkbox updatePlot = new Checkbox();
updatePlot.setLabel("Plot");
updatePlot.setValue(selectedUpdatePlot);
updatePlot.addValueChangeListener(e -> {
selectedUpdatePlot = updatePlot.getValue();
});
// Start and stop button for logging
Button loggingActivate = new Button(START_LOGGING);
if(loggingNow.get() == true)
loggingActivate.setText(STOP_LOGGING);
loggingActivate.addClickListener(e -> {
if(loggingNow.get() == false) {
loggingActivate.setText(STOP_LOGGING);
calibration.setEnabled(false);
alarm.setEnabled(false);
loggerId.setEnabled(false);
do0Slider.setEnabled(true);
do1Slider.setEnabled(true);
do2Slider.setEnabled(true);
do3Slider.setEnabled(true);
samplingTime.setEnabled(false);
showSamples.setEnabled(false);
updatePlot.setEnabled(false);
loggingNow.set(true);
}else{
loggingActivate.setText(START_LOGGING);
calibration.setEnabled(true);
alarm.setEnabled(true);
loggerId.setEnabled(true);
do0Slider.setEnabled(false);
do1Slider.setEnabled(false);
do2Slider.setEnabled(false);
do3Slider.setEnabled(false);
samplingTime.setEnabled(true);
showSamples.setEnabled(true);
updatePlot.setEnabled(true);
loggingNow.set(false);
do0Slider.setValue(0);
do1Slider.setValue(0);
do2Slider.setValue(0);
do3Slider.setValue(0);
}
});
// Layout
HorizontalLayout firstRow = new HorizontalLayout(loggerId, calibration, alarm, showSamples, samplingTime);
HorizontalLayout secondRow = new HorizontalLayout(do0SliderLayout, do1SliderLayout, do2SliderLayout, do3SliderLayout);
HorizontalLayout thirdRow = new HorizontalLayout(updatePlot, loggingActivate);
thirdRow.setAlignItems(Alignment.CENTER);
VerticalLayout layout = new VerticalLayout(firstRow, secondRow, thirdRow, apexChart);
setContent(layout);
}
}
And a thread
public class ControlThread extends Thread{
private UI ui;
public ControlThread(UI ui) {
this.ui = ui;
}
#Override
public void run() {
while(true) {
}
}
}
Update:
Here is a very minimal code example.
I'm using Vaadin 14.2.1 with OpenJDK 11
#Route("test")
#CssImport("./styles/shared-styles.css")
#CssImport(value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field")
public class TestView extends AppLayout {
/**
*
*/
private static final long serialVersionUID = 1L;
static public PaperSlider do0Slider;
#PostConstruct
public void init() {
// Set the slider
if(do0Slider == null) {
do0Slider = new PaperSlider(4095);
}
setContent(do0Slider);
}
}
And the paper-slider from Vaadin dev team.
#Tag("paper-slider")
#NpmPackage(value = "#polymer/paper-slider",
version = "3.0.1")
#JsModule("#polymer/paper-slider/paper-slider.js")
public class PaperSlider extends AbstractSinglePropertyField<PaperSlider, Integer> {
/**
*
*/
private static final long serialVersionUID = 1L;
public PaperSlider(int max) {
super("value", 0, false);
this.getElement().setProperty("max", max);
this.getElement().setProperty("pin", true);
}
}
Notice that if I use this test example:
#Route("test")
#CssImport("./styles/shared-styles.css")
#CssImport(value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field")
public class TestView extends AppLayout {
/**
*
*/
private static final long serialVersionUID = 1L;
static public ApexCharts apexChart;
#PostConstruct
public void init() {
// Set the chart
if(apexChart == null)
apexChart = new Graf().getApexChart();
setContent(apexChart);
}
}
With the plot class. I know that Apex Chart's is a third library for Vaadin. But it gives the same error as Paper-Slider.
#Data
public class Graf {
private ApexCharts apexChart;
private XAxis xAxis;
public Graf() {
apexChart = ApexChartsBuilder.get()
.withChart(ChartBuilder.get()
.withType(Type.line)
.withZoom(ZoomBuilder.get()
.withEnabled(true)
.build())
.withToolbar(ToolbarBuilder.get()
.withShow(true)
.build())
.withAnimations(AnimationsBuilder.get()
.withEnabled(false)
.build())
.build())
.withLegend(LegendBuilder.get()
.withShow(true)
.build())
.withDataLabels(DataLabelsBuilder.get()
.withEnabled(false)
.build())
.withColors("#48912c", "#13ebd5", "#215ed9", "#e6c222", "#a524e0", "#633326") // PWM1, PWM2, PMW4, Temp1, Temp2
.withTooltip(TooltipBuilder.get()
.withEnabled(false)
.build())
.withStroke(StrokeBuilder.get()
.withCurve(Curve.straight)
.build())
.withTitle(TitleSubtitleBuilder.get()
.withText("MySQL")
.withAlign(Align.left)
.build())
.withGrid(GridBuilder.get()
.withRow(RowBuilder.get()
.withColors("#f3f3f3", "transparent")
.withOpacity(0.5)
.build())
.build())
.withYaxis(YAxisBuilder.get()
.withTitle(TitleBuilder.get()
.withText("Measurements")
.build())
.build())
.withXaxis(XAxisBuilder.get()
.withTitle(com.github.appreciated.apexcharts.config.xaxis.builder.TitleBuilder.get()
.withText("Time")
.build())
.withCategories("")
.build())
.withSeries(new Series<>("desktop", 1, 2, 3))
.build();
apexChart.setWidthFull();
}
}
One bug related to this was fixed in Vaadin 14.2.1.

RadioGroupButton deselect value when button is clicked in Vaadin 14

I've been working on an online exam project and currently adding some multiple choice feature. My problem is, each time I moved to the next question the value from the previous radiogroupbutton is removed/deselect. But still the assigned value of the object is present.
I tried removing/adding the component as well, still the selected value for the RadioGroupButton is missing.
public class TestQuestionaire extends Dialog {
TQCoverageService tqcs = new TQCoverageServiceImpl();
CellItemService cis = new CellItemServiceImpl();
ItemKeyService iks = new ItemKeyServiceImpl();
VerticalLayout mainLayout;
TQCoverage tqCoverage;
List<CellItem> ciList = new ArrayList();
Map<CellItem, CellItemOption> cellItemAnswerMap = new HashMap();
CellItem cellItem;
Binder<CellItem> binder;
private int tqCoverageId;
private int cellItemIndex = 0;
private int cellItemIndexSize = 0;
private int score = 0;
Button next;
Button prev;
String stem;
Paragraph stemHolder;
RadioButtonGroup<CellItemOption> cioGroup;
public TestQuestionaire(int tqCoverageId) {
this.tqCoverageId = tqCoverageId;
tqCoverage = tqcs.findTQCoverage(tqCoverageId);
cellItemIndexSize = tqCoverage.getTotalItems();
for(TQItems tqi : tqcs.findAllTQItems(tqCoverageId)){
cellItem = cis.findCellItem(tqi.getCellItemId());
List<CellItemOption> cioList = cis.findAllItemOptions(tqi.getCellItemId());
cellItem.setCellItemOptionList(cioList);
ItemKey ik = iks.findItemKey(tqi.getItemKeyId());
cellItem.setItemKey(ik);
TQAnswerKey tqak = tqcs.findTQAnswerKeyByTQItem(tqi.getTqItemId());
cellItem.setTQAnswerKey(tqak);
cellItemAnswerMap.put(cellItem, new CellItemOption());
ciList.add(cellItem);
}
stemHolder = new Paragraph();
stemHolder.setWidthFull();
stemHolder.getStyle().set("font-weight", "500");
Hr hr = new Hr();
hr.setWidthFull();
cioGroup = new RadioButtonGroup<>();
cioGroup.setRenderer(new TextRenderer<>(CellItemOption::getCellItemOption));
cioGroup.addThemeVariants(RadioGroupVariant.LUMO_VERTICAL);
cioGroup.addValueChangeListener(event -> {
if(event.getValue() == null){
return;
}
if(!event.getValue().equals(event.getOldValue())){
cellItemAnswerMap.replace(getCellItem(), event.getValue());
}
});
mainLayout = new VerticalLayout(stemHolder, hr, cioGroup);
mainLayout.setWidth("600px");
hr = new Hr();
hr.setWidthFull();
mainLayout.add(hr);
binder = new Binder();
binder.forField(cioGroup)
.bind(CellItem::getCellItemOption, CellItem::setCellItemOption);
changeCellItem();
prev = new Button(VaadinIcon.BACKWARDS.create());
prev.addClickListener(event -> {
cellItemIndex--;
if(cellItemIndex == 0){
prev.setEnabled(false);
next.setEnabled(true);
} else {
prev.setEnabled(true);
next.setEnabled(true);
}
changeCellItem();
});
prev.setEnabled(false);
next = new Button(VaadinIcon.FORWARD.create());
next.getStyle().set("margin-left", "490px");
next.addClickListener(event -> {
cellItemIndex++;
if((cellItemIndex + 1) == cellItemIndexSize){
next.setEnabled(false);
prev.setEnabled(true);
} else {
next.setEnabled(true);
prev.setEnabled(true);
}
changeCellItem();
});
//this button is only to test if the current value for radiobuttongroup is removed/deselect when clicked!!
mainLayout.add(new Button("TEST", event -> {
changeCellItem();
}));
HorizontalLayout buttons = new HorizontalLayout(prev, next);
buttons.setWidthFull();
buttons.setJustifyContentMode(FlexComponent.JustifyContentMode.START);
mainLayout.add(buttons);
add(mainLayout);
open();
}
//refresh components for new/previous set if item
private void changeCellItem(){
stemHolder.removeAll();
cellItem = ciList.get(getCellItemIndex());
stem = cellItem.getItem().replace("{key}", cellItem.getItemKey().getItemKey());
stemHolder.add(stem);
cioGroup.clear();
cioGroup.setItems(cellItem.getCellItemOptionList());
cellItem.setCellItemOption(cellItemAnswerMap.get(cellItem));
binder.readBean(cellItem);
//binder.setBean(cellItem);
}
public TQCoverage getTQCoverage() {
return tqCoverage;
}
public CellItem getCellItem() {
return cellItem;
}
public int getCellItemIndex() {
return cellItemIndex;
}
public int getCellItemIndexSize() {
return cellItemIndexSize;
}
}

How do I display a table in Vaadin?

I've got two classes in my Vaadin 7 project. I'm having a hard time displaying the table in my main UI class. MyTable.java and DocUI.java. How can I get my table to show/display in DocUI.java when I load localhost:8080?
public class MyTable extends DocUI{
public MyTable() {
Table table = new Table("The Brightest Stars");
table.addContainerProperty("Name", String.class, null);
table.addContainerProperty("Mag", Float.class, null);
Object newItemId = table.addItem();
Item row1 = table.getItem(newItemId);
row1.getItemProperty("Name").setValue("Sirius");
row1.getItemProperty("Mag").setValue(-1.46f);
table.addItem(new Object[] {"Canopus", -0.72f}, 2);
table.addItem(new Object[] {"Arcturus", -0.04f}, 3);
table.addItem(new Object[] {"Alpha Centauri", -0.04f}, 4);
table.setPageLength(table.size());
}
}
public class DocUI extends UI {
// new addition 4/28
public String[] userString = { "jacob.smith#example.com",
"isabella.johnson#example.com", "ethan.williams#example.com",
"emma.jones#example.com", "michael.brown#example.com" };
// create combo box
public ComboBox comboBox1 = new ComboBox("Random Combo Box") {
};
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = DocUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
Button button2 = new Button("I am button 2");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
layout.addComponent(new Label("Thank you for clicking"));
}
});
#SuppressWarnings("deprecation")
FieldGroup form = new FieldGroup();
layout.setSizeFull();
layout.addComponent(button);
layout.addComponent(button2);
addComponent(MyTable.table);
//new addition 4/28
layout.addComponent(comboBox1);
comboBox1.setInputPrompt("Select a value");
comboBox1.addItems("--add new user--", "jacob.smith#example.com", "isabella.johnson#example.com","ethan.williams#example.com","emma.jones#example.com","michael.brown#example.com");
}
}
Do you know Java ?
DonĀ“t extend from UI in MyTable.
public class MyTable{
private Table table;
public MyTable() {
this.table = new Table("The Brightest Stars");
/* do something with table */
}
public function getTable() {
return this.table;
}
}
Know you can create a MyTable-Object and then use it to getTable and add it to the layout.

How to add data to the GXT Grid properly?

I have a webapp in which I need to get some data from the file and fill to the table. Here is the code of the page with this table:
public class Rules extends ContentPanel{
private final ServerManagementAsync serverManagementSvc = GWT.create(ServerManagement.class);
private ArrayList<PropertyItem> propslist;
private ArrayList<PropertyItem> itemArrayList;
private EditorGrid<PropertyItem> grid;
public Rules(final String customerId){
setLayout(new FlowLayout(10));
List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
ColumnConfig column = new ColumnConfig();
column.setId("name");
column.setHeader("Name");
column.setWidth(220);
TextField<String> text = new TextField<String>();
text.setAllowBlank(false);
column.setEditor(new CellEditor(text));
configs.add(column);
column = new ColumnConfig();
column.setId("type");
column.setHeader("Type");
column.setWidth(220);
TextField<String> typeText = new TextField<String>();
typeText.setAllowBlank(false);
column.setEditor(new CellEditor(typeText));
configs.add(column);
column = new ColumnConfig();
column.setId("value");
column.setHeader("Value");
column.setWidth(220);
configs.add(column);
final ListStore<PropertyItem> store = new ListStore<PropertyItem>();
propslist = getPropslist(customerId);
for (PropertyItem propertyItem: propslist){
store.insert(propertyItem, 0);
}
ColumnModel cm = new ColumnModel(configs);
setHeading("Settings");
setFrame(true);
setWidth(600);
setLayout(new FitLayout());
grid = new EditorGrid<PropertyItem>(store, cm);
grid.setAutoExpandColumn("name");
grid.setBorders(true);
add(grid);
ToolBar toolBar = new ToolBar();
setTopComponent(toolBar);
setButtonAlign(Style.HorizontalAlignment.RIGHT);
addButton(new Button("Refresh", new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
store.insert(getPropslist(customerId), 5);
}
}));
addButton(new Button("Add", new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
store.commitChanges();
}
}));
}
public ArrayList<PropertyItem> getPropslist(String customerId){
itemArrayList = new ArrayList<PropertyItem>();
AsyncCallback<ArrayList<PropertyItem>> callback = new AsyncCallback<ArrayList<PropertyItem>>() {
#Override
public void onFailure(Throwable throwable) {
}
#Override
public void onSuccess(ArrayList<PropertyItem> propertyItems) {
itemArrayList = propertyItems;
Window.alert("read successful");
}
}
};
serverManagementSvc.getProperties(customerId, callback);
return itemArrayList;
}
}
When I run my app I See only columns names and no data in the cells(and no cells of course). As the example I used this one: Ext GWT 2.2.6 Explorer(Grid)
I don't understand what could cause such proplem. What can be the reason of this?
Because your propsList is being populated Asynchronously the grid is being rendered before the server call returns.
To fix this first make the store a private property like the grid
Next, move the code that populates your store:
for (PropertyItem propertyItem: propslist){
store.insert(propertyItem, 0);
}
into the onSuccess Method of your callback.
Lastly, you may also need to call :
grid.reconfigure(grid.getStore(), grid.getColumnModel());
Just to get the Grid to render again.

Creating context menu only for a particular item selected in the Tree Viewer

I have a TreeViewer, and I created a context menu with some actions.
With this code snippet below, I get the context menu for all tree items.
protected void createMasterPart(final IManagedForm managedForm, final Composite parent)
{
Tree t = toolkit.createTree(client, SWT.NULL);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 20;
gd.widthHint = 100;
t.setLayoutData(gd);
toolkit.paintBordersFor(client);
section.setClient(client);
final SectionPart spart = new SectionPart(section);
managedForm.addPart(spart);
viewer = new TreeViewer(t);
viewer.addSelectionChangedListener(new ISelectionChangedListener()
{
public void selectionChanged(SelectionChangedEvent event)
{
managedForm.fireSelectionChanged(spart, event.getSelection());
}
});
viewer.setContentProvider(new MasterTreeContentProvider());
viewer.setInput(page.getEditor().getEditorInput());
m_newKeyAction = new AddNewKeyAction(viewer, parent.getShell());
m_newValueAction = new AddNewValueAction(viewer, parent.getShell());
hookContextMenu();
}
private void hookContextMenu()
{
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager)
{
fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
}
protected void fillContextMenu( IMenuManager manager )
{
manager.add( m_newKeyAction );
manager.add( m_newValueAction );
}
I want this context menu to be displayed only for tree items of particular type.
Please let me know how do I get this done.

Categories