NOTE
Exceptions in previous versions were caused by the fact that plug-in id was ending with a number. This is probably not possible in Eclipse RCP.
UPDATED VERSION
I am trying to display a View by defining perspective extension in plugin.xml.
Here is may plugin.xml:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension
id="application"
point="org.eclipse.core.runtime.applications">
<application>
<run
class="try_03_eclipseplugin.Application">
</run>
</application>
</extension>
<extension
point="org.eclipse.ui.perspectiveExtensions">
<perspectiveExtension
targetID="*">
<view
id="try_03_eclipseplugin.SampleView"
minimized="false"
ratio="0.20"
relationship="left"
relative="org.eclipse.ui.editorss">
</view>
</perspectiveExtension>
</extension>
<extension
point="org.eclipse.ui.views">
<view
allowMultiple="false"
class="try_03_eclipseplugin.SampleView"
icon="icons/sample.gif"
id="try_03_eclipseplugin.SampleView"
name="Sample View">
</view>
</extension>
<extension
point="org.eclipse.ui.handlers">
<handler
class="try_03_eclipseplugin.Handler"
commandId="Try_03_EclipsePlugin.command1">
</handler>
</extension>
<extension
point="org.eclipse.ui.menus">
<menuContribution
allPopups="false"
locationURI="menu:org.eclipse.ui.main.menu">
<command
commandId="Try_03_EclipsePlugin.command1"
label="Try"
style="push">
</command>
</menuContribution>
</extension>
</plugin>
And here is entire code for Application class (all advisors are made as inner classes):
package try_03_eclipseplugin;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* This class controls all aspects of the application's execution
*/
public class Application implements IApplication {
/*
* (non-Javadoc)
*
* #see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
* IApplicationContext)
*/
public Object start(IApplicationContext context) throws Exception {
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
/*
int returnCode = PlatformUI.createAndRunWorkbench(display, new WorkbenchAdvisor() {
#Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new WorkbenchWindowAdvisor(configurer) {
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(400, 300));
configurer.setShowCoolBar(false);
configurer.setShowStatusLine(false);
configurer.setTitle("Hello RCP"); //$NON-NLS-1$
}
};
}
#Override
public String getInitialWindowPerspectiveId() {
return null;
}
});
*/
if (returnCode == PlatformUI.RETURN_RESTART)
return IApplication.EXIT_RESTART;
else
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
/*
* (non-Javadoc)
*
* #see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop() {
if (!PlatformUI.isWorkbenchRunning())
return;
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed())
workbench.close();
}
});
}
}
The code of SampleView is following:
package try_03_eclipseplugin;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
/**
* This sample class demonstrates how to plug-in a new
* workbench view. The view shows data obtained from the
* model. The sample creates a dummy model on the fly,
* but a real implementation would connect to the model
* available either in this or another plug-in (e.g. the workspace).
* The view is connected to the model using a content provider.
* <p>
* The view uses a label provider to define how model
* objects should be presented in the view. Each
* view can present the same model objects using
* different labels and icons, if needed. Alternatively,
* a single label provider can be shared between views
* in order to ensure that objects of the same type are
* presented in the same way everywhere.
* <p>
*/
public class SampleView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "try_03_eclipseplugin.SampleView";
private TableViewer viewer;
private Action action1;
private Action action2;
private Action doubleClickAction;
/*
* The content provider class is responsible for
* providing objects to the view. It can wrap
* existing objects in adapters or simply return
* objects as-is. These objects may be sensitive
* to the current input of the view, or ignore
* it and always show the same content
* (like Task List, for example).
*/
class ViewContentProvider implements IStructuredContentProvider {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
}
public void dispose() {
}
public Object[] getElements(Object parent) {
return new String[] { "One", "Two", "Three" };
}
}
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().
getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
class NameSorter extends ViewerSorter {
}
/**
* The constructor.
*/
public SampleView() {
}
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setSorter(new NameSorter());
viewer.setInput(getViewSite());
// Create the help context id for the viewer's control
PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "Try_EclipsePlugin_03.viewer");
makeActions();
hookContextMenu();
hookDoubleClickAction();
contributeToActionBars();
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
SampleView.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, viewer);
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(action1);
manager.add(new Separator());
manager.add(action2);
}
private void fillContextMenu(IMenuManager manager) {
manager.add(action1);
manager.add(action2);
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(action1);
manager.add(action2);
}
private void makeActions() {
action1 = new Action() {
public void run() {
showMessage("Action 1 executed");
}
};
action1.setText("Action 1");
action1.setToolTipText("Action 1 tooltip");
action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
action2 = new Action() {
public void run() {
showMessage("Action 2 executed");
}
};
action2.setText("Action 2");
action2.setToolTipText("Action 2 tooltip");
action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
doubleClickAction = new Action() {
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection)selection).getFirstElement();
showMessage("Double-click detected on "+obj.toString());
}
};
}
private void hookDoubleClickAction() {
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
doubleClickAction.run();
}
});
}
private void showMessage(String message) {
MessageDialog.openInformation(
viewer.getControl().getShell(),
"Sample View",
message);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
viewer.getControl().setFocus();
}
}
I expect view will appear immediately after program run. But it does not happen.
Simultaneously, I have a code to show new instance of a view with menu command -- and it works and shows view and even icon is shown.
This was because of the absence of perspective id.
When defined perspective factory
package try_03_eclipseplugin;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
public class PerspectiveFactory implements IPerspectiveFactory {
public static final String ID = "Try_03_EclipsePlugin.perspective";
#Override
public void createInitialLayout(IPageLayout layout) {
}
}
and described it in plugin.xml and then returned it's id in advisor:
#Override
public String getInitialWindowPerspectiveId() {
return PerspectiveFactory.ID;
//return "org.eclipse.ui.resourcePerspective";
}
it started to show initial view.
Still don't understand why it does not work with the ID of resource perspective (commented).
Related
Well I'm studying Java FX, but this time I'm using FXML in NetBeans, then I want to restric the Keys allowed by a TextField. Like just numbers or just Letters.
I found This , then I created a new class, then put that code (the checked as correct in the link), i extend TextField, but when I run the code, throws a exception, I think is because SceneBuilder doesn't have my Class.
Update i found a similar code for Java FX :
import java.util.function.UnaryOperator;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author Alejandro
*/
public class JavaFXApplication2 extends Application {
#Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
TextFormatter<String> textFormatter = getTextFormatter();
textField.setTextFormatter(textFormatter);
VBox root = new VBox();
root.getChildren().add(textField);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("TextFormat");
primaryStage.setScene(scene);
primaryStage.show();
}
private TextFormatter<String> getTextFormatter() {
UnaryOperator<Change> filter = getFilter();
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
return textFormatter;
}
private UnaryOperator<Change> getFilter() {
return change -> {
String text = change.getText();
if (!change.isContentChange()) {
return change;
}
if (text.matches("[a-z]*") || text.isEmpty()) {
return change;
}
return null;
};
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
That code above works fine in a Java FX app, but I need one to use in Java FXML, one guy below Post a similar code, it compiles, no trows exception, but doesn't work, or i don't know how to implement it.
If you want to limit your text to just ALPHA/NUMERIC you can use a textformatter like this:
public class MaxLengthTextFormatter extends TextFormatter<String> {
private int maxLength;
public MaxLengthTextFormatter(int maxLength) {
super(new UnaryOperator<TextFormatter.Change>() {
#Override
public TextFormatter.Change apply(TextFormatter.Change change) {
//If the user is deleting the text (i.e. full selection, ignore max to allow the
//change to happen)
if(change.isDeleted()) {
//if the user is pasting in, then the change could be longer
//ensure it stops at max length of the field
if(change.getControlNewText().length() > maxLength){
change.setText(change.getText().substring(0, maxLength));
}
}else if (change.getControlText().length() + change.getText().length() >= maxLength) {
int maxPos = maxLength - change.getControlText().length();
change.setText(change.getText().substring(0, maxPos));
}
return change;
}
});
this.maxLength = maxLength;
}
public int getMaxLength()
{
return maxLength;
}
}
public class AlphaNumericTextFormatter extends TextFormatter<String> {
/** The Constant ALPHA_NUMERIC_ONLY. */
//private static final String ALPHA_NUMERIC_ONLY = "^[a-zA-Z0-9]*$";
/** MAKE NUMERIC ONLY **/
private static final String DIGITS_ONLY = "^[0-9]*$";
/**
* Instantiates a new alpha numeric text formatter.
*/
public AlphaNumericTextFormatter() {
super(applyFilter(null));
}
/**
* Instantiates a new alpha numeric text formatter.
*
* #param maxLength
* the max length
*/
public AlphaNumericTextFormatter(int maxLength) {
super(applyFilter(new MaxLengthTextFormatter(maxLength).getFilter()));
}
/**
* Apply filter.
*
* #param filter
* the filter
* #return the unary operator
*/
private static UnaryOperator<Change> applyFilter(UnaryOperator<Change> filter) {
return change -> {
if (change.getControlNewText() != null && change.getControlNewText().matches(DIGITS_ONLY)) {
if (filter != null) {
filter.apply(change);
}
return change;
}
return null;
};
}
}
That creates a formatter than only allows numbers and letters - you can adjust the pattern to your needs.
You attach it to your textfield like this....
#FXML
private TextField myTextField;
#FXML
private void initialize() {
//Create a alpha field which max length of 4
myTextField.setTextFormatter(new AlphaNumericTextFormatter(4));
}
I need some help concerning writing widget for Lotus Notes on Java. My problem is : I created a plugin according to this tutorial : Developing a simple plug-in for Lotus Notes
But there is no information how to write any code. Also I failed to find anything using Google. To be more specific:
When I click some email in Notes Client I need to fetch this email address and show it on my widget.
When I click some link I need to open this link in a browser.
Could anyone help me and provide some example? Thanks a lot in advance! Here is my code:
package com.domiclipse.tutorial1.views;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
/**
* This sample class demonstrates how to plug-in a new
* workbench view. The view shows data obtained from the
* model. The sample creates a dummy model on the fly,
* but a real implementation would connect to the model
* available either in this or another plug-in (e.g. the workspace).
* The view is connected to the model using a content provider.
* <p>
* The view uses a label provider to define how model
* objects should be presented in the view. Each
* view can present the same model objects using
* different labels and icons, if needed. Alternatively,
* a single label provider can be shared between views
* in order to ensure that objects of the same type are
* presented in the same way everywhere.
* <p>
*/
public class SampleView extends ViewPart {
private Action action1;
private Action action2;
private Action doubleClickAction;
/*
* The content provider class is responsible for
* providing objects to the view. It can wrap
* existing objects in adapters or simply return
* objects as-is. These objects may be sensitive
* to the current input of the view, or ignore
* it and always show the same content
* (like Task List, for example).
*/
class ViewContentProvider implements IStructuredContentProvider {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
}
public void dispose() {
}
public Object[] getElements(Object parent) {
return new String[] { "One", "Two", "Three" };
}
}
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().
getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
class NameSorter extends ViewerSorter {
}
/**
* The constructor.
*/
public SampleView() {
}
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
#Override
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setSorter(new NameSorter());
viewer.setInput(getViewSite());
makeActions();
hookContextMenu();
hookDoubleClickAction();
contributeToActionBars();
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
SampleView.this.fillContextMenu(manager);
}
});
// Menu menu = menuMgr.createContextMenu(viewer.getControl());
//viewer.getControl().setMenu(menu);
//getSite().registerContextMenu(menuMgr, viewer);
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(action1);
manager.add(new Separator());
manager.add(action2);
}
private void fillContextMenu(IMenuManager manager) {
manager.add(action1);
manager.add(action2);
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(action1);
manager.add(action2);
}
private void makeActions() {
action1 = new Action() {
public void run() {
showMessage("Action 1 executed");
}
};
action1.setText("Action 1");
action1.setToolTipText("Action 1 tooltip");
action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
action2 = new Action() {
public void run() {
showMessage("Action rehrhrhertrSd");
}
};
action2.setText("Action 2");
action2.setToolTipText("Action 2 tooltip");
action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
doubleClickAction = new Action() {
public void run() {
//ISelection selection = viewer.getSelection();
//Object obj = ((IStructuredSelection)selection).getFirstElement();
//showMessage("Double-click detected on "+obj.toString());
}
};
}
private void hookDoubleClickAction() {
//viewer.addDoubleClickListener(new IDoubleClickListener() {
// public void doubleClick(DoubleClickEvent event) {
// doubleClickAction.run();
// }
//});
}
private void showMessage(String message) {
//MessageDialog.openInformation(
// viewer.getControl().getShell(),
// "Sample View",
// message);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
// viewer.getControl().setFocus();
}
}
I am creating a custom toolbar for my RCP application.
As shown in figure I want to have a drop down box with three other text boxes. These are basically the input box and are interdependent. Right now each of these boxes are in separate classes. I want to bring them together in one class so it is easier to create listeners for each other.
protected void fillCoolBar(ICoolBarManager coolBar) {
IToolBarManager toolbar = new ToolBarManager(coolBar.getStyle());
coolBar.add(toolbar);
Toolbar extraToolBar = new Toolbar("Toolbar");
toolbar.add(extraToolBar);
toolbar.add(new Separator());
toolbar.add(new MyCombo("Demo Combo box"));
toolbar.add(new Separator());
toolbar.add(new IPaddress("Ip"));
toolbar.add(new Separator());
toolbar.add(new Mask("Mask"));
toolbar.add(new Separator());
toolbar.add(new Count("Count"));
}
public class IPaddress extends ControlContribution {
Text textBox;
public IPaddress(String id) {
super(id);
// TODO Auto-generated constructor stub
}
#Override
protected Control createControl(Composite parent) {
textBox = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP);
textBox.setLayoutData(new GridData(GridData.FILL_BOTH));
textBox.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent event) {
Text text = (Text) event.widget;
System.out.println(text.getText());
}
});
return textBox;
}
}
Thus I want to create a new custom Toolbar will all the functionalities that I want and then stick it to the original. But somehow it only shows an empty bar on the left.
protected Control createControl(Composite parent) {
toolBar = new ToolBar(parent, SWT.FLAT |SWT.BORDER);
Device dev = toolBar.getDisplay();
try {
newi = new Image(dev, "C:\\Users\\RahmanAs\\ChipcoachWorkspace\\ChipCoach\\icons\\FileClose.png");
opei = new Image(dev, "C:\\Users\\RahmanAs\\ChipcoachWorkspace\\ChipCoach\\icons\\FileOpen.png");
} catch (Exception e) {
System.out.println("Cannot load images");
System.out.println(e.getMessage());
System.exit(1);
}
ToolItem item0 = new ToolItem (toolBar, SWT.PUSH);
item0.setImage(newi);
item0.setText("Hello");
ToolItem item1 = new ToolItem(toolBar, SWT.PUSH);
item1.setText("Push");
ToolItem item2 = new ToolItem(toolBar, SWT.PUSH);
item2.setText("Pull");
return toolBar;
}
I also have run buttons, which I created in the plugin using Vogella's tutorial. But I cannot program their placements in this way. (For example if I want them in the beginning.) Is there a way to create them programmatically?
I think the reason your leftmost ToolBar is empty is a layout issue. In my code below, I had a similar "empty" ToolBar problem when I did not have any buttons located outside the custom ToolBar but still in the main ToolBar. Adding in the "foo" and "bar" buttons fixed the layout issue, but I could not figure out the right calls to layout() or pack() to fix it. I think this may be related to the bug here.
I took a swing at creating a similar ToolBar and built around the "RCP Mail Template" plugin-project that you can create from the "New Plug-in Project" wizard.
To address your first two concerns, I created 3 packages in the example RCP bundle (I called my project "com.bar.foo"):
com.bar.foo.actions - Contains classes that extend ContributionControl and wrap Combo and Text widgets. These have nothing to do with the data model and just worry about creating widgets.
com.bar.foo.model - Contains the data model. I just made up a simple model here with an IP, mask, gateway, and one or two helpful methods.
com.bar.foo.toolBar - These classes are plugged up to the main UI ToolBar via the org.eclipse.ui.menus extension point. They link the data model to the ContributionControls in the first package. The most important class here is ToolBarContribution, which effectively centralizes all of your listeners. This makes it easier for you to link the listeners for the widgets to the same model.
Here's the source for the ToolBarContribution (note that it addresses your first two concerns because it hooks up the listeners to the model and provides its own ToolBar to the UI):
package com.bar.foo.toolBar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
import com.bar.foo.actions.ComboContributionItem;
import com.bar.foo.actions.TextContributionItem;
import com.bar.foo.model.NetworkConfig;
public class ToolBarContribution extends WorkbenchWindowControlContribution {
// Our data model.
private NetworkConfig configuration = new NetworkConfig();
// Each of these corresponds to a widget in the ToolBar.
private Action scanAction;
private ComboContributionItem sourceCombo;
private TextContributionItem ipText;
private TextContributionItem maskText;
private TextContributionItem gatewayText;
#Override
protected Control createControl(Composite parent) {
setupContributionItems();
// Let's not get our hands messy with SWT... add IActions or
// IContributionItems to a ToolBarManager and let the ToolBarManager
// create the SWT ToolBar.
ToolBarManager manager = new ToolBarManager();
manager.add(scanAction);
manager.add(sourceCombo);
manager.add(ipText);
manager.add(maskText);
manager.add(gatewayText);
ToolBar toolBar = manager.createControl(parent);
// Highlight the ToolBar in red.
toolBar.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_RED));
return toolBar;
}
private void setupContributionItems() {
scanAction = new Action("Scan Host") {
#Override
public void run() {
System.out.println("Scanning...");
String host = sourceCombo.getComboControl().getText();
configuration.scanHost(host);
System.out.println("Scanned!");
refreshTexts();
}
};
scanAction.setToolTipText("Scans the host for a configuration.");
final SelectionListener comboListener = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
ipText.getTextControl().setText("");
maskText.getTextControl().setText("");
gatewayText.getTextControl().setText("");
}
};
sourceCombo = new ComboContributionItem("sourceCombo") {
#Override
public Control createControl(Composite parent) {
// Let ComboContributionItem create the initial control.
Control control = super.createControl(parent);
// Now customize the Combo widget.
Combo combo = getComboControl();
combo.setItems(configuration.getAvailableHosts());
combo.addSelectionListener(comboListener);
// Return the default control.
return control;
}
};
ipText = new TextContributionItem("ipText", SWT.BORDER | SWT.SINGLE
| SWT.READ_ONLY);
maskText = new TextContributionItem("maskText");
gatewayText = new TextContributionItem("gatewayText");
}
private void refreshTexts() {
ipText.getTextControl().setText(configuration.getIP());
maskText.getTextControl().setText(configuration.getMask());
gatewayText.getTextControl().setText(configuration.getGateway());
}
}
In addition to this ToolBar, I have two separate buttons in the main UI ToolBar, one before, and one after the custom ToolBar. Their sources are in the package com.bar.foo.toolBar. Here is the first command:
package com.bar.foo.toolBar;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
public class FooHandler extends AbstractHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("foo");
return null;
}
}
And here is the second one:
package com.bar.foo.toolBar;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
public class BarHandler extends AbstractHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("bar");
return null;
}
}
Since I didn't know too much about your data, I had to create my own model. The model in the package com.bar.foo.model is just one class:
package com.bar.foo.model;
public class NetworkConfig {
private String ip = "";
private String mask = "";
private String gateway = "";
public String[] getAvailableHosts() {
return new String[] { "fooHost" };
}
public void scanHost(String host) {
if ("fooHost".equals(host)) {
ip = "192.168.1.2";
mask = "255.255.255.0";
gateway = "192.168.1.1";
} else {
ip = "";
mask = "";
gateway = "";
}
}
public String getIP() {
return ip;
}
public String getMask() {
return mask;
}
public String getGateway() {
return gateway;
}
}
Now for the com.bar.foo.actions package that contains the ControlContributions that go in the custom ToolBar. Note that neither of these two classes have anything to do with the model, and they can be re-used elsewhere in your product.
The first class just wraps a Combo widget. The widget can be initially customized by overriding the controlCreated(Combo) method. I use that in the ToolBarContribution class to add a SelectionListener and set the Combo's items. Here's the class:
package com.bar.foo.actions;
import org.eclipse.jface.action.ControlContribution;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
public class ComboContributionItem extends ControlContribution {
private Combo combo;
public ComboContributionItem(String id) {
super(id);
}
#Override
protected Control createControl(Composite parent) {
combo = new Combo(parent, SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
return combo;
}
#Override
public int computeWidth(Control control) {
// The widget is now 100 pixels. You can new GC gc = new GC(control) and
// use the gc.stringExtent(String) method to help compute a more dynamic
// width.
return 100;
}
public Combo getComboControl() {
return combo;
}
}
The other class in this package wraps a Text widget:
package com.bar.foo.actions;
import org.eclipse.jface.action.ControlContribution;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
public class TextContributionItem extends ControlContribution {
private final int style;
private Text text;
public TextContributionItem(String id) {
this(id, SWT.BORDER | SWT.SINGLE);
}
public TextContributionItem(String id, int style) {
super(id);
this.style = style;
}
#Override
protected Control createControl(Composite parent) {
text = new Text(parent, style);
return text;
}
#Override
public int computeWidth(Control control) {
return 100;
}
public Text getTextControl() {
return text;
}
}
I didn't do this, but if you need to further customize the Text widget for your ToolBar, you can override the createControl(Composite) method just like I did when initializing the ComboContributionItem.
Now one last thing: I used extensions to customize the ToolBar. However, the same logic used by ToolBarContribution applies to your fillCoolBar(ICoolBarManager) method or your createControl(Composite) method, depending on which ToolBar you ultimately wish to modify.
In my case, here's what I added to the end of the plugin's plugin.xml:
<extension
point="org.eclipse.ui.menus">
<menuContribution
locationURI="toolbar:org.eclipse.ui.main.toolbar">
<toolbar
id="com.bar.foo.toolbar">
<command
commandId="com.bar.foo.commands.foo"
label="Foo"
style="push">
</command>
<control
class="com.bar.foo.toolBar.ToolBarContribution">
</control>
<command
commandId="com.bar.foo.commands.bar"
label="Bar"
style="push">
</command>
</toolbar>
</menuContribution>
</extension>
<extension
point="org.eclipse.ui.commands">
<command
id="com.bar.foo.commands.foo"
name="Foo">
</command>
<command
id="com.bar.foo.commands.bar"
name="Bar">
</command>
</extension>
<extension
point="org.eclipse.ui.handlers">
<handler
class="com.bar.foo.toolBar.FooHandler"
commandId="com.bar.foo.commands.foo">
</handler>
<handler
class="com.bar.foo.toolBar.BarHandler"
commandId="com.bar.foo.commands.bar">
</handler>
</extension>
The commands are hooked up so that there's a button for FooHandler before the custom ToolBar and a button for BarHandler after the custom ToolBar. The order in which these commands are specified in the xml will be reflected in the application. Likewise, the order in which the items are added to the custom ToolBar will reflect in your product.
Another note on placement: You can make the menuContributions appear in different places by setting a placement in the locationURI's query, e.g., toolbar:org.eclipse.ui.main.toolbar?after=additions. "before" is another placement keyword like "after". More examples of this can be found in this Eclipse help doc.
I am trying to push a new screen when a bitmap is "clicked" on the screen. For this I have created a Class from this post: Blackberry Clickable BitmapField whose partial code I've posted below:
public class CustomMenuButtonField extends Field{
Bitmap normal,focused;
...
protected boolean navigationClick(int status, int time)
{
// push new screen
fieldChangeNotify(0);
return true;
}
...
I want to push a new screen when the user clicks the bitmap. I have consulted this thread:
Communicating between classes, but I still can't figure out the commands to call the new screen command. The UserInterface I have so far is:
public class UserInterface extends UiApplication {
public static void main(String[] args){
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
}
public UserInterface() {
pushScreen(new UserInterfaceScreen());
}
}
final class UserInterfaceScreen extends MainScreen {
public UserInterfaceScreen() {
...
What would be the command to pop up the new screen, and more importantly where would I be able to work on it? I know it should probably use pushScreen() but that is not recognized in that class. Would I create a new final class NewScreenFromClick extends MainScreen? and if so how would I call it and put it in the eventDispatcher. I've been going through the blackberry site but they don't have much sample code on this issue and I am very new to Java so this is fairly confusing to me.
imageField imageField = new imageField ("",Field.FOCUSABLE,"image.png","image.png", 0x102839);
add(imageField );
FieldChangeListener listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (field == imageField ) {
home home = new home();//your screen
UiApplication.getUiApplication().pushScreen(home);
}
}
};
imageField .setChangeListener(listener);
//imagefield class is given below
package com.pl.button;
import net.rim.device.api.ui.*;
import net.rim.device.api.system.*;
public class imagefield extends Field {
private String _label;
private int _labelHeight;
private int _labelWidth;
private Font _font;
private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
int color;
public imagefield (String text, long style ,String img, String img_hvr, int color){
super(style);
_offPicture = Bitmap.getBitmapResource(img);
_onPicture = Bitmap.getBitmapResource(img_hvr);
_font = getFont();
_label = text;
_labelHeight = _onPicture.getHeight();
_labelWidth = _onPicture.getWidth();
this.color = color;
_currentPicture = _offPicture;
}
/**
* #return The text on the button
*/
String getText(){
return _label;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredHeight()
*/
public int getPreferredHeight(){
return _labelHeight;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredWidth()
*/
public int getPreferredWidth(){
return _labelWidth;
}
/**
* Field implementation. Changes the picture when focus is gained.
* #see net.rim.device.api.ui.Field#onFocus(int)
*/
protected void onFocus(int direction) {
_currentPicture = _onPicture;
invalidate();
}
/**
* Field implementation. Changes picture back when focus is lost.
* #see net.rim.device.api.ui.Field#onUnfocus()
*/
protected void onUnfocus() {
_currentPicture = _offPicture;
invalidate();
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#drawFocus(Graphics, boolean)
*/
protected void drawFocus(Graphics graphics, boolean on) {
// Do nothing
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(Math.min( width, getPreferredWidth()),
Math.min( height, getPreferredHeight()));
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#paint(Graphics)
*/
protected void paint(Graphics graphics){
// First draw the background colour and picture
graphics.setColor(this.color);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
// Then draw the text
graphics.setColor(Color.BLACK);
graphics.setFont(_font);
graphics.drawText(_label, 4, 2,
(int)( getStyle() & DrawStyle.ELLIPSIS | DrawStyle.HALIGN_MASK ),
getWidth() - 6 );
}
/**
* Overridden so that the Event Dispatch thread can catch this event
* instead of having it be caught here..
* #see net.rim.device.api.ui.Field#navigationClick(int, int)
*/
protected boolean navigationClick(int status, int time){
fieldChangeNotify(1);
return true;
}
}
You can use:
UiApplication.getUiApplication().pushScreen(new HomeScreen());
If your application is not doing anything strange UiApplication.getUiApplication() will always return the UiApplication object for your program. This is a singleton object created for each UiApplication context.
You could also use:
UserInterface.getUiApplication().pushScreen(new HomeScreen());
If the UserInterface class is visible to the class you are working on, but this would make your code less re-usable.
I've collected some basic samples on my blog. Have a look at this page. Start at the bottom and work your way up.
Try the following code I have added UserInterfaceScreen. When UserInterfaceScreen is constructed, it adds a CustomMenuButtonField and sets a field change listener. When the button is clicked it pushes the new screen to the stack
package mypackage;
import net.rim.device.api.ui.UiApplication;
public class UserInterface extends UiApplication {
public static void main(String[] args){
UserInterface theApp = new UserInterface();
theApp.enterEventDispatcher();
}
public UserInterface() {
pushScreen(new UserInterfaceScreen());
}
}
This is the UserInterfaceScreen
package mypackage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
public class UserInterfaceScreen extends MainScreen {
public UserInterfaceScreen() {
super();
//replace null with the image string
CustomMenuButtonField button = new CustomMenuButtonField(null, null);
button.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
UiApplication.getUiApplication().pushScreen(new MyHomeScreen());
}
});
}
}
Look the answer in the below link which I posted by me(alishaik786) :
Clickable Bitmap;
I use JFace TableViewer and databinding to display data of a database table, some columns have very long text, I found the text is cut out. if I activate the text editor associated with that cell, I can see the full text.
Does swt table has limitation on text length in a cell ? or the OS has such limitation ?(I am using eclipse 3.6 and windows 7 32 bit)
/*******************************************************************************
* Copyright (c) 2006 Tom Schindl and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tom Schindl - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.snippets.viewers;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* A simple TableViewer to demonstrate usage
*
* #author Tom Schindl <tom.schindl#bestsolution.at>
*
*/
public class Snippet001TableViewer {
private class MyContentProvider implements IStructuredContentProvider {
/* (non-Javadoc)
* #see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return (MyModel[])inputElement;
}
/* (non-Javadoc)
* #see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/* (non-Javadoc)
* #see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public class MyModel {
public int counter;
public MyModel(int counter) {
this.counter = counter;
}
public String toString() {
**return "very loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog text" + this.counter;**
}
}
public Snippet001TableViewer(Shell shell) {
final TableViewer v = new TableViewer(shell);
v.setLabelProvider(new LabelProvider());
v.setContentProvider(new MyContentProvider());
MyModel[] model = createModel();
v.setInput(model);
v.getTable().setLinesVisible(true);
}
private MyModel[] createModel() {
MyModel[] elements = new MyModel[10];
for( int i = 0; i < 10; i++ ) {
elements[i] = new MyModel(i);
}
return elements;
}
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display ();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new Snippet001TableViewer(shell);
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
It's windows bug/feature (see bugzilla for details), here is the proof (linux screenshot of your code)
I may be possible to workaround this bug/feature by self cell rendering (see Custom Drawing Table and Tree Items tutorial).
I found a simple way to get the whole text shown.
You have to use a StyledCellLabelProvider and override the update-method.
Here is a little example which shows the differences between a StyledCellLabelProvider and a ColumnLabelProvider. To override the update-method of ColumnLabelProvider is unnecessary. I did it to show that it depends on the class.
package tabletest;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableColumn;
public class MyClass {
private static final String LINE = "123456789A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J"// 100
+ "123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789T" // 200
+ "123456789U123456789V123456789W123456789X123456789Y123456789Z" // 260
+ " a lot mor text";
public MyClass(Shell shell){
createControl(shell);
}
private void createControl(Composite parent){
parent.setLayout(new GridLayout(1, true));
TableViewer viewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL |SWT.H_SCROLL);
viewer.getTable().setHeaderVisible(true);
viewer.getTable().setLinesVisible(true);
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new LabelProvider());
createColumn(viewer);
viewer.setInput(new String[] { LINE });
for(TableColumn col : viewer.getTable().getColumns()){
col.pack();
}
GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getControl());
}
private void createColumn(TableViewer viewer) {
TableViewerColumn column1 = new TableViewerColumn(viewer, SWT.NONE);
column1.getColumn().setText("ColumnLabelProvider");
column1.setLabelProvider(new ColumnLabelProvider(){
#Override
public void update(ViewerCell cell) {
cell.setText(cell.getElement().toString());
super.update(cell);
}
});
TableViewerColumn column2 = new TableViewerColumn(viewer, SWT.NONE);
column2.getColumn().setText("StyledCellLabelProvider");
column2.setLabelProvider(new StyledCellLabelProvider() {
#Override
public void update(ViewerCell cell) {
cell.setText(cell.getElement().toString());
super.update(cell);
}
});
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
new MyClass(shell);
shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep();
}
}
}
}
It also works in the Snippet001TableViewer when you change the LabelProvider to a StyledCellLabelProvider and override the update-method similar to my example.