This program shall paste an image from clipboard into an ImageView (on Windows 10). Unfortunately the image is not correctly displayed.
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Clipboard cb = Clipboard.getSystemClipboard();
if (cb.hasImage()) {
Image image = cb.getImage();
imageView.setImage(image);
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
}
Steps to reproduce:
Start cmd.exe
Press ALT-Print to copy the cmd window into the clipboard
Start program PasteImageFromClipboard
Press "Paste" button in PasteImageFromClipboard
This result is displayed on my computer:
It should be like this:
Is there more code required to draw the image correctly?
found this solution by the help of
https://community.oracle.com/thread/2238566
package com.wilutions.jiraddin;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
java.awt.Image image = getImageFromClipboard();
if (image != null) {
javafx.scene.image.Image fimage = awtImageToFX(image);
imageView.setImage(fimage);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
private java.awt.Image getImageFromClipboard() {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
try {
return (java.awt.Image) transferable.getTransferData(DataFlavor.imageFlavor);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static javafx.scene.image.Image awtImageToFX(java.awt.Image image) throws Exception {
if (!(image instanceof RenderedImage)) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = bufferedImage;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) image, "png", out);
out.flush();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return new javafx.scene.image.Image(in);
}
}
i'm trying to get an URL from TextField exapmle: http://www.google.com and i have a WebViewthat it will be visible by clicking on the "Enter key" but the problem is when i run the application it didn't show anything note that i'm using FXML File.This is the code i've traied:
#FXML
private void onpressed (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent evt) {
if (evt.getCode() == KeyCode.ENTER){
String az = text1.getText();
//c.1
if(text1.getText().equals("1")){
web1.setVisible(true);
String hh = text11.getText();
Socket socket = new Socket();
try {
//open cursor
text1.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
writ.setCursor(Cursor.WAIT);
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
//do work
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load("http://www.google.com");
//close the window chooser
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//close chooser
Stage stage = new Stage();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
}
}
});
}
So please can any body explain for me where is the problem for this code and i'll be so thankful :)
Here is a simple example application that goes to the web page you typed in when you press enter in the text field:
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception {
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
final TextField text1 = new TextField();
WebView web = new WebView();
final WebEngine webEngine= web.getEngine();
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
if (ke.getCode().toString().equalsIgnoreCase("ENTER")) {
String urlString = text1.getText().trim();
webEngine.load(urlString);
}
}
});
pane.getChildren().addAll(web,text1);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch("application.Main");
}
}
You can try typing in https://www.google.com and it should take you there
If you exclude the http or https it should not work
Depending on your jre you may need to remove the #Override
I hope this helps
I am not really sure if you want 'if(text1.getText().equals("1")){' the if statement will only be true if someone types in the character "1" but how you set the web engine is by getting the text from the text field (text1) and getting the web engine to load it and it is good practice to put a .trim() at the end incase the user accidentally types in a space at the beginning of the end.
So your code should look something like this:
String urlString = text1.getText().trim();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(urlString);
And you complet code should look something like this:
#FXML
private void onpressed (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent evt) {
if (evt.getCode() == KeyCode.ENTER){
String az = text1.getText();
web1.setVisible(true);
String hh = text11.getText();
Socket socket = new Socket();
try {
//open cursor
text1.setCursor(Cursor.WAIT);
que.setCursor(Cursor.WAIT);
writ.setCursor(Cursor.WAIT);
ancpa.setCursor(Cursor.WAIT);
web1.setCursor(Cursor.WAIT);
web2.setCursor(Cursor.WAIT);
web3.setCursor(Cursor.WAIT);
web4.setCursor(Cursor.WAIT);
web5.setCursor(Cursor.WAIT);
web6.setCursor(Cursor.WAIT);
web7.setCursor(Cursor.WAIT);
web8.setCursor(Cursor.WAIT);
web9.setCursor(Cursor.WAIT);
String urlString = text1.getText().trim();
WebEngine myWebEngine = web1.getEngine();
myWebEngine.load(urlString);
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//close cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
}
catch (IOException e){
final Stage stg = new Stage();
stg.initModality(Modality.APPLICATION_MODAL);
stg.initOwner(stg);
stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
labelno.setText("Cannot connect to the internet...");
//close chooser
Stage stage = new Stage();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override public void handle(WindowEvent t) { } });
//set cursor
ancpa.setCursor(Cursor.DEFAULT);
web1.setCursor(Cursor.DEFAULT);
web2.setCursor(Cursor.DEFAULT);
web3.setCursor(Cursor.DEFAULT);
web4.setCursor(Cursor.DEFAULT);
web5.setCursor(Cursor.DEFAULT);
web6.setCursor(Cursor.DEFAULT);
web7.setCursor(Cursor.DEFAULT);
web8.setCursor(Cursor.DEFAULT);
web9.setCursor(Cursor.DEFAULT);
} finally{
try{ socket.close(); } catch (Exception e){ }
}
}
}
}
});
}
I hope this helps. If you have any questions just ask.
package com.example.libtracker;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private LibactivityMainActivity studentDBoperation;
private TextView editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentDBoperation = new LibactivityMainActivity(this);
studentDBoperation.open();
List values = studentDBoperation.getAllTriptakerActivity();
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
// connecting listview to another activity
try {
setContentView(R.layout.activity_main);
ListView mlistView = (ListView) findViewById(R.id.editText1);
mlistView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new String[] {"activity_main"}));
mlistView.setOnClickListener(new OnClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
String sText = ((TextView) view).getText().toString();
Intent intent = null;
if(sText.equals("activity_main"))
intent = new Intent(getBaseContext(),TriploggerActivity.class);
//else if(sText.equals("Help")) ..........
if(intent != null)
startActivity(intent);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end of connecting listview to another actovity
public void addUser(View view)
{
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
EditText text = (EditText) findViewById(R.id.editText1);
TriptakerActivity stud = studentDBoperation.addTriptakerActivity(text.getText().toString());
adapter.add(stud);
}
public void deleteFirstUser(View view) {
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
TriptakerActivity stud = null;
if (getListAdapter().getCount() > 0)
{
stud = (TriptakerActivity) getListAdapter().getItem(0);
studentDBoperation.deleteTriptakerActivity(stud);
adapter.remove(stud);
}
}
#Override
protected void onResume() {
studentDBoperation.open();
super.onResume();
}
#Override
protected void onPause() {
studentDBoperation.close();
super.onPause();
// public void linkclickview(View v)
//// {
//Intent i = new Intent(this,TriploggerActivity.class );
//startActivity(i);
}
}
`
This is the code that I want to use to connect or link to another activity, but it is not working.
Please kindly help me out. Thanks
I have a tabbed editor with TextArea and I want to save the selected file's textarea content.
But how can I do this?
Here I have my items defined (or what it's called on english. I'm danish) :
public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;
My code for adding a tab:
public static void AddTab(String title, String con) {
area = new TextArea();
lines = new ListView();
box = new VBox();
bps = new BorderPane();
bps.setLeft(lines);
bps.setRight(area);
box.getChildren().addAll(bps);
tabs = new Tab(title);
tabs.setContent(box);
pane.getTabs().add(tabs);
}
When i add a tab i use this code :
int i;
for (i = 0; i < GUI.Editor.pane.getTabs().size(); i++) {
}
String title = "New File (" + i + ")";
GUI.Editor.AddTab(title, null);
GUI.Editor.pane.getSelectionModel().select(i);
But how can I save a file on this way?.
Oh and of course I know I need a file dialog (and I have try to save file).
The only thing I will need is how to get the content from the selected tab (when I mean content I mean the TextArea's content).
As you are setting tab content is VBox it's bit difficult to get the TextArea directly. One way is by doing multiple type casts from VBox to Textarea we can get the selected area.
private static TextArea getSelectedTabContent() {
Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
if(selectedTabContent instanceof VBox){
Node borderPane = ((VBox) selectedTabContent).getChildren().get(0);
if(borderPane instanceof BorderPane){
Node textAreaNode = ((BorderPane) borderPane).getRight();
if(textAreaNode instanceof TextArea){
return (TextArea) textAreaNode;
}
}
}
return null;
}
Below is the complete code to save to file.
package com.pw.jnotepad.app;
import com.pw.jnotepad.app.providers.AlertBox;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
public class StackOverflowAnswer extends Application {
public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;
public static Stage window;
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
area = new TextArea();
lines = new ListView();
box = new VBox();
bps = new BorderPane();
bps.setTop(createMenuBar());
bps.setLeft(lines);
bps.setRight(area);
box.getChildren().addAll(bps);
tabs = new Tab("tab-1");
tabs.setContent(box);
pane.getTabs().add(tabs);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
// to create menu bar with file menu
private static MenuBar createMenuBar(){
Menu fileMenu = new Menu("File");
MenuItem saveFile = new MenuItem("Save");
saveFile.setOnAction(event -> {
System.out.println("Save file action triggered");
FileChooser fileChooser = createFileChooser("Save File");
File selectedFile = fileChooser.showSaveDialog(window);
if(selectedFile != null){
File savedFile = saveTextToFile(selectedFile);
if(savedFile!= null){
System.out.println("file saved successfully");
updateTabTitle(savedFile.getName());
}
}
});
fileMenu.getItems().addAll(saveFile);
return new MenuBar(fileMenu);
}
// to open save dialog window
private static FileChooser createFileChooser(String title) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter onlyTextFilesFilter = new FileChooser.ExtensionFilter("Txt files(*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(onlyTextFilesFilter);
fileChooser.setTitle(title);
fileChooser.setInitialDirectory(Paths.get("").toAbsolutePath().toFile());
return fileChooser;
}
// to save the file into disk
public static File saveTextToFile(File file) {
TextArea selectedTabContent = getSelectedTabContent();
if(selectedTabContent!=null){
try(BufferedWriter buffer = new BufferedWriter(new FileWriter(file));) {
ObservableList<CharSequence> paragraphs = selectedTabContent.getParagraphs();
paragraphs.forEach(charSequence -> {
try {
buffer.append(charSequence);
buffer.newLine();
} catch (IOException e) {
System.out.println("failed to write to text file.");
AlertBox.display("File Save Error", "failed to write to text file.");
e.printStackTrace();
}
});
buffer.flush();
return file;
} catch (IOException e) {
System.out.println("failed to write to text file.");
AlertBox.display("File Save Error", "failed to write to text file.");
e.printStackTrace();
}
}
return null;
}
// to get selected text area
private static TextArea getSelectedTabContent() {
Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
if(selectedTabContent instanceof VBox){
Node borderPane = ((VBox) selectedTabContent).getChildren().get(0);
if(borderPane instanceof BorderPane){
Node textAreaNode = ((BorderPane) borderPane).getRight();
if(textAreaNode instanceof TextArea){
return (TextArea) textAreaNode;
}
}
}
return null;
}
// to update tab title by saved file name
private static void updateTabTitle(String name){
pane.getSelectionModel().getSelectedItem().setText(name);
}
}
I would like to use multiple-page editor (eclipse RCP). I want to follow this tutorial
but I cannot get "plug-in with multiple page editor" when I create a new project. I have only :
Hello
with a view
with an introduction
mail template
Does anyone have an idea about how to get the option plug-in with multiple page editor when creating a new RCP project?
Thnx
PS: I use Galileo 3.5.2
Please use the Eclipse Indigo instead.
Otherwise, you can create from the empty plugin project.
Here is my example of multiple pages editor. PropertyFileEditor is multiple pages editor. Hope this will help you.
FileDocumentProvider.java
package com.bosch.training.eclipseplugin.editors;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.MultiPageEditorPart;
import com.bosch.training.eclipseplugin.LinkedProperties;
public class PropertyFileEditor extends MultiPageEditorPart {
public static String EDITOR_ID = "com.bosch.training.eclipseplugin.editors.PropertyFileEditor";
private Text m_keyText;
private Text m_valueText;
private TableViewer m_tableViewer;
private IPath m_filePath;
private Properties m_properties;
private FileEditor m_firstPage;
public PropertyFileEditor() {
}
#Override
protected void createPages() {
try {
m_filePath = ((FileEditorInput) getEditorInput()).getFilePath();
m_firstPage = new FileEditor();
addPage(m_firstPage, (FileEditorInput) getEditorInput());
addPage(createDesignPage());
setPagesText();
} catch (PartInitException e) {
e.printStackTrace();
}
}
private void setPagesText() {
setPageText(0, "Plain Text");
setPageText(1, "Properties");
}
#Override
public void doSave(IProgressMonitor monitor) {
m_firstPage.doSave(monitor);
}
#Override
public void doSaveAs() {
}
#Override
public boolean isSaveAsAllowed() {
return false;
}
private Control createDesignPage() {
Composite parent = new Composite(getContainer(), SWT.NONE);
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
parent.setLayout(new GridLayout(1, false));
// First row
Composite composite1 = new Composite(parent, SWT.NONE);
composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
composite1.setLayout(new GridLayout(3, false));
m_keyText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_keyText.setText("");
m_valueText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_valueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_valueText.setText("");
Button applyButton = new Button(composite1, SWT.PUSH);
applyButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
applyButton.setText("Apply");
applyButton.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
m_properties.put(m_keyText.getText(), m_valueText.getText());
// Update table
TableItem tableItem= new TableItem(m_tableViewer.getTable(), SWT.NONE);
tableItem.setText(new String[] { m_keyText.getText(), m_valueText.getText() });
// Update editor
IDocument doc = m_firstPage.getDocumentProvider().getDocument(getEditorInput());
int offset;
try {
offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
doc.replace(offset, 0, m_keyText.getText() + "=" + m_valueText.getText() + "\n");
} catch (BadLocationException ex) {
ex.printStackTrace();
}
// set text = ""
m_keyText.setText("");
m_valueText.setText("");
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
// Second row
Composite composite2 = new Composite(parent, SWT.NONE);
composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite2.setLayout(new GridLayout(1, false));
m_tableViewer = new TableViewer(composite2, SWT.FILL);
Table table = m_tableViewer.getTable();
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TableColumn columnKey = new TableColumn(table, SWT.LEAD);
columnKey.setText("Key");
columnKey.setWidth(300);
TableColumn columnValue = new TableColumn(table, SWT.FILL);
columnValue.setText("Value");
columnValue.setWidth(300);
table.setHeaderVisible(true);
table.setLinesVisible(true);
m_tableViewer.setContentProvider(new IStructuredContentProvider() {
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
#Override
public void dispose() {
}
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
});
m_tableViewer.setLabelProvider(new ITableLabelProvider() {
#Override
public void removeListener(ILabelProviderListener listener) {
}
#Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
#Override
public void dispose() {
}
#Override
public void addListener(ILabelProviderListener listener) {
}
#Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Entry) {
switch (columnIndex) {
case 0:
return String.valueOf(((Entry) element).getKey());
case 1:
return String.valueOf(((Entry) element).getValue());
}
}
return "";
}
#Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
});
m_tableViewer.setInput(loadProperties());
m_firstPage.getDocumentProvider().getDocument(getEditorInput()).addDocumentListener(new IDocumentListener() {
#Override
public void documentChanged(DocumentEvent event) {
m_tableViewer.setInput(loadProperties());
}
#Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
});
return parent;
}
private Object[] loadProperties() {
IDocument document = m_firstPage.getFileDocumentProvider().getDocument(getEditorInput());
m_properties = new LinkedProperties();
ByteArrayInputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(document.get().getBytes());
m_properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return m_properties.entrySet().toArray();
}
}
FileEditor.java
package com.bosch.training.eclipseplugin.editors;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
public class FileEditor extends AbstractTextEditor {
public static final String EDITOR_ID = "com.bosch.training.eclipseplugin.editors.FileEditor";
private FileDocumentProvider m_fileDocumentProvider;
public FileEditor() {
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope" });
internal_init();
}
protected void internal_init() {
configureInsertMode(ITextEditorExtension3.SMART_INSERT, false);
m_fileDocumentProvider = new FileDocumentProvider();
setDocumentProvider(m_fileDocumentProvider);
}
public FileDocumentProvider getFileDocumentProvider() {
return m_fileDocumentProvider;
}
}
FileEditorInput.java
package com.bosch.training.eclipseplugin.editors;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.PlatformUI;
public class FileEditorInput implements IPathEditorInput {
private IPath m_filePath;
public FileEditorInput(IPath path) {
if (path == null) {
throw new IllegalArgumentException();
}
this.m_filePath = path;
}
#Override
public int hashCode() {
return m_filePath.hashCode();
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof FileEditorInput)) {
return false;
}
FileEditorInput other = (FileEditorInput) obj;
return m_filePath.equals(other.m_filePath);
}
#Override
public boolean exists() {
return m_filePath.toFile().exists();
}
#Override
public ImageDescriptor getImageDescriptor() {
return PlatformUI.getWorkbench().getEditorRegistry().getImageDescriptor(m_filePath.toString());
}
#Override
public String getName() {
return m_filePath.toString();
}
#Override
public String getToolTipText() {
return m_filePath.makeRelative().toOSString();
}
#Override
public IPath getPath() {
return m_filePath;
}
#SuppressWarnings("rawtypes")
#Override
public Object getAdapter(Class adapter) {
return null;
}
#Override
public IPersistableElement getPersistable() {
// no persistence
return null;
}
public IPath getFilePath() {
return m_filePath;
}
public void setFilePath(IPath filePath) {
m_filePath = filePath;
}
}
PropertyFileEditor.java
package com.bosch.training.eclipseplugin.editors;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.MultiPageEditorPart;
import com.bosch.training.eclipseplugin.LinkedProperties;
public class PropertyFileEditor extends MultiPageEditorPart {
public static String EDITOR_ID = "com.bosch.training.eclipseplugin.editors.PropertyFileEditor";
private Text m_keyText;
private Text m_valueText;
private TableViewer m_tableViewer;
private IPath m_filePath;
private Properties m_properties;
private FileEditor m_firstPage;
public PropertyFileEditor() {
}
#Override
protected void createPages() {
try {
m_filePath = ((FileEditorInput) getEditorInput()).getFilePath();
m_firstPage = new FileEditor();
addPage(m_firstPage, (FileEditorInput) getEditorInput());
addPage(createDesignPage());
setPagesText();
} catch (PartInitException e) {
e.printStackTrace();
}
}
private void setPagesText() {
setPageText(0, "Plain Text");
setPageText(1, "Properties");
}
#Override
public void doSave(IProgressMonitor monitor) {
m_firstPage.doSave(monitor);
}
#Override
public void doSaveAs() {
}
#Override
public boolean isSaveAsAllowed() {
return false;
}
private Control createDesignPage() {
Composite parent = new Composite(getContainer(), SWT.NONE);
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
parent.setLayout(new GridLayout(1, false));
// First row
Composite composite1 = new Composite(parent, SWT.NONE);
composite1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
composite1.setLayout(new GridLayout(3, false));
m_keyText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_keyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_keyText.setText("");
m_valueText = new Text(composite1, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
m_valueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
m_valueText.setText("");
Button applyButton = new Button(composite1, SWT.PUSH);
applyButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
applyButton.setText("Apply");
applyButton.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
m_properties.put(m_keyText.getText(), m_valueText.getText());
// Update table
TableItem tableItem= new TableItem(m_tableViewer.getTable(), SWT.NONE);
tableItem.setText(new String[] { m_keyText.getText(), m_valueText.getText() });
// Update editor
IDocument doc = m_firstPage.getDocumentProvider().getDocument(getEditorInput());
int offset;
try {
offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
doc.replace(offset, 0, m_keyText.getText() + "=" + m_valueText.getText() + "\n");
} catch (BadLocationException ex) {
ex.printStackTrace();
}
// set text = ""
m_keyText.setText("");
m_valueText.setText("");
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
// Second row
Composite composite2 = new Composite(parent, SWT.NONE);
composite2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
composite2.setLayout(new GridLayout(1, false));
m_tableViewer = new TableViewer(composite2, SWT.FILL);
Table table = m_tableViewer.getTable();
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TableColumn columnKey = new TableColumn(table, SWT.LEAD);
columnKey.setText("Key");
columnKey.setWidth(300);
TableColumn columnValue = new TableColumn(table, SWT.FILL);
columnValue.setText("Value");
columnValue.setWidth(300);
table.setHeaderVisible(true);
table.setLinesVisible(true);
m_tableViewer.setContentProvider(new IStructuredContentProvider() {
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
#Override
public void dispose() {
}
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
});
m_tableViewer.setLabelProvider(new ITableLabelProvider() {
#Override
public void removeListener(ILabelProviderListener listener) {
}
#Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
#Override
public void dispose() {
}
#Override
public void addListener(ILabelProviderListener listener) {
}
#Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Entry) {
switch (columnIndex) {
case 0:
return String.valueOf(((Entry) element).getKey());
case 1:
return String.valueOf(((Entry) element).getValue());
}
}
return "";
}
#Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
});
m_tableViewer.setInput(loadProperties());
m_firstPage.getDocumentProvider().getDocument(getEditorInput()).addDocumentListener(new IDocumentListener() {
#Override
public void documentChanged(DocumentEvent event) {
m_tableViewer.setInput(loadProperties());
}
#Override
public void documentAboutToBeChanged(DocumentEvent event) {
}
});
return parent;
}
private Object[] loadProperties() {
IDocument document = m_firstPage.getFileDocumentProvider().getDocument(getEditorInput());
m_properties = new LinkedProperties();
ByteArrayInputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(document.get().getBytes());
m_properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return m_properties.entrySet().toArray();
}
}
I cannot tell you, if this template is available in Galileo. It is in Indigo.
But this template just combines two steps you can do on your own. Create an empty plugin project, open the MANIFEST.MF to open the plugin editor and select the extension tabs.
There you can add extension for editors and for wizards.
For a multipage editor click on Add, then select org.eclipse.ui.editors. In the template area at the bottom of the dialog select Multi-Page editor. Then enter the properties as show in your tutorial.
Repeat for the new wizard by selectin org.eclipse.ui.newWizard and the New File Wizard template.