DefaultTableModel modeltable = new DefaultTableModel(8,8);
table = new JTable(modeltable);
table.setBorder(BorderFactory.createLineBorder (Color.blue, 2));
int height = table.getRowHeight();
table.setRowHeight(height=50);
table.setColumnSelectionAllowed(true);
table.setDragEnabled(true);
le1.setFillsViewportHeight(true);
panel.add(table);
panel.setSize(400,400);
DnDListener dndListener = new DnDListener();
DragSource dragSource = new DragSource();
DropTarget dropTarget1 = new DropTarget(table, dndListener);
DragGestureRecognizer dragRecognizer2 = dragSource.
createDefaultDragGestureRecognizer(option1,
DnDConstants.ACTION_COPY, dndListener);
DragGestureRecognizer dragRecognizer3 = dragSource.
createDefaultDragGestureRecognizer(option2,
DnDConstants.ACTION_COPY, dndListener);
}
}
i have a problem with adding mouse listeners to "table" which is drop target, to accept drop component wherever it drops from the mouse. in this code when component drops in to a drop target it always goes to a default position. i cant customize the position on drop target. please someone help me with this.
thanks in advance
Those listeners are far too low-level. The appropriate approach for implementing dnd is to implement a custom TransferHandler and set that custom handler to your table.
public class MyTransferHandler extends TransferHandler {
public boolean canImport(TransferHandler.TransferSupport info) {
// we only import Strings
if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation();
// ... your code to decide whether the data can be dropped based on location
}
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop()) {
return false;
}
// Check for String flavor
if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
displayDropLocation("Table doesn't accept a drop of this type.");
return false;
}
JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation();
// ... your code to handle the drop
}
}
// usage
myTable.setTransferHandler(new MyTransferHandler());
For details, see the example in the online tutorial linked to in the Swing tag description, namely the chapter Drag and Drop The code snippet above is c&p'ed from the BasicDnD example.
Related
I'm on Vaadin 7.7 and I switch tables to the grid. Only I can not personalize my cells as I would like. Here I would like to add comboboxes on a column from an arraylist and retrieve the chosen value.
Here's some of my code:
Here I create my IndexedContainer
IndexedContainer indexedContainer = new IndexedContainer();
indexedContainer.addContainerProperty("Type de véhicule",String.class,"");
Here I add my items:
indexedContainer.addItem(listValue);
indexedContainer.getContainerProperty(listValue,
key.get(0)).setValue(
String.valueOf(listValue.get(0)));
Finally I put my object in editable and I use this function to do actions during the backup:
grid.getEditorFieldGroup().addCommitHandler(new FieldGroup.CommitHandler() {
#Override
public void preCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
}
#Override
public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
If you have any ideas or suggestions do not hesitate :)
Good night
You could use something like this:
List<String> values = obtainValues();
IndexedContainer container = new IndexedContainer();
//Add other properties...
container.addContainerProperty("comboBox", ComboBox.class, null);
//Do more stuff
ComboBox cb = new ComboBox();
cb.addItems(values);
item.getItemProperty("comboBox").setValue(cb);
And, in grid declaration, you may use an addon that allows grid to render components.
Grid grid = new Grid();
//Even more stuff
grid.setContainerDataSource(container);
grid.getColumn("comboBox").setRenderer(new ComponentRenderer());
To obtain the value of the comboBox:
Item item = container.getItem(itemId);
ComboBox cb = item.getItemProperty("comboBox").getValue();
String value = (String) cb.getValue();
Try this:
grid.getColumn("state").setEditorField(getComboState());
where getComboState is:
private Field<?> getComboState() {
ComboBox comboBox = new ComboBox();
comboBox.addItem("approve");
comboBox.addItem("no-approve");
comboBox.setImmediate(true);
comboBox.setNullSelectionAllowed(false);
return comboBox;
}
I try to update my JTable with the fireTableChanged() Method after i imported the names of spreadsheets from excel in my datastructure but the Method is not executed. I confirmed with a test that the data is correctly imported and that the jtable should have the necessary informationen.
What do i have to do that the JTable is correctly updated?
I found several other links to this topic but none of them worked for me:
Refresh Jtable
How to make JTable show refreshed data after updating database?
JTable How to refresh table model after insert delete or update the data.
AbstractDataTable fireTableDataChanged() does not refresh jtable
Can't refresh my JTable with new data
Model:
public class Model extends Observable {
String[][] data;
List<Arbeitsmappe> AMList = new LinkedList<>();
.....
public void setAMList(List<Arbeitsmappe> aMList) {
AMList = aMList; //new List replace the old
this.getData(); //The 2dimensional Array is filled with the names from the list
setChanged();
notifyObservers(Controller.Command_Excel_Eingelesen);
}
}
View:
JTextField cellEditorTF = new JTextField();
cellEditorTF.setEditable(false);
DefaultCellEditor cellEditor = new DefaultCellEditor(cellEditorTF);
ContentTable = new JTable(model.getData(), Model.columnNames);
//Cell Editable FALSE
ContentTable.getColumnModel().getColumn(0).setCellEditor(cellEditor);
//Single Interval Selection
ContentTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//Cell Listener - When Cell is edited the new informationen is safed in AMLISt
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
TableCellListener tcl = (TableCellListener)e.getSource();
Model.AMList.get(tcl.getRow()).Speichername = String.valueOf(tcl.getNewValue());
// System.out.println("Row: " + tcl.getRow() + " " + Model.data[tcl.getRow()][1]);
}
};
TableCellListener tcl = new TableCellListener(ContentTable, action);
JScrollPane scrollPane = new JScrollPane(ContentTable);
ContentTable.setFillsViewportHeight(true);
ContentTable.getTableHeader().setReorderingAllowed(false);
this.add(BorderLayout.NORTH,ButtonPanel);
this.add(BorderLayout.SOUTH,scrollPane);
}
#Override
public void update(Observable arg0, Object arg1) {
if(arg0 instanceof Model){
Model model = (Model) arg0;
String cmd = (String) arg1;
if(cmd.equals(Controller.Command_Excel_Eingelesen)){
((AbstractTableModel)ContentTable.getModel()).fireTableDataChanged();
ContentTable.repaint();
this.repaint();
}
}
((AbstractTableModel)ContentTable.getModel()).fireTableDataChanged(); is called out of models definitions, it should't be, must be part of code, class void that override AbstractTableModel and its methods
as aside this method reseting all custom properties for model, and important part of methods for JTable (e.g. override for XxxTableCellRenderer/Editor)
read API in part methods for fireTableXxxXxx, there are notifiers for all JTable/AbstractTableModel's lifecycle, be sure that youare used the correct notifier for every actions/event
So I'm having a heck of a time creating a Datagrid with GWT. I've created my table according the the docs for GWT, and I've added my data, but I can't get it or the datagrid itself to show up at all. What am I missing? I feel I've been tearing my hair out over this. I feel like making an aysnc call might be an issue, but I get no errors. When i compile and execute this portion of my code nothing shows up on the screen and the area where the datagrid is supposed to be on the dock is empty. Am I forgetting something trivial?
static int orderID = 1001;
private static List<OrderLine> orderLineList = new ArrayList<OrderLine>();
final DataGrid<OrderLine> dgOrder = new DataGrid<OrderLine>();
dgOrder.setWidth("100%");
//set columns
TextColumn<OrderLine> orderLineIdColumn = new TextColumn<OrderLine>(){
#Override
public String getValue(OrderLine object) {
return Integer.toString(object.getOrderLineID());
}
};
dgOrder.addColumn(orderLineIdColumn, "OrderLine ID");
TextColumn<OrderLine> productColumn = new TextColumn<OrderLine>(){
#Override
public String getValue(OrderLine object) {
return getProductName(object.getProductNumber());
}
};
dgOrder.addColumn(productColumn, "Product");
TextColumn<OrderLine> quantityColumn = new TextColumn<OrderLine>(){
#Override
public String getValue(OrderLine object) {
return Integer.toString(object.getQuantity());
}
};
dgOrder.addColumn(quantityColumn, "Quantity");
// add data to datagrid
Ioma.dataservice.getOrderLines(orderID, new AsyncCallback<ArrayList<OrderLine>>(){
#Override
public void onFailure(Throwable caught) {// TODO Auto-generated method stub
System.out.println("error in retrieving GP.getOrderLines" + caught.toString());
}
#Override
public void onSuccess(ArrayList<OrderLine> result) {
// TODO Auto-generated method stub
//yes i realize I could also set it to "result" but I use the result in other places as well, I have also tried setting it to result with no success
orderLineList = result;
dgOrder.setRowData(0, orderLineList);
}
});
//add datagrid to the dock
dock.add(dgOrder, DockPanel.EAST);
//add dock to mainPanel
return dock;
When you use the DataGrid you need to give it an explicit size. For CellTable you don't need to so that's why it worked.
When you were using the DataGrid is was there but had both height and width of 0. So you either need to explicitly set the size:
DataGrid<OrderLine> grid = new DataGrid<OrderLine>;
grid.setWidth("500px");
grid.setHeight("600px");
dock.add(dgOrder, DockPanel.EAST);
or you can put the gird in a ProvidesResize widget. So in your case I believe you can make it work with a DockLayoutPanel as opposed to a DockPanel which is what you seem to be using.
I had a smilliar problem . Try to put the datagrid in a Panel that implements the ProvidesResize interface, like SimpleLayoutPanel. Also in my case it helped to set the size of the SimpleLayoutPanel.
Turns out my problem was my declaration.
final DataGrid<OrderLine> dgOrder = new DataGrid<OrderLine>();
should be
final CellTable<OrderLine> dgOrder = new CellTable<OrderLine>();
I can't find out why this works, but it does. I can see my table now. are you not supposed to explicitly call an instance of datagrid I wonder?
I have this combo box that I would like to enable or disable depending on a selection of "SDO/OD", (coded as 10 in database) in a previous combo box. When I use the following code it gives me the drop down listing, but for every choice. I want the drop down for only when "SDO/OD" is chosen. Otherwise, disable the combo box but allow the data to pass the null for the record. I don't think it is reading the Listener. My question is why is this happening? How to I handle the Listerner to accommodate such a task?
fcbRole.addSelectionChangedListener(new SelectionChangedListener<ModelData>()
{
#Override
public void selectionChanged(SelectionChangedEvent<ModelData> se)
{
fcbOfficeRegion.clearSelections();
fcbOfficeRegion.getStore().clearFilters();
if(fcbRole.getValue().equals("SDO/OD") && se.getSelectedItem() != null)
{
fcbOfficeRegion.enable();
fcbOfficeRegion.setValueField(se.getSelectedItem().get("strValue").toString());
StoreFilter<ModelData> sfRole = new StoreFilter<ModelData>()
{
#Override
public boolean select(Store<ModelData> store,
ModelData parent, ModelData item,
String property) {
String name = item.get("filterDepts");
name = getScc().cleanString(name.toLowerCase());
if (name.contains("(" + fcbRole.getValue().get("strValue") + ")"))
{
return true;
}
return false;
}
};
fcbOfficeRegion.getStore().addFilter(sfRole);
fcbOfficeRegion.getStore().applyFilters("fcbOfficeRegion");
}
else
Best of Listeners for JComboBox is ItemListener, this Listener fired events SELECTED/DESELECTED, always twice
I need a wizard which second page content depends on the first page's selection. The first page asks the user the "kind" of filter he wants to create and the second one asks the user to create one filter instance of the selected "kind".
JFace's wizards pages contents (createControl(...) method) are all created when the wizard is open and not when a given page is displayed (this allow JFace to know the wizard size I guess ??).
Because of this, I have to create my second page content BEFORE the wizard is opened BUT I can't since the second page's content depends on the first page selection.
For now the cleaner solution I found consists in creating all (seconds) pages before the wizard is open (with their content) and override the getNextPage() method in the first page's implementation.
The main drawback of that solution is that it can be be expensive when there are many second pages to create.
What do you think about that solution ? How do you manage your wizard's pages ? Is there any cleaner solution I missed ?
The approach is right if you are several other pages which are
completely different one with another
depends on the previous choices made in a previous page
Then you can add the next page dynamically (also as described here)
But if you have just a next page with a dynamic content, you should be able to create that content in the onEnterPage() method
public void createControl(Composite parent)
{
//
// create the composite to hold the widgets
//
this.composite = new Composite(parent, SWT.NONE);
//
// create the desired layout for this wizard page
//
GridLayout layout = new GridLayout();
layout.numColumns = 4;
this.composite.setLayout(layout);
// set the composite as the control for this page
setControl(this.composite);
}
void onEnterPage()
{
final MacroModel model = ((MacroWizard) getWizard()).model;
String selectedKey = model.selectedKey;
String[] attrs = (String[]) model.macroMap.get(selectedKey);
for (int i = 0; i < attrs.length; i++)
{
String attr = attrs[i];
Label label = new Label(this.composite, SWT.NONE);
label.setText(attr + ":");
new Text(this.composite, SWT.NONE);
}
pack();
}
As shown in the eclipse corner article Creating JFace Wizards:
We can change the order of the wizard pages by overwriting the getNextPage method of any wizard page.Before leaving the page, we save in the model the values chosen by the user. In our example, depending on the choice of travel the user will next see either the page with flights or the page for travelling by car.
public IWizardPage getNextPage(){
saveDataToModel();
if (planeButton.getSelection()) {
PlanePage page = ((HolidayWizard)getWizard()).planePage;
page.onEnterPage();
return page;
}
// Returns the next page depending on the selected button
if (carButton.getSelection()) {
return ((HolidayWizard)getWizard()).carPage;
}
return null;
}
We define a method to do this initialization for the PlanePage, onEnterPage() and we invoke this method when moving to the PlanePage, that is in the getNextPage() method for the first page.
If you want to start a new wizard based on your selection on the first page, you can use the JFace base class org.eclipse.jface.wizard.WizardSelectionPage.
The example below shows a list of available wizards defined by an extension point.
When you press Next, the selected wizard is started.
public class ModelSetupWizardSelectionPage extends WizardSelectionPage {
private ComboViewer providerViewer;
private IConfigurationElement selectedProvider;
public ModelSetupWizardSelectionPage(String pageName) {
super(pageName);
}
private class WizardNode implements IWizardNode {
private IWizard wizard = null;
private IConfigurationElement configurationElement;
public WizardNode(IConfigurationElement c) {
this.configurationElement = c;
}
#Override
public void dispose() {
}
#Override
public Point getExtent() {
return new Point(-1, -1);
}
#Override
public IWizard getWizard() {
if (wizard == null) {
try {
wizard = (IWizard) configurationElement
.createExecutableExtension("wizardClass");
} catch (CoreException e) {
}
}
return wizard;
}
#Override
public boolean isContentCreated() {
// TODO Auto-generated method stub
return wizard != null;
}
}
#Override
public void createControl(Composite parent) {
setTitle("Select model provider");
Composite main = new Composite(parent, SWT.NONE);
GridLayout gd = new GridLayout(2, false);
main.setLayout(gd);
new Label(main, SWT.NONE).setText("Model provider");
Combo providerList = new Combo(main, SWT.NONE);
providerViewer = new ComboViewer(providerList);
providerViewer.setLabelProvider(new LabelProvider() {
#Override
public String getText(Object element) {
if (element instanceof IConfigurationElement) {
IConfigurationElement c = (IConfigurationElement) element;
String result = c.getAttribute("name");
if (result == null || result.length() == 0) {
result = c.getAttribute("class");
}
return result;
}
return super.getText(element);
}
});
providerViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
#Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty()
&& selection instanceof IStructuredSelection) {
Object o = ((IStructuredSelection) selection)
.getFirstElement();
if (o instanceof IConfigurationElement) {
selectedProvider = (IConfigurationElement) o;
setMessage(selectedProvider.getAttribute("description"));
setSelectedNode(new WizardNode(selectedProvider));
}
}
}
});
providerViewer.setContentProvider(new ArrayContentProvider());
List<IConfigurationElement> providers = new ArrayList<IConfigurationElement>();
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry
.getExtensionPoint(<your extension point namespace>,<extension point name>);
if (extensionPoint != null) {
IExtension extensions[] = extensionPoint.getExtensions();
for (IExtension extension : extensions) {
IConfigurationElement configurationElements[] = extension
.getConfigurationElements();
for (IConfigurationElement c : configurationElements) {
providers.add(c);
}
}
}
providerViewer.setInput(providers);
setControl(main);
}
The corresponding wizard class looks like this:
public class ModelSetupWizard extends Wizard {
private ModelSetupWizardSelectionPage wizardSelectionPage;
public ModelSetupWizard() {
setForcePreviousAndNextButtons(true);
}
#Override
public boolean performFinish() {
// Do what you have to do to finish the wizard
return true;
}
#Override
public void addPages() {
wizardSelectionPage = new ModelSetupWizardSelectionPage("Select a wizard");
addPage(wizardSelectionPage);
}
}
Another alternative is to #Override setVisible. You can update page values or add additional widgets at that time.
I have a different solution.
If page depends on the result of page 1, create a variable and pass it into to first page, when that wizard page has the option from the user, then the last thing before the page is closed is to set the variable to the required value.
Then pass this variable to wizard, then pass it to the next wizard page. Then do a simple if statement and that way you get both choices together.
Remember that in most code there is only a small difference in the user options, so remember not to get bogged down in duplicating your code.