how can we use combos in jface tableviewer columns - eclipse

I am reading excel data and taking headers(only first row) as my columns and added to list and this list is added as input to my tableviewer to display data in my table.I am creating tablecolumns and added the label provider. I am able to see the data in the table. Now i want to display the all textboxes as combos in each column . How can i can add combos for each column? my code is like
my tableviewer class
public class TableViewerExample {
public TableViewerExample(Shell shell) {
TableViewer viewer = new TableViewer(shell, SWT.BORDER | SWT.FULL_SELECTION);
TableViewerColumn upDownColumn = new TableViewerColumn(viewer, SWT.NONE);
upDownColumn.getColumn().setText("Display Order");
upDownColumn.getColumn().setWidth(200);
upDownColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getDisplayOrder();
}
});
TableViewerColumn checkboxColumn = new TableViewerColumn(viewer, SWT.NONE);
checkboxColumn.getColumn().setText("Checkbox Selection");
checkboxColumn.getColumn().setWidth(200);
checkboxColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getCheckboxSelection();
}
});
TableViewerColumn uniqueFieldsColumn = new TableViewerColumn(viewer, SWT.NONE);
uniqueFieldsColumn.getColumn().setText("Unique Fields");
uniqueFieldsColumn.getColumn().setWidth(200);
uniqueFieldsColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getUniqueFields();
}
});
TableViewerColumn inputFieldNameColumn = new TableViewerColumn(viewer, SWT.NONE);
inputFieldNameColumn.getColumn().setText("Input Field Name");
inputFieldNameColumn.getColumn().setWidth(200);
inputFieldNameColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getInputFieldName();
}
});
TableViewerColumn dataTypeColumn = new TableViewerColumn(viewer, SWT.NONE);
dataTypeColumn.getColumn().setText("Data Type");
dataTypeColumn.getColumn().setWidth(200);
dataTypeColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getDataType();
}
});
TableViewerColumn inputFieldFormatColumn = new TableViewerColumn(viewer, SWT.NONE);
inputFieldFormatColumn.getColumn().setText("Input Field Format");
inputFieldFormatColumn.getColumn().setWidth(200);
inputFieldFormatColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getInputFieldFormat();
}
});
TableViewerColumn displayNameColumn = new TableViewerColumn(viewer, SWT.NONE);
displayNameColumn.getColumn().setText("Display Name");
displayNameColumn.getColumn().setWidth(200);
displayNameColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getDisplayName();
}
});
TableViewerColumn displayFormatColumn = new TableViewerColumn(viewer, SWT.NONE);
displayFormatColumn.getColumn().setText("Display Format");
displayFormatColumn.getColumn().setWidth(200);
displayFormatColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return ((DataSourceModel) element).getDisplayFormat();
}
});
viewer.setContentProvider(ArrayContentProvider.getInstance());
System.out.println(RetrieveExcelData.getDataSourceFieldsList());
viewer.setInput(RetrieveExcelData.getDataSourceFieldsList());
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(true);
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new TableViewerExample(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
setinput class
public class RetrieveExcelData {
public static List getDataSourceFieldsList() {
String filename = "D:\\ServiceOrders_point_Org_morethan500.xlsx";
List<List<XSSFCell>> sheetData = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filename)) {
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet myExcelSheet = workbook.getSheetAt(0);
XSSFRow row = (XSSFRow )myExcelSheet.getRow(0);
Iterator cells=row.cellIterator();
List<XSSFCell> data = new ArrayList<>();
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return showExcelData(sheetData);
}
private static List showExcelData(List<List<XSSFCell>> sheetData) {
List<DataSourceModel> resultList = new ArrayList();
// Iterates the data and print it out to the console.
for (List<XSSFCell> data : sheetData) {
for (XSSFCell cell : data) {
DataSourceModel dataSourceModel=new DataSourceModel(cell.getStringCellValue(), cell.getStringCellValue(), cell.getStringCellValue(), cell.getStringCellValue(), cell.getStringCellValue(), cell.getStringCellValue(), cell.getStringCellValue(), cell.getStringCellValue());
resultList.add(dataSourceModel);
}
}
return resultList;
}
my model class
public class DataSourceModel {
private String displayOrder;
private String checkboxSelection;
private String uniqueFields;
private String inputFieldName;
private String dataType;
private String inputFieldFormat;
private String displayName;
private String displayFormat;
public DataSourceModel(String displayOrder,String checkboxSelection,String uniqueFields,String inputFieldName,String dataType, String inputFieldFormat, String displayName,String displayFormat) {
this.displayOrder=displayOrder;
this.checkboxSelection=checkboxSelection;
this.uniqueFields=uniqueFields;
this.inputFieldName=inputFieldName;
this.dataType=dataType;
this.inputFieldFormat=inputFieldFormat;
this.displayName=displayName;
this.displayFormat=displayFormat;
}
public String getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(String displayOrder) {
this.displayOrder = displayOrder;
}
public String getCheckboxSelection() {
return checkboxSelection;
}
public void setCheckboxSelection(String checkboxSelection) {
this.checkboxSelection = checkboxSelection;
}
public String getUniqueFields() {
return uniqueFields;
}
public void setUniqueFields(String uniqueFields) {
this.uniqueFields = uniqueFields;
}
public String getInputFieldName() {
return inputFieldName;
}
public void setInputFieldName(String inputFieldName) {
this.inputFieldName = inputFieldName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getInputFieldFormat() {
return inputFieldFormat;
}
public void setInputFieldFormat(String inputFieldFormat) {
this.inputFieldFormat = inputFieldFormat;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDisplayFormat() {
return displayFormat;
}
public void setDisplayFormat(String displayFormat) {
this.displayFormat = displayFormat;
}
and the table looks like
Now i want to make combos instead of text in the columns . Colud you please help how can i change to combos instead of text boxes using my code for all

Related

assertion failed: Unknown column layout data

When I create combo box in particular only one 3rd column using table viewer in Eclipse SWT.
I think I've done everything ok until now, however when I compile the code then i get error:
Code:
public void createPartControl(Composite parent) {
Composite tableComposite = new Composite(parent, SWT.NONE);
tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
true));
tableViewer = new TableViewer(tableComposite, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
// TODO viewer.setLabelProvider(new ViewLabelProvider());
table = tableViewer.getTable();
// Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = { "Threat Name", "Category Name", "Status",
"Priority", "Description", "Justification" };
int[] bounds = { 100, 100, 100, 100 };
TableViewerColumn col = createTableViewerColumn(titles[2], bounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
Dummy p = (Dummy) element;
return p.getValue();
}
});
col.setEditingSupport(new FirstValueEditingSupport(tableViewer));
}
private SelectionAdapter getSelectionAdapter(final TableColumn column,
final int index) {
SelectionAdapter selectionAdapter = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
tableViewer.refresh();
}
};
return selectionAdapter;
}
private static class Dummy {
public String value;
public Dummy(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static class FirstValueEditingSupport extends EditingSupport {
private final TableViewer viewer;
private final CellEditor editor;
private final String[] possibleValues = { "Mitigated",
"Not Applicable", "Not Started", "Needs Investigation" };
public FirstValueEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
this.editor = new ComboBoxCellEditor(viewer.getTable(),
possibleValues);
}
#Override
protected CellEditor getCellEditor(Object element) {
return editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
Dummy dummy = (Dummy) element;
int index = 0;
for (int i = 0; i < possibleValues.length; i++) {
if (Objects.equals(possibleValues[i], dummy.getValue())) {
index = i;
break;
}
}
return index;
}
#Override
protected void setValue(Object element, Object value) {
Dummy dummy = (Dummy) element;
int index = (Integer) value;
dummy.setValue(possibleValues[index]);
viewer.update(element, null);
}
}
private void fillRows(String shortdesc, String categ, String descp) {
System.out.println("fillRows call from above method.");
TableColumn status_Name_Col = tableViewer.getTable().getColumn(2);
System.out.println("**************** status_Name_Col ************ "
+ status_Name_Col);
tableViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
#Override
public void selectionChanged(
SelectionChangedEvent selectionChangedEvent) {
StructuredSelection selection = (StructuredSelection) selectionChangedEvent
.getSelection();
System.out.println(((Dummy) selection.getFirstElement())
.getValue());
}
});
List<Dummy> elements = new ArrayList<>();
for (int i = 0; i < Connection.Number_Of_Connection; i++) {
elements.add(new Dummy("First option"));
}
tableViewer.setInput(elements);
tableColumnLayout.setColumnData(status_Name_Col, new ColumnWeightData(
1, true));
tableViewerColumn.setEditingSupport(new FirstValueEditingSupport(
tableViewer));
}
Questions:
how to display combo box in particular only one column?
You must not do the TableViewer setInput call until you have set up everything on the table. All the content providers, label providers, column layouts, editing support, .... must be set before setInput is called.
You must also call setColumnData for every column you create.

GWT/GWT Bootstrap - Pagination (SimplePager)

I have a celltable and I'm trying implement pagination, but it doesn't work. I looked for solutions but without any success. I click in next page, nothing happens. I forgot to implement something? Someone can help me? Thanks for attention! Below, my implementation:
Java:
public class TaskPanel extends Composite {
private static TaskPanelUiBinder uiBinder = GWT
.create(TaskPanelUiBinder.class);
interface TaskPanelUiBinder extends UiBinder<Widget, TaskPanel> {
}
public TaskPanel() {
this.tableTask = createTableTask();
//Populate celltable
preencheListaTask();
initWidget(uiBinder.createAndBindUi(this));
}
#UiField(provided = true)
CellTable<Task> tableTask;
#UiField
AccordionGroup accordionTable;
#UiField Button btnRefresh;
#UiField SimplePager pager;
#UiField FormTaskPanel formTask;
List<Task> listTasks = new ArrayList<Task>();
ListDataProvider<Task> tableTaskProvider;
public List<Task> getListTasks() {
return this.listTasks;
}
public void setListTasks(List<Task> lista) {
this.listTasks = lista;
}
public TaskPanel getTaskPanel() {
return this;
}
//Create celltable
public CellTable<Task> createTableTask() {
tableTask = new CellTable<Task>();
tableTask.setPageSize(2);
TextColumn<Task> dataInicioColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getDataInicial();
}
};
tableTask.addColumn(dataInicioColumn, "Data Inicio");
TextColumn<Task> dataFinalColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getDataFinal();
}
};
tableTask.addColumn(dataFinalColumn, "Data Final");
TextColumn<Task> descricaoColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getDescricao();
}
};
tableTask.addColumn(descricaoColumn, "Descricao");
TextColumn<Task> categoriaColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getCategoria();
}
};
tableTask.addColumn(categoriaColumn, "Categoria");
TextColumn<Task> prioridadeColumn = new TextColumn<Task>() {
#Override
public String getValue(Task task) {
return task.getPrioridade();
}
};
tableTask.addColumn(prioridadeColumn, "Prioridade");
return tableTask;
}
//Generate a JSON, and I parse for List<Task> to populate celltable
public List<Task> preencheListaTask() {
final List<Task> lista = new ArrayList<Task>();
String url = "http://127.0.0.1:8888/financecontrol/jsonTableTasks.json";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println("Error to retrieve JSON");
}
#Override
public void onResponseReceived(Request arg0, Response response) {
if (200 == response.getStatusCode()) {
JSONValue value = JSONParser.parse(response.getText());
com.google.gwt.json.client.JSONObject taskObjs = value
.isObject();
JSONArray tasksArray = taskObjs.get("tasks").isArray();
if (tasksArray != null) {
for (int i = 0; i < tasksArray.size(); i++) {
com.google.gwt.json.client.JSONObject taskObj = tasksArray
.get(i).isObject();
String id = taskObj.get("ID").isNumber().toString();
String dataInicial = taskObj
.get("Data Inicial").isString()
.stringValue();
String dataFinal = taskObj.get("Data Final")
.isString().stringValue();
String descricao = taskObj.get("Descricao")
.isString().stringValue();
String categoria = taskObj.get("Categoria").isString().toString();
String prioridade = taskObj.get("Prioridade").isString().toString();
Task task = new Task(Integer.parseInt(id),
dataInicial, dataFinal,
descricao, categoria, prioridade);
lista.add(task);
}
setListTasks(lista);
System.out.println("JSON retrieve");
}
addLinhas();
} else {
System.out.println("Couldn't retrieve JSON ("
+ response.getStatusText() + ")");
}
}
});
} catch (RequestException e) {
System.err.println("Erro cath - " + e.getMessage());
}
return lista;
}
//add rows to celltable
public void addLinhas() {
this.tableTask.setRowCount(getListTasks().size(), true);
this.tableTask.setRowData(0, getListTasks());
tableTask.redraw();
tableTaskProvider = new ListDataProvider<Task>(getListTasks());
tableTaskProvider.addDataDisplay(tableTask);
//Pagination
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true);
pager.setDisplay(tableTask);
}
#UiHandler("btnRefresh")
public void onClickRefresh(ClickEvent e) {
preencheListaTask();
}
}
UiBinder:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:style>
.formContent {
height: 70%;
}
</ui:style>
<b:Container addStyleNames="{style.formContent}">
<r:FormTaskPanel ui:field="formTask"/>
<b:AccordionGroup ui:field="accordionTable" defaultOpen="false" heading="Task List">
<b:CellTable ui:field="tableTask" />
<b:SimplePager ui:field="pager" location="CENTER"/>
<b:Button ui:field="btnRefresh" text="Refresh" icon="REFRESH"/>
</b:AccordionGroup>
</b:Container>
You have pager = new SimplePager(...), so you have to declare #uiField(provided = true) for pager, and move pager declaration/initialisation into your createTableTask function (pager must be set before initwidget).

Cannot understand ComboBoxTableCell in a TableView

I have read everything available on this site and others; I have cut and pasted every line of code ever written on this subject ( am willing to bet). This is what the result is:
final class Books extends Group {
private TableView table = new TableView();
private ObservableList<Book> data = FXCollections.observableArrayList();
final HBox hb = new HBox();
final TextField Title = new TextField();
final TextField Author = new TextField();
final TextField Publisher = new TextField();
final TextField Copywrite = new TextField();
final TextField ISBN = new TextField();
final Boolean CheckedOut = false;
final Label Whom;
final Button addButton = new Button("Add");
Boolean FirstRead = true;
public static class Book {
private final SimpleStringProperty title;
private final SimpleStringProperty author;
private final SimpleStringProperty publisher;
private final SimpleStringProperty copywrite;
private final SimpleStringProperty isbn;
private final BooleanProperty checkedout;
private final SimpleStringProperty who;
Book(String Titl, String Auth, String Publ,
String Cpywrit, String IsBn, Boolean ChkdOut, String WHO) {
this.title = new SimpleStringProperty(Titl);
this.author = new SimpleStringProperty(Auth);
this.publisher = new SimpleStringProperty(Publ);
this.copywrite = new SimpleStringProperty(Cpywrit);
this.isbn = new SimpleStringProperty(IsBn);
this.checkedout = new SimpleBooleanProperty(ChkdOut);
this.who = new SimpleStringProperty(WHO);
}
public boolean isCheckedOut() {
return checkedout.get();
}
public void setCheckedOut(boolean international) {
this.checkedout.set(international);
}
public BooleanProperty isCheckedOutProperty() {
return checkedout;
}
public String getTitle() {
return title.get();
}
public void setTitle(String Title) {
title.set(Title);
}
public String getAuthor() {
return author.get();
}
public void setAutor(String Author) {
author.set(Author);
}
public String getPublisher() {
return publisher.get();
}
public void setPublisher(String Publisher) {
publisher.set(Publisher);
}
public String getCopywrite() {
return copywrite.get();
}
public void setCopywrite(String Copywrite) {
copywrite.set(Copywrite);
}
public String getIsbn() {
return isbn.get();
}
public void setIsbn(String ISBN) {
isbn.set(ISBN);
}
public Boolean getIo() {
return checkedout.get();
}
public void setIo(Boolean CheckedOut) {
checkedout.set(CheckedOut);
}
public String getWho() {
return who.get();
}
public void setWho(String Who) {
who.set(Who);
}
public ObservableValue<String> whoProperty() {
return who;
}
}
public Books(final File User) throws IOException {
this.Whom = new Label("inLibrary");
this.data = FXCollections.<Book>observableArrayList(
(Book bk) -> new Observable[]{bk.isCheckedOutProperty()
});
final PhoneList p = new PhoneList(User);
final Label label = new Label("Book List");
label.setFont(new Font("Arial", 20));
table.setPrefSize(600, 400);
table.setEditable(true);
TableColumn nameCol = bookName();
TableColumn authorCol = bookAuthor();
TableColumn publisherCol = bookPublisher();
TableColumn copywriteCol = bookCopywrite();
TableColumn isbnCol = bookISBN();
final TableColumn<Book, Boolean> ioCol = new TableColumn<>("In/Out");
ioCol.setMinWidth(50);
ioCol.setEditable(true);
ioCol.setCellValueFactory(new PropertyValueFactory<>("isCheckedOut"));
final Callback<TableColumn<Book, Boolean>, TableCell<Book, Boolean>> iocellFactory = CheckBoxTableCell.forTableColumn(ioCol);
ioCol.setCellFactory((TableColumn<Book, Boolean> column) -> {
TableCell<Book, Boolean> iocell = iocellFactory.call(column);
iocell.setAlignment(Pos.CENTER);
return iocell;
});
ioCol.setCellFactory(iocellFactor
final TableColumn<String, Book> whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
whoCol.setEditable(true);
whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
#Override
public String toString(Book string) {
return string.getWho();
}
#Override
public Book fromString(String string) {
return null;
}
}, data));
AddBook(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol, User);
data.addListener((javafx.collections.ListChangeListener.Change<? extends Book> change) -> {
while (change.next()) {
if (change.wasUpdated() && FirstRead != true) {
try {
System.out.println("List changed");
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
getChildren().addAll(vbox);
try {
readFile(User);
} catch (Exception ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
private TableColumn bookISBN() {
TableColumn isbnCol = new TableColumn("ISBN #");
isbnCol.setMinWidth(100);
isbnCol.setCellValueFactory(
new PropertyValueFactory<>("isbn"));
isbnCol.setCellFactory(TextFieldTableCell.forTableColumn());
return isbnCol;
}
private TableColumn bookCopywrite() {
TableColumn copywriteCol = new TableColumn("Copywrite");
copywriteCol.setMinWidth(100);
copywriteCol.setCellValueFactory(
new PropertyValueFactory<>("copywrite"));
copywriteCol.setCellFactory(TextFieldTableCell.forTableColumn());
return copywriteCol;
}
private TableColumn bookPublisher() {
TableColumn publisherCol = new TableColumn("Publisher");
publisherCol.setMinWidth(100);
publisherCol.setCellValueFactory(
new PropertyValueFactory<>("publisher"));
publisherCol.setCellFactory(TextFieldTableCell.forTableColumn());
return publisherCol;
}
private TableColumn bookAuthor() {
TableColumn authorCol = new TableColumn("Author");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(
new PropertyValueFactory<>("author"));
authorCol.setCellFactory(TextFieldTableCell.forTableColumn());
return authorCol;
}
private TableColumn bookName() {
TableColumn nameCol = new TableColumn("Title");
nameCol.setMaxWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<>("title"));
nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
return nameCol;
}
private void AddBook(TableColumn nameCol, TableColumn authorCol, TableColumn publisherCol,
TableColumn copywriteCol, TableColumn isbnCol, TableColumn ioCol, TableColumn whoCol, final File User) {
table.setItems(data);
table.getColumns().addAll(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol);
addButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
addBook();
try {
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void addBook() {
data.add(new Book(
Title.getText(),
Author.getText(),
Publisher.getText(),
Copywrite.getText(),
ISBN.getText(),
CheckedOut,
Whom.getText()
));
Title.clear();
Author.clear();
Publisher.clear();
Copywrite.clear();
ISBN.clear();
}
});
hb.getChildren().addAll(Title, Author, Publisher,
Copywrite, ISBN, addButton);
hb.setSpacing(10);
Title.setPromptText("Tile of Book");
Title.setMaxWidth(nameCol.getPrefWidth());
Author.setMaxWidth(authorCol.getPrefWidth());
Author.setPromptText("Author");
Publisher.setMaxWidth(publisherCol.getPrefWidth());
Publisher.setPromptText("Publisher");
Copywrite.setMaxWidth(copywriteCol.getPrefWidth());
Copywrite.setPromptText("Year Copywrite");
ISBN.setMaxWidth(isbnCol.getPrefWidth());
ISBN.setPromptText("ISBN #");
}
private void writeFile(File User) throws IOException {
File file = new File(User + "/Books.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
if (table.getItems() != null) {
data.stream().map((data1) -> {
if (data1.getTitle().equals("")) {
data1.setTitle("No_Title");
}
return data1;
}).map((data1) -> {
if (data1.getAuthor().equals("")) {
data1.setAutor("No_Author");
}
return data1;
}).map((data1) -> {
if (data1.getPublisher().equals("")) {
data1.setPublisher("No_Publisher");
}
return data1;
}).map((data1) -> {
if (data1.getCopywrite().equals("")) {
data1.setCopywrite("No_Copywrite");
}
return data1;
}).map((data1) -> {
if (data1.getIsbn().equals("")) {
data1.setIsbn("No_ISBN");
}
return data1;
}).map((data1) -> {
if (data1.getWho().equals("")) {
data1.setWho("InLibrary");
}
return data1;
}).map((data1) -> {
outFile.println(data1.getTitle());
return data1;
}).map((data1) -> {
outFile.println(data1.getAuthor());
return data1;
}).map((data1) -> {
outFile.println(data1.getPublisher());
return data1;
}).map((data1) -> {
outFile.println(data1.getCopywrite());
return data1;
}).map((data1) -> {
outFile.println(data1.getIsbn());
return data1;
}).map((data1) -> {
outFile.println(data1.getIo());
return data1;
}).forEach((data1) -> {
outFile.println(data1.getWho());
});
outFile.close();
}
}
private void readFile(File User) throws Exception {
try {
String name, author, publisher, copywrite, isbn, whom;
Boolean InOut;
try (Scanner inFile = new Scanner(new File(User + "/Books.txt"))) {
while (inFile.hasNextLine()) {
name = inFile.next();
author = inFile.next();
publisher = inFile.next();
copywrite = inFile.next();
isbn = inFile.next();
InOut = inFile.nextBoolean();
whom = inFile.next();
data.add(new Book(name, author, publisher, copywrite,
isbn, InOut, whom));
}
}
table.setItems(data);
} //insert catch statements
catch (FileNotFoundException exception) {
System.out.println("File not found");
} catch (ArrayIndexOutOfBoundsException AIOOBexception) {
System.out.println("Array Index is out of bounds");
} catch (IllegalArgumentException IAexception) {
System.out.println("Divide by zero error");
} catch (NoSuchElementException NAexception) {
}
FirstRead = false;
}
}
This gives the following error:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: mediatracker.Books$Book cannot be cast to java.lang.String
at mediatracker.Books$1.toString(Books.java:198)
Line 198 starts:
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
Can anyone type in the "theory" behind the ComboBoxTableCell, and list the parts necessary to accomoplish this. All I want to do is to change the value of the cell extracted from a PhoneList in another file.
I'm just going to assume that line 198 is
return (String) object ;
in the anonymous StringConverter's toString() method. When you post a question with a stack trace, always indicate which is the line in your code to which the exception is pointing.
First, it's always better to use generic types instead of raw types. So instead of
TableColumn whoCol = ...
you should have
TableColumn<S,T> whoCol = ...
where you replace S with the type of the data in the table and T with the type of the data in the column. Since you haven't given a complete example, I have no way of guessing what S is; from the error message it looks like the type of the data in the column might be Book.
Read the Javadocs for the method you are calling. They clearly state what the converter is:
converter - A StringConverter to convert the given item (of type T) to
a String for displaying to the user.
So, assuming that your TableColumn is displaying Books, and assuming data is of type ObservableList<Book>, you should have something like
ObservableList<Book> data = ... ;
TableColumn<S, Book> whoCol = new TableColumn<>("Who to");
// ...
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
#Override
public String toString(Book book) {
// assuming your Book class defines a getTitle() method, and that's
// how you want to display it in your ComboBox:
return book.getTitle(); // or get a String from book some other way
}
#Override
public Book fromString(String string) {
// I think this is not actually used, as the combo box is not editable
// So you could probably safely just return null here.
// But in general:
Book book = ... ; // create a book from the string
return book ;
}
}, data));
Again, you replace S by whatever you are using for the type of the TableView; and again I had to make guesses at the type of your TableColumn as you didn't provide a complete example. But this should be enough for you to get the idea.
`final TableColumn<Book, String> whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
whoCol.setEditable(true);
whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));
whoCol.setCellFactory(ComboBoxTableCell.<Book, String>forTableColumn(p.data.get(myIndex()).toString()));
whoCol.setOnEditCommit((TableColumn.CellEditEvent<Book, String> t) -> {
((Book) t.getTableView().getItems().get(
t.getTablePosition().getRow()))
.setWho(t.getNewValue());
try {
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
});`
This works - #James_D thank you for your aid - you sent me in the right direction
Your problems don't seem to have anything to do with a ComboBoxTableCell.
Your toString() method is wrong; you're trying to cast an Object to a String. That's (probably) why you're seeing a java.lang.ClassCastException. Can you verify which line is line 198?
Also, I notice all your fromString() method does is return its argument. What exactly are you trying to achieve here in this code snippet? Can you give us a little more background information?

Password Style TextCellEditor showing original characters in TableViewer

TextCellEditor passEdit has SWT.PASSWORD style. But when Add button was clicked original characters were shown instead of default * echo characters. Also focus listeners on passEdit were not working. i.e When user double clicks it should show original characters and on focus lost it should show password echo characters.
How to fix this?
public class UserAddSolution {
public static boolean flag = true;
private TextCellEditor userNameEdit;
private TextCellEditor passEdit;
class UserNamePassword {
private final String name;
private final String password;
public UserNamePassword(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
}
public UserAddSolution(final Shell shell) {
shell.setLayout(new GridLayout(2, false));
GridData layoutData = new GridData();
layoutData.heightHint = 300;
shell.setLayoutData(layoutData);
final TableViewer viewer = new TableViewer(shell, SWT.BORDER
| SWT.FULL_SELECTION | SWT.MULTI);
viewer.setContentProvider(ArrayContentProvider.getInstance());
Table table = viewer.getTable();
table.setLayout(new GridLayout());
table.setLayoutData(layoutData);
userNameEdit = new TextCellEditor(table);
passEdit = new TextCellEditor(table, SWT.PASSWORD);
final Text tex = (Text) passEdit.getControl();
final char echar = tex.getEchoChar();
tex.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
tex.setEchoChar(echar);
}
#Override
public void focusGained(FocusEvent e) {
tex.setEchoChar('\0');
}
});
viewer.setCellEditors(new CellEditor[] { userNameEdit, passEdit });
viewer.setCellModifier(new ICellModifier() {
#Override
public boolean canModify(Object element, String property) {
return true;
}
#Override
public Object getValue(Object element, String property) {
UserNamePassword ele = (UserNamePassword) element;
if (property.equals("1")) {
return ele.getName();
} else if (property.equals("2")) {
return ele.getPassword();
}
return "";
}
#Override
public void modify(Object element, String property, Object value) {
}
});
viewer.setColumnProperties(new String[] { "1", "2" });
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(
viewer) {
#Override
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
int feature = ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL
| ColumnViewerEditor.KEYBOARD_ACTIVATION;
TableViewerEditor.create(viewer, actSupport, feature);
TableViewerColumn userNameColumn;
userNameColumn = new TableViewerColumn(viewer, SWT.NONE);
userNameColumn.getColumn().setWidth(200);
userNameColumn.getColumn().setMoveable(true);
userNameColumn.getColumn().setText("Name");
userNameColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public Image getImage(Object element) {
return super.getImage(element);
}
#Override
public String getText(Object element) {
UserNamePassword fdf = (UserNamePassword) element;
return super.getText(fdf.getName());
}
});
TableViewerColumn passwordColumn;
passwordColumn = new TableViewerColumn(viewer, SWT.NONE);
passwordColumn.getColumn().setWidth(200);
passwordColumn.getColumn().setMoveable(true);
passwordColumn.getColumn().setText("Password");
passwordColumn.setLabelProvider(new ColumnLabelProvider() {
#Override
public Image getImage(Object element) {
return super.getImage(element);
}
#Override
public String getText(Object element) {
UserNamePassword fdf = (UserNamePassword) element;
return super.getText(fdf.getPassword());
}
#Override
public void update(ViewerCell cell) {
super.update(cell);
}
});
viewer.setInput(new ArrayList<UserNamePassword>());
table.setLinesVisible(true);
table.setHeaderVisible(true);
viewer.refresh();
Button add = new Button(shell, SWT.PUSH);
add.setText("Add");
add.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
viewer.add(new UserNamePassword("abc", "xyz"));
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new UserAddSolution(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
The ColumnLabelProvider is responsible for displaying the data in the table. The text widget appears only when you edit a cell. That's why you need to tell the label provider to mask characters and not to display the plain text.
As a consequence you don't need to set SWT.PASSWORD style to the passEdit since you want to display the password in the editor as plain text:
passEdit = new TextCellEditor(table, SWT.NONE);
You also don't need the FocusListener and you can set the echo char as a constant:
private static final String ECHARSTR = Character.toString((char)9679);
So you can remove 15 lines below the initialization of passEdit
I don't know if there is a solution for this in JFace (I think not) but you can easily solve this by modifying your existing label provider. My suggestion is to modify the getText() method of ColumnLabelProvider for passwordColumn as follows:
#Override
public String getText(Object element)
{
UserNamePassword fdf = (UserNamePassword)element;
return fdf.getPassword().replaceAll(".", ECHARSTR);
}

Jenkins plugin development - persistence

I'm still learning plugin dev. This is my first one.
I would like to persist the configuration of my plugin, but it won't work.
Could you please tell me, what am I doing wrong?
I have tried debuging the process, starting from the addition of the plugin to the job 'til the saving of the job config.
I have found, that inside the load() method of the descriptor, no xml file is found!
The path it is looking for is something like: c:\users\Peter\workspace\r-script.\work\whatEverDir\xy.xml
I don't think that the .\ part is causing the config file not to be found, but since it is a Jenkins class generating this path, I would not bet on it. Although the system might have tried to create it here at the first place.
Thanks in advance!
Scriptrunner.jelly
<f:block>
<f:entry title="RScript" field="command">
<f:textarea style="width:99%" />
</f:entry>
</f:block>
<f:entry field="installedPackages" title="Installed packages">
<f:select style="width:40%" />
</f:entry>
<f:entry field="mirrors" title="Choose a mirror">
<f:select style="width:40%" />
</f:entry>
<f:entry>
<f:repeatableProperty field="availablePackages" minimum="1"/>
</f:entry>
AvailablePackage.jelly
<f:entry field="availablePackages">
<f:select style="width:40%" />
<f:repeatableDeleteButton />
</f:entry>
ScriptRunner.java
public class ScriptRunner extends Builder {
private static final String fileExtension = ".R";
private ArrayList<AvailablePackage> availablePackages;
private String command;
private String chosenMirror;
private List<String> mirrorList = new ArrayList<String>();
#DataBoundConstructor
public ScriptRunner(String command, ArrayList<String> installedPackages, ArrayList<String> mirrors, ArrayList<AvailablePackage> availablePackages) {
this.chosenMirror = mirrors.get(0);
this.availablePackages = availablePackages;
this.command = command;
}
public final String getCommand() {
return command;
}
#Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException {
return perform(build, launcher, (TaskListener) listener);
}
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
TaskListener listener) throws InterruptedException {
FilePath workSpace = build.getWorkspace();
FilePath rScript = null;
if (workSpace == null) {
try {
throw new NoSuchFileException("Workspace could not be set!");
} catch (NoSuchFileException e) {
e.printStackTrace();
}
}
try {
try {
String fullScript;
if (command.contains("options(repos=structure(")) {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, "", command);
} else {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, chosenMirror, command);
}
rScript = workSpace.createTextTempFile("RScriptTemp",
getFileExtension(), fullScript, false);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToProduceScript()));
return false;
}
boolean successfullyRan = false;
try {
EnvVars envVars = build.getEnvironment(listener);
for (Map.Entry<String, String> e : build.getBuildVariables()
.entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
if (launcher.launch().cmds(buildCommandLine(rScript))
.envs(envVars).stdout(listener).pwd(workSpace).join() == 1) {
successfullyRan = true;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_CommandFailed()));
}
return successfullyRan;
} finally {
try {
if (rScript != null) {
rScript.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
} catch (Exception e) {
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
}
}
}
public String[] buildCommandLine(FilePath script) {
return new String[] { "Rscript", script.getRemote() };
}
protected String getFileExtension() {
return fileExtension;
}
public List<String> getMirrorList() {
return mirrorList;
}
public void setMirrorList(List<String> mirrorList) {
this.mirrorList = mirrorList;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
public ArrayList<AvailablePackage> getAvailablePackages() {
return availablePackages;
}
#Override
public ScriptBuildStepDescriptorImplementation getDescriptor() {
return (ScriptBuildStepDescriptorImplementation)super.getDescriptor();
}
#Extension
public static class ScriptBuildStepDescriptorImplementation extends
BuildStepDescriptor<Builder> {
private boolean showInstalled;
private String command;
private String chosenMirror;
private ArrayList<AvailablePackage> availablePackages;
public ScriptBuildStepDescriptorImplementation() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
#Override
public String getDisplayName() {
return "Advanced R script runner";
}
#Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public ListBoxModel doFillInstalledPackagesItems() {
ListBoxModel mirrors = new ListBoxModel();
Set<String> mirrorsList = PackagesManager.singleton()
.getInstalledPackages();
for (String entry : mirrorsList) {
mirrors.add(entry);
}
return mirrors;
}
public ListBoxModel doFillAvailablePackagesItems() {
ListBoxModel packages = new ListBoxModel();
List<String> packageList = PackagesManager.singleton().getAvailablePackages();
Set<String> alreadyInstalled = PackagesManager.singleton().getInstalledPackages();
for (String entry : packageList) {
if (!alreadyInstalled.contains(entry)) {
packages.add(entry);
}
}
return packages;
}
public ListBoxModel doFillMirrorsItems() {
ListBoxModel mirrors = new ListBoxModel();
String[] mirrorsList = MirrorManager.singleton().getMirrors();
int selected = 34;
for (int i = 0; i < mirrorsList.length; i++) {
String[] splitCurrent = mirrorsList[i].split(" - ");
if (chosenMirror != null && chosenMirror.equals(splitCurrent[1])) {
selected = i;
}
mirrors.add(splitCurrent[1], splitCurrent[0]);
}
mirrors.get(selected).selected = true;
return mirrors;
}
public boolean getShowInstalled() {
return showInstalled;
}
public void setShowInstalled(boolean showInstalled) {
this.showInstalled = showInstalled;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
}
}
AvailablePackage.java
public class AvailablePackage extends AbstractDescribableImpl<AvailablePackage> {
private String name;
#DataBoundConstructor
public AvailablePackage(String availablePackages) {
this.name = availablePackages;
}
public String getName() {
return name;
}
#Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
#Extension
public static class DescriptorImpl extends Descriptor<AvailablePackage> {
private String name;
public DescriptorImpl() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
public ListBoxModel doFillAvailablePackagesItems() {
return PackagesManager.singleton().getAvailablePackagesAsListBoxModel(name);
}
#Override
public String getDisplayName() {
return "";
}
public String getName() {
return name;
}
}
}
Sorry for the code formatting! First timer at stackoverflow code posting.
I think you may need to comment this line out
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
//return super.configure(req,formData);
return true;
}
as it will then save again but with no fields.
A good place to locate Jenkins plugin examples is in https://github.com/jenkinsci