How to add an GUI component like a Button in a Editor? - eclipse

I'm a beginner in RCP just started building RCP application today.I want to a GUI component like a Button ,comboBox,Checkbox in a Editor .I've managed to add a editor in Extensions and create a class for it.I have written the code to create a label in creatPartControl but it does not work..I get a black window.Should I add the editor in perspective like this
layout.addStandaloneView(Editor.id, true, IPageLayout.TOP,0.7f,
layout.getEditorArea());
layout.addStandaloneView(View.ID, true, IPageLayout.BOTTOM,0.4f,
layout.getEditorArea());
Please help me resolve this issue.If possible please give an eg on how to add a editor and create a label and a button in it.
Thank you for your help in advance
code in my Editor.java content in createPartControl()
parent.setLayout(new GridLayout());
Button b=new Button(parent,SWT.TOGGLE);
b.setText("Hello ");
Label label1 = new Label(parent, SWT.NONE);
label1.setText("First Name");
package com.hello;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
public class Editor extends EditorPart {
public static final String ID = "TestApplication.editor3";
public Editor() {
// TODO Auto-generated constructor stub
}
#Override
public void doSave(IProgressMonitor monitor) {
// TODO Auto-generated method stub
}
#Override
public void doSaveAs() {
// TODO Auto-generated method stub
}
#Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
// TODO Auto-generated method stub
}
#Override
public boolean isDirty() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isSaveAsAllowed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void createPartControl(Composite parent) {
Label label = new Label(parent, SWT.NONE);
label.setText("sssssss");
}
#Override
public void setFocus() {
// TODO Auto-generated method stub
}
}

You are not correctly initializing the editor and it causes problems when opening the editor. Fill up your init() method like below and see if this helps:
#Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
setSite(site);
setInput(input);
}

It's been a few years since I worked on an Eclipse editor. Here's a screen capture of the editor so you can see I did more than add a Button.
I extended the Viewer class to create the GUI of the editor.
I extended the EditorPart class to create the functionality of the editor.
Because of the kind of editor I was building, I had to create my own version of Canvas and my own version of IDocument.

Related

How to capture mouse click events from console in eclipse plugin

I'm developing an eclipse plugin. It writes some lines in a console. In order to select a line displayed in the console, I’m trying to capture mouse double click event from that console.
The console has been implemented by following this eclipse FAQ. MessageConsole or IconsoleView classes doesn‘t seem to provide a methode to add a listener with an SWT.MouseDoubleClick event.
Is there any way to capture a mouse event from a console and then read the selected line ?
The MessageConsole doesn't know anything about how the data is displayed, it is the TextConsoleViewer that deals with that.
To access the console viewer you need to use a custom message console - extending MessageConsole or TextConsole and overriding createPage to create your own console page extending TextConsolePage.
The console page needs to override the createViewer method to create your own text console viewer extending TextConsoleViewer.
In the viewer you can override the mouseDoubleClick method to receive the double clicks.
For an example see the Eclipse JDT JavaStackTraceConsole, JavaStackTraceConsolePage, and JavaStackTraceConsoleViewer classes.
public class JavaStackTraceConsole extends TextConsole {
...
#Override
public IPageBookViewPage createPage(IConsoleView view) {
return new JavaStackTraceConsolePage(this, view);
}
}
public class JavaStackTraceConsolePage extends TextConsolePage {
...
#Override
protected TextConsoleViewer createViewer(Composite parent) {
return new JavaStackTraceConsoleViewer(parent, (JavaStackTraceConsole) getConsole());
}
}
public class JavaStackTraceConsoleViewer extends TextConsoleViewer {
...
}
Thank you, it works fine. I just had to managed the mouse event in another way because overriding the mouseDoubleClick method didn’t work. Here is my code :
public class MyTextConsoleViewer extends TextConsoleViewer {
public MyTextConsoleViewer(Composite parent, MyMessageConsole console) {
super(parent, console);
StyledText styledText = getTextWidget();
MouseListener listener = new MouseListener() {
#Override
public void mouseUp(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDown(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDoubleClick(MouseEvent event) {
// TODO Auto-generated method stub
IDocument document = console.getDocument();
try {
int currentLine = document.getLineOfOffset(styledText.getOffsetAtLocation(new Point (event.x, event.y)));
IRegion lineInfo = document.getLineInformation(currentLine);
System.out.println(document.get(lineInfo.getOffset(), lineInfo.getLength()));
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
styledText.addMouseListener(listener );
// TODO Auto-generated constructor stub
}
public MyTextConsoleViewer(Composite parent, TextConsole console,
IScrollLockStateProvider scrollLockStateProvider) {
super(parent, console, scrollLockStateProvider);
// TODO Auto-generated constructor stub
}
#Override
public void mouseDoubleClick(MouseEvent e) {
System.out.println("This even doesn't work!");
}
}

Focuslost event on Jcombobox in netbeans

I am trying to have a bind a focuslost event on my combobox but it's not happening.
Here is my code-:
jComboBox1.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e){
}
public void focusLost(FocusEvent e){
JOptionPane.showConfirmDialog(null,"focuslost");
}
});
I also tried this-:
JComboBox default editor has an internal class BasicComboBoxEditor$BorderlessTextField that is the component that gets and loses focus.
It can be accessed simply by-:
Component component = comboBox.getEditor().getEditorComponent();
if (component instanceof JTextField)
JTextField borderlesstextfield = (JTextField) borderless;
But i am getting error on this line-
JTextField borderlesstextfield = (JTextField) borderless;
I am new to netbeans. Kindly guide me.Thank you in advance.
I tested this(Adding the JComboBox inside a JPanel ). If there are more elements inside the panel the focuslost is triggered when pressing tab or clicking on another element.
Considering that you do not have any other elements or you want the focus lost event to trigger also when you click somewhere on the window:
Keep your focus listener as is and add the following after the auto-generated initComponents():
jPanel1.setFocusable(true);
jPanel1.setRequestFocusEnabled(true);
jPanel1.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
jPanel1.requestFocusInWindow();
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});

Getting user data in NewProjectCreationPage in Eclipse Plugin

I have been successful in making a plugin. However now i need that on project creation page i add some more textboxes to get the user information. Also i need to use this information to add into the auto generated .php files made in project directory.
I want to know how can i override the WizardNewProjectCreationPage to add some more textboxes to the already given layout. I am pretty new to plugin development. Here is the code for my custom wizard.
import java.net.URI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
import rudraxplugin.pages.MyPageOne;
import rudraxplugin.projects.RudraxSupport;
public class CustomProjectNewWizard extends Wizard implements INewWizard, IExecutableExtension {
private WizardNewProjectCreationPage _pageOne;
protected MyPageOne one;
private IConfigurationElement _configurationElement;
public CustomProjectNewWizard() {
// TODO Auto-generated constructor stub
setWindowTitle("RudraX");
}
#Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// TODO Auto-generated method stub
}
#Override
public void addPages() {
super.addPages();
_pageOne = new WizardNewProjectCreationPage("From Scratch Project Wizard");
_pageOne.setTitle("From Scratch Project");
_pageOne.setDescription("Create something from scratch.");
addPage(one);
addPage(_pageOne);
}
#Override
public boolean performFinish() {
String name = _pageOne.getProjectName();
URI location = null;
if (!_pageOne.useDefaults()) {
location = _pageOne.getLocationURI();
System.err.println("location: " + location.toString()); //$NON-NLS-1$
} // else location == null
RudraxSupport.createProject(name, location);
// Add this
BasicNewProjectResourceWizard.updatePerspective(_configurationElement);
return true;
}
#Override
public void setInitializationData(IConfigurationElement config,
String propertyName, Object data) throws CoreException {
_configurationElement = config;
// TODO Auto-generated method stub
}
}
Ask for any other code required. Any help is appreciated. Thank You.
Instead of using WizardNewProjectCreationPage directly create a new class extending WizardNewProjectCreationPage and override the createControl method to create new controls:
class MyNewProjectCreationPage extends WizardNewProjectCreationPage
{
#Override
public void createControl(Composite parent)
{
super.createControl(parent);
Composite body = (Composite)getControl();
... create new controls here
}
}

My Custom CursorAdapter doesn't update my ListView

I'm having troubles with my Custom CursorAdapter and my ListView, the fact is, I can save data in my sqlite Database in my custom ContentProvider but my ListView is not populated.
I know DB Operations are heavy long operations, therefore I do it in another thread and furthermore CursorLoader is a subclass of AsyncTaskLoader, so it should be prepared for that.
With SimpleCursorAdapter works fine but with this Custom CursorAdapter not.
Can anyone tell me what is wrong and how could I solve it?
Thanks in advance.
My code is the following
public class TextNoteAdapter extends CursorAdapter {
/*********** Declare Used Variables *********/
private Cursor mCursor;
private Context mContext;
private static LayoutInflater mInflater=null;
/************* TextNoteAdapter Constructor *****************/
public TextNoteAdapter (Context context, Cursor cursor, int flags) {
super(context, cursor,flags);
mInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
mCursor = cursor;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = mInflater.inflate(R.layout.textnote_info, parent, false);
ViewHolder holder = new ViewHolder();
holder.note_name = (TextView)view.findViewById(R.id.note_name);
holder.creation_date = (TextView)view.findViewById(R.id.creation_date);
holder.modification_date = (TextView)view.findViewById(R.id.modification_date);
holder.label_creation_date = (TextView)view.findViewById(R.id.label_creation_date);
holder.label_modification_date = (TextView)view.findViewById(R.id.label_modification_date);
view.setTag(holder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data what means, take the data from the cursor and put it in views
View vi = view;
ViewHolder holder = (ViewHolder)view.getTag();
if(view==null){
/****** Inflate textnote_info.xml file for each row ( Defined below ) *******/
vi = mInflater.inflate(R.layout.textnote_info, null);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
} else
holder=(ViewHolder)vi.getTag();
/************ Set Model values in Holder elements ***********/
holder.note_name.setText(cursor.getString(cursor.getColumnIndex(TextNotesDb.KEY_NOTE_NAME)));
holder.creation_date.setText(cursor.getString(cursor.getColumnIndex(TextNotesDb.KEY_CREATION_DATE)));
holder.modification_date.setText(cursor.getString(cursor.getColumnIndex(TextNotesDb.KEY_MODIFICATION_DATE)));
holder.label_creation_date.setText(Constants.LABEL_CREATION_DATE);
holder.label_modification_date.setText(Constants.LABEL_MODIFICATION_DATE);
}
#Override
protected void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
notifyDataSetChanged();
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView note_name;
public TextView creation_date;
public TextView modification_date;
public TextView label_creation_date;
public TextView label_modification_date;
}
}
And here my MainActivity
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>{
private Cursor cursor;
private Button addButton;
private ListView listView;
private TextNoteAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayListView();
addButton = (Button)findViewById(R.id.add_textnote);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starts a new Intent to add a Note
Intent intent = new Intent(getBaseContext(), TextNoteEdit.class);
Bundle bundle = new Bundle();
bundle.putString("mode", "add");
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
Log.i("TAG", "MainActivity:: onResume");
/** Starts a new or restarts an existing Loader in this manager **/
getLoaderManager().restartLoader(0, null, this);
}
private void displayListView() {
// That ensures a loader is initialized and active.
// If the loader specified by the ID already exists, the last created loader is reused.
// else initLoader() triggers the LoaderManager.LoaderCallbacks method onCreateLoader().
// This is where you implement the code to instantiate and return a new loader
getLoaderManager().initLoader(0, null, this);
// We get ListView from Layout and initialize
listView = (ListView) findViewById(R.id.textnote_list);
// DB takes long, therefore this operation should take place in a new thread!
new Handler().post(new Runnable() {
#Override
public void run() {
dataAdapter = new TextNoteAdapter(MainActivity.this, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(dataAdapter);
Log.i("TAG", "MainActivity:: Handler... Run()");
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
/** Get the cursor, positioned to the corresponding row in the result set **/
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// display the selected note
String noteName = cursor.getString(cursor.getColumnIndexOrThrow(TextNotesDb.KEY_NOTE_NAME));
Toast.makeText(getApplicationContext(), noteName, Toast.LENGTH_SHORT).show();
String rowId = cursor.getString(cursor.getColumnIndexOrThrow(TextNotesDb.KEY_ROWID));
// starts a new Intent to update/delete a Textnote
// pass in row Id to create the Content URI for a single row
Intent intent = new Intent(getBaseContext(), TextNoteEdit.class);
Bundle bundle = new Bundle();
bundle.putString("mode", "update");
bundle.putString("rowId", rowId);
intent.putExtras(bundle);
startActivityForResult(intent, 1);
}
});
}
/** This is called when a new Loader needs to be created.**/
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.i("TAG", "MainActivity:: onCreateLoader");
String[] projection = {
TextNotesDb.KEY_ROWID,
TextNotesDb.KEY_GUID,
TextNotesDb.KEY_NOTE_NAME,
TextNotesDb.KEY_NOTE,
TextNotesDb.KEY_CREATION_DATE,
TextNotesDb.KEY_MODIFICATION_DATE
};
CursorLoader cursorLoader = new CursorLoader(this, MyContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
dataAdapter.swapCursor(null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
As in comment below my Question, I could solve it by adding 2 lines. Now it should look like this
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.notifyDataSetChanged(); // <-
listView.setAdapter(dataAdapter); // <-
dataAdapter.swapCursor(data);
}

Is it possible to add a ActionEvent Handler to a javaFX Textfield using addEventHandler method?

I tried to add action handlers to text field using the addEventHandler() but seem not to be working. Is it even possible o is it a bug? If I try the same with Button control everything is fine.
Here is the sample code:
package com.teste;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class EventHandlerTest extends Application {
#Override
public void start(Stage stage) throws Exception {
// TODO Auto-generated method stub
stage.setTitle("Custom JavaFX Event");
TextField btn = new TextField();
btn.setId("Fire Button");
btn.setText("Fire MyEvent'");
btn.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (event.getEventType().equals(ActionEvent.ACTION)) {
System.out.println("ActionEvent 2");
}
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
stage.setScene(new Scene(root, 300, 250));
stage.show();
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
}
Documentation says it should be possible, but can't find anything else. Any ideas?
If you use setOnAction rather than addEventHandler, then you will be able to capture the ActionEvent for the TextField.
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
System.out.println("ActionEvent: " + event);
}
});
I don't know why the addEventHandler code does not capture the event. I also tried addEventFilter as well and that did not work for me either (JavaFX 2.2).
Note that a TextField will generate an ActionEvent when you press the Enter key on the TextField.
In java 8 now is possible
btn.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("ActionEvent: " + event);
}
});
//Lambda Notation
btn.addEventHandler(ActionEvent.ACTION, event -> {
System.out.println("ActionEvent: " + event);
});