Tooltip on Line Chart showing Date - charts

I want to add Tooltip when I move cursor over a chart line. I found this example:
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
public class AnimatedLineChart extends Application {
private static final int MAX_DATA_POINTS = 50;
private int xSeriesData = 0;
private XYChart.Series series1;
private XYChart.Series series2;
private XYChart.Series series3;
private ExecutorService executor;
private AddToQueue addToQueue;
private ConcurrentLinkedQueue<Number> dataQ1 = new ConcurrentLinkedQueue<Number>();
private ConcurrentLinkedQueue<Number> dataQ2 = new ConcurrentLinkedQueue<Number>();
private ConcurrentLinkedQueue<Number> dataQ3 = new ConcurrentLinkedQueue<Number>();
private NumberAxis xAxis;
private void init(Stage primaryStage) {
xAxis = new NumberAxis(0,MAX_DATA_POINTS,MAX_DATA_POINTS/10);
xAxis.setForceZeroInRange(false);
xAxis.setAutoRanging(false);
xAxis.setTickLabelsVisible(false);
xAxis.setTickMarkVisible(false);
xAxis.setMinorTickVisible(false);
NumberAxis yAxis = new NumberAxis();
yAxis.setAutoRanging(true);
//-- Chart
final LineChart<Number, Number> sc = new LineChart<Number, Number>(xAxis, yAxis) {
// Override to remove symbols on each data point
#Override protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item) {}
};
sc.setAnimated(false);
sc.setId("liveLineeChart");
sc.setTitle("Animated Line Chart");
//-- Chart Series
series1 = new XYChart.Series<Number, Number>();
series2 = new XYChart.Series<Number, Number>();
series3 = new XYChart.Series<Number, Number>();
sc.getData().addAll(series1, series2, series3);
primaryStage.setScene(new Scene(sc));
}
#Override public void start(Stage stage) {
stage.setTitle("Animated Line Chart Sample");
init(stage);
stage.show();
executor = Executors.newCachedThreadPool(new ThreadFactory() {
#Override public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
addToQueue = new AddToQueue();
executor.execute(addToQueue);
//-- Prepare Timeline
prepareTimeline();
}
private class AddToQueue implements Runnable {
public void run() {
try {
// add a item of random data to queue
dataQ1.add(Math.random());
dataQ2.add(Math.random());
dataQ3.add(Math.random());
Thread.sleep(500);
executor.execute(this);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
//-- Timeline gets called in the JavaFX Main thread
private void prepareTimeline() {
// Every frame to take any data from queue and add to chart
new AnimationTimer() {
#Override public void handle(long now) {
addDataToSeries();
}
}.start();
}
private void addDataToSeries() {
for (int i = 0; i < 20; i++) { //-- add 20 numbers to the plot+
if (dataQ1.isEmpty()) break;
series1.getData().add(new AreaChart.Data(xSeriesData++, dataQ1.remove()));
series2.getData().add(new AreaChart.Data(xSeriesData++, dataQ2.remove()));
series3.getData().add(new AreaChart.Data(xSeriesData++, dataQ3.remove()));
}
// remove points to keep us at no more than MAX_DATA_POINTS
if (series1.getData().size() > MAX_DATA_POINTS) {
series1.getData().remove(0, series1.getData().size() - MAX_DATA_POINTS);
}
if (series2.getData().size() > MAX_DATA_POINTS) {
series2.getData().remove(0, series2.getData().size() - MAX_DATA_POINTS);
}
if (series3.getData().size() > MAX_DATA_POINTS) {
series3.getData().remove(0, series3.getData().size() - MAX_DATA_POINTS);
}
// update
xAxis.setLowerBound(xSeriesData-MAX_DATA_POINTS);
xAxis.setUpperBound(xSeriesData-1);
}
public static void main(String[] args) {
launch(args);
}
}
For example I would like to display something like this:
Is this possible with JavaFX 8? On mouse hover it is showing Date.
Is there any similar example that I can use for my case?

I have managed to pull something very close to what you want. Have a look at the image below
I have used DateAxis for populating date on X-axis, along with events on Y-axis. Once the data is populated in the LineChart, iterate through its data and apply a tooltip on each node.
I have also used a styleclass on mouseEntered to apply the effect as shown on the image. This styleclass is removed on mouseExit
Have a look at the code below :
ToolTipOnLineChart.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Tooltip;
import javafx.stage.Stage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ToolTipOnLineChart extends Application {
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public void start(Stage stage) throws ParseException {
stage.setTitle("Line Chart Sample");
final DateAxis xAxis = new DateAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Date");
yAxis.setLabel("Events");
final LineChart<Date,Number> lineChart = new LineChart<>(xAxis, yAxis);
lineChart.setTitle("Events");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy");
XYChart.Series<Date,Number> series = new XYChart.Series<>();
series.setName("Events this Year");
series.getData().add(new XYChart.Data(dateFormat.parse("11/Jan/2014"), 23));
series.getData().add(new XYChart.Data(dateFormat.parse("09/Feb/2014"), 14));
series.getData().add(new XYChart.Data(dateFormat.parse("22/Mar/2014"), 15));
series.getData().add(new XYChart.Data(dateFormat.parse("14/Apr/2014"), 24));
series.getData().add(new XYChart.Data(dateFormat.parse("22/May/2014"), 34));
series.getData().add(new XYChart.Data(dateFormat.parse("07/Jun/2014"), 36));
series.getData().add(new XYChart.Data(dateFormat.parse("22/Jul/2014"), 22));
series.getData().add(new XYChart.Data(dateFormat.parse("21/Aug/2014"), 45));
series.getData().add(new XYChart.Data(dateFormat.parse("04/Sep/2014"), 43));
series.getData().add(new XYChart.Data(dateFormat.parse("22/Oct/2014"), 17));
series.getData().add(new XYChart.Data(dateFormat.parse("30/Nov/2014"), 29));
series.getData().add(new XYChart.Data(dateFormat.parse("10/Dec/2014"), 25));
Scene scene = new Scene(lineChart,800,600);
scene.getStylesheets().add(getClass().getResource("chart.css").toExternalForm());
lineChart.getData().add(series);
stage.setScene(scene);
stage.show();
/**
* Browsing through the Data and applying ToolTip
* as well as the class on hover
*/
for (XYChart.Series<Date, Number> s : lineChart.getData()) {
for (XYChart.Data<Date, Number> d : s.getData()) {
Tooltip.install(d.getNode(), new Tooltip(
d.getXValue().toString() + "\n" +
"Number Of Events : " + d.getYValue()));
//Adding class on hover
d.getNode().setOnMouseEntered(event -> d.getNode().getStyleClass().add("onHover"));
//Removing class on exit
d.getNode().setOnMouseExited(event -> d.getNode().getStyleClass().remove("onHover"));
}
}
}
public static void main(String[] args) {
launch(args);
}
}
chart.css
.onHover{
-fx-background-color: ORANGE;
}

Related

how to create a table by using Nattable and add value into its column

I have to create a Nat Table with three column and add value in the column.please help me. thanks in Advance
hope this helps. For the details of the layer you can refer the http://www.vogella.com/tutorials/NatTable/article.html link which is quite apt.
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DummyBodyDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayerTransform;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.LabelStack;
import org.eclipse.nebula.widgets.nattable.layer.cell.IConfigLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.style.Style;
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Nat_explore {
private BodyLayerStack bodyLayer ;
private int statusColumn;
private int statusRejected;
private int statusInProgress;
private boolean check = false;
private NatTable nattable;
private String[] properties;
private static final String FOO_LABEL = "FOO";
private static final String CELL_LABEL = "Cell_LABEL";
public static void main(String[] args) {
new Nat_explore();
}
public Nat_explore() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
properties = new String[3];
for(int i=0;i<properties.length;i++){
properties[i]="Column"+i;
}
//Setting the data layout layer
GridData gridData = new GridData();
gridData.heightHint = (int) 24;
gridData.widthHint = (int) 110;
IConfigRegistry configRegistry = new ConfigRegistry();
//Body Data Provider
IDataProvider dataProvider = new DataProvider(properties.length,55);
bodyLayer= new BodyLayerStack(dataProvider);
//datalayer.addConfiguration(new
//Column Data Provider
DefaultColumnHeaderDataProvider columnData = new DefaultColumnHeaderDataProvider(properties);
ColumnHeaderLayerStack columnlayer = new ColumnHeaderLayerStack(columnData);
//Row Data Provider
DefaultRowHeaderDataProvider rowdata = new DefaultRowHeaderDataProvider(dataProvider);
RowHeaderLayerStack rowlayer = new RowHeaderLayerStack(rowdata);
//Corner Data Provider
DefaultCornerDataProvider cornerdata = new DefaultCornerDataProvider(columnData, rowdata);
DataLayer cornerDataLayer = new DataLayer(cornerdata);
CornerLayer cornerLayer = new CornerLayer(cornerDataLayer, rowlayer, columnlayer);
GridLayer gridlayer = new GridLayer(bodyLayer, columnlayer, rowlayer, cornerLayer);
nattable = new NatTable(shell, gridlayer,false);
// Change for paint
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
//#Override
public void accumulateConfigLabels(LabelStack configLabels,int columnPosition, int rowPosition) {
int columnIndex = bodyLayer.getColumnIndexByPosition(columnPosition);
int rowIndex = bodyLayer.getRowIndexByPosition(rowPosition);
if (columnIndex == 2 && rowIndex == 45) {
configLabels.addLabel(FOO_LABEL);
}
else if ((columnIndex == statusColumn) && (rowIndex == statusRejected) && (check ==true)) {
configLabels.addLabel(CELL_LABEL);
}
}
};
bodyLayer.setConfigLabelAccumulator(cellLabelAccumulator);
nattable.addConfiguration(new DefaultNatTableStyleConfiguration());
nattable.addConfiguration(new AbstractRegistryConfiguration() {
//#Override
public void configureRegistry(IConfigRegistry configRegistry) {
Style cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR,GUIHelper.COLOR_YELLOW);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle,DisplayMode.NORMAL, FOO_LABEL);
cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR,GUIHelper.COLOR_RED);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle,DisplayMode.NORMAL, CELL_LABEL);
}
});
nattable.setLayoutData(gridData);
nattable.setConfigRegistry(configRegistry);
nattable.configure();
shell.open();
while (!shell.isDisposed()) {
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public class DataProvider extends DummyBodyDataProvider{
public DataProvider(int columnCount, int rowCount) {
super(columnCount, rowCount);
}
#Override
public int getColumnCount() {
return properties.length;
}
#Override
public Object getDataValue(int columnIndex, int rowIndex) {
return new String("Column"+columnIndex+" Row"+rowIndex);
}
#Override
public int getRowCount() {
return 55;
}
#Override
public void setDataValue(int arg0, int arg1, Object arg2) {
}
}
public class BodyLayerStack extends AbstractLayerTransform {
private SelectionLayer selectionLayer;
public BodyLayerStack(IDataProvider dataProvider) {
DataLayer bodyDataLayer = new DataLayer(dataProvider);
ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(bodyDataLayer);
ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
this.selectionLayer = new SelectionLayer(columnHideShowLayer);
ViewportLayer viewportLayer = new ViewportLayer(this.selectionLayer);
setUnderlyingLayer(viewportLayer);
}
public SelectionLayer getSelectionLayer() {
return this.selectionLayer;
}
}
public class ColumnHeaderLayerStack extends AbstractLayerTransform {
public ColumnHeaderLayerStack(IDataProvider dataProvider) {
DataLayer dataLayer = new DataLayer(dataProvider);
ColumnHeaderLayer colHeaderLayer = new ColumnHeaderLayer(dataLayer,Nat_explore.this.bodyLayer, Nat_explore.this.bodyLayer.getSelectionLayer());
setUnderlyingLayer(colHeaderLayer);
}
}
public class RowHeaderLayerStack extends AbstractLayerTransform {
public RowHeaderLayerStack(IDataProvider dataProvider) {
DataLayer dataLayer = new DataLayer(dataProvider, 50, 20);
RowHeaderLayer rowHeaderLayer = new RowHeaderLayer(dataLayer,Nat_explore.this.bodyLayer, Nat_explore.this.bodyLayer.getSelectionLayer());setUnderlyingLayer(rowHeaderLayer);
}
}
}

JavaFX 2 XYChart.Series and setOnMouseEntered

Is it possible to set instance of XYChart.Series to act on setOnMouseEntered? It seems to me that one precondition to make it work would be to implement EventTarget interface. As for JavaFX XYChart.Series I would like to highlight the following data series when cursor touches the yellow line (instance of XYChart.Series):http://docs.oracle.com/javafx/2.0/charts/img/line-series.png
To be more precise I would like to do the following but for instance of XYChart.Series not Button:
public class Temp {
/*code removed*/
Button btn = new Button("Button to touch");
btn.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
System.out.println("Cursor just touched the button!");
}
});
/*code removed*/
}
Lookup the appropriate nodes and add the event handlers you want to them.
Here is an example.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.chart.*;
import javafx.scene.effect.Glow;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
public class LineChartSample extends Application {
#Override public void start(Stage stage) {
//create the chart
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Number of Month");
final LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
XYChart.Series series = new XYChart.Series();
series.setName("My portfolio");
series.getData().addAll(new XYChart.Data(1, 23),new XYChart.Data(2, 14),new XYChart.Data(3, 15),new XYChart.Data(4, 24),new XYChart.Data(5, 34),new XYChart.Data(6, 36),new XYChart.Data(7, 22),new XYChart.Data(8, 45),new XYChart.Data(9, 43),new XYChart.Data(10, 17),new XYChart.Data(11, 29),new XYChart.Data(12, 25));
lineChart.getData().add(series);
// show the scene.
Scene scene = new Scene(lineChart, 800, 600);
stage.setScene(scene);
stage.show();
// make the first series in the chart glow when you mouse over it.
Node n = lineChart.lookup(".chart-series-line.series0");
if (n != null && n instanceof Path) {
final Path path = (Path) n;
final Glow glow = new Glow(.8);
path.setEffect(null);
path.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent e) {
path.setEffect(glow);
}
});
path.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent e) {
path.setEffect(null);
}
});
}
}
public static void main(String[] args) { launch(args); }
}

GWT RPC - Why the results from database are printed twice ?

I am writing a simple app to enter a user into database & display list of users using GWT RPC, Hibernate in Eclipse. The problem I am getting is that the list of users is printed twice.
Here is my code where I call insert user & display users list methods.
package rpctest.client;
import java.util.ArrayList;
import rpctest.shared.User;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
//final Label label1 = new Label("First Name");
//final Label label2 = new Label("Last Name");
private FlexTable userFlexTable = new FlexTable();
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync callService = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
userFlexTable.setText(0, 0, "User ID");
userFlexTable.setText(0, 1, "First Name");
userFlexTable.setText(0, 2, "Second Name");
userFlexTable.setText(0, 3, "Remove");
//add input boxes to panel
addpanel1.add(firstName);
addpanel1.add(lastName);
firstName.setFocus(true);
//add input/result panels
mainpanel.add(userFlexTable);
mainpanel.add(addpanel1);
addpanel1.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addStock();
}
});
lastName.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
RootPanel.get().add(mainpanel);
getUser();
}
private void addStock(){
String name1 = firstName.getValue();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
/*if (!name1.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
firstName.selectAll();
return;
}*/
firstName.setValue("");
String name2 = lastName.getValue();
/*if (!name2.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
lastName.selectAll();
return;
}*/
lastName.setValue("");
firstName.setFocus(true);
callService.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
// Add the user to the table.
// int row = userFlexTable.getRowCount();
// userFlexTable.setText(row, 1, result);
getUser();
}
});
}
private void getUser(){
callService.getUser(new AsyncCallback<User[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("Problem in database connection");
}
#Override
public void onSuccess(User[] result) {
// TODO Auto-generated method stub
for(int i = 0; i < result.length; i ++)
{
//String s = result[i].getFirstName();
int row = userFlexTable.getRowCount();
userFlexTable.setText(row, 0, result[i].getId().toString());
userFlexTable.setText(row, 1, result[i].getFirstName());
userFlexTable.setText(row, 2, result[i].getLastName());
}
}
});
}
}
Man did you notice that you are calling getUser twice if the entered Name is valid and the call to the service is successfull??
You have to remove one of them!
getUser is called on every new entry & all data is entered again into table.

eclipse rcp : help to create a customized StyledText widget

I want a customized StyledText widget which can accept a keyword list,then highlight these keywords!
I found it's very hard to implement it by myself.
God damned! after spent hours searching the web, I finally found some sample code from the book The Definitive Guide to SWT and JFace, it's quite simple :
Main class :
package amarsoft.rcp.base.widgets.test;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import amarsoft.rcp.base.widgets.SQLSegmentEditor;
public class PageDemo extends ApplicationWindow {
public PageDemo(Shell parentShell) {
super(parentShell);
final Composite topComp = new Composite(parentShell, SWT.BORDER);
FillLayout fl = new FillLayout();
fl.marginWidth = 100;
topComp.setLayout(fl);
new SQLSegmentEditor(topComp);
}
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new PageDemo(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
package amarsoft.rcp.base.widgets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
/**
* SQL语句/SQL语句片段编辑器,除了内容编辑之外,提供一个额外的功能——常用SQL语句关键字高亮显示。
* #author ggfan#amarsoft
*
*/
public class SQLSegmentEditor extends Composite{
private StyledText st;
public SQLSegmentEditor(Composite parent) {
super(parent, SWT.NONE);
this.setLayout(new FillLayout());
st = new StyledText(this, SWT.WRAP);
st.addLineStyleListener(new SQLSegmentLineStyleListener());
}
}
package amarsoft.rcp.base.widgets;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.LineStyleEvent;
import org.eclipse.swt.custom.LineStyleListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.wb.swt.SWTResourceManager;
public class SQLSegmentLineStyleListener implements LineStyleListener {
private static final Color KEYWORD_COLOR = SWTResourceManager
.getColor(SWT.COLOR_BLUE);
private List<String> keywords = new ArrayList<String>();
public SQLSegmentLineStyleListener() {
super();
keywords.add("select");
keywords.add("from");
keywords.add("where");
}
#Override
public void lineGetStyle(LineStyleEvent event) {
List<StyleRange> styles = new ArrayList<StyleRange>();
int start = 0;
int length = event.lineText.length();
System.out.println("current line length:" + event.lineText.length());
while (start < length) {
System.out.println("while lopp");
if (Character.isLetter(event.lineText.charAt(start))) {
StringBuffer buf = new StringBuffer();
int i = start;
for (; i < length
&& Character.isLetter(event.lineText.charAt(i)); i++) {
buf.append(event.lineText.charAt(i));
}
if (keywords.contains(buf.toString())) {
styles.add(new StyleRange(event.lineOffset + start, i - start, KEYWORD_COLOR, null, SWT.BOLD));
}
start = i;
}
else{
start ++;
}
}
event.styles = (StyleRange[]) styles.toArray(new StyleRange[0]);
}
}

Identify a class call by another class from another package in eclipse galileo

Here I have a set of resource bundles( a .properties java class) that been called by many classes in a eclipse project file. I just wondering is it eclipse got any shortcut key or function to identify automatically the class(resource bundles) from another package that have been call from another class in different package.
The line that call another package resource bundle is
private ResourceBundle useCaseResourceBundle;
The full code is
package my.com.infopro.icba10.accounting.ui.maintainproductgl;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import my.com.infopro.icba10.accounting.delegate.AccountingDelegate;
import my.com.infopro.icba10.accounting.domain.GLField;
import my.com.infopro.icba10.accounting.domain.GLProduct;
import my.com.infopro.icba10.accounting.domain.GLProductDetail;
import my.com.infopro.icba10.admin.vlh.lov.CurrencyLov;
import my.com.infopro.icba10.kernel.uiframework.annotation.ValidationConfigFile;
import my.com.infopro.icba10.kernel.uiframework.binding.PresentationModelFactory;
import my.com.infopro.icba10.kernel.uiframework.component.CustomizedCombobox;
import my.com.infopro.icba10.kernel.uiframework.form.IconFactory;
import my.com.infopro.icba10.kernel.uiframework.form.IconType;
import my.com.infopro.icba10.kernel.uiframework.form.builders.CustomizedPanelBuilder;
import my.com.infopro.icba10.kernel.uiframework.form.builders.PanelBuilderFactory;
import my.com.infopro.icba10.kernel.uiframework.session.UserSessionProfileStore;
import my.com.infopro.icba10.kernel.uiframework.util.LayoutType;
import my.com.infopro.icba10.kernel.uiframework.validation.controls.CustomizedForm;
import my.com.infopro.icba10.kernel.util.configuration.CustomConfig;
import my.com.infopro.icba10.kernel.util.db.DataAccessMode;
import my.com.infopro.icba10.kernel.valuelisthandler.lov.Lov;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.log4j.Logger;
import com.jgoodies.binding.beans.Model;
import com.jgoodies.binding.list.SelectionInList;
/* =================================================================================================
* HISTORY
* -------------------------------------------------------------------------------------------------
* Date Author Remarks
* -------------------------------------------------------------------------------------------------
* 2010/08/22 hmho class created
* =================================================================================================
*/
#ValidationConfigFile("my.com.infopro.icba10.cbs.core.ui.vconfig.maintainproductglset-vconfig")
public class MaintainProductGLCopyPopUp extends CustomizedForm implements ActionListener {
private Logger logger= Logger.getLogger(MaintainProductGLCopyPopUp.class);
private CustomConfig config = CustomConfig.getInstance();
private ResourceBundle useCaseResourceBundle;
private UserSessionProfileStore userSessionProfileStore= UserSessionProfileStore.getInstance();
private CustomizedCombobox currencyComboBox;
private CustomizedCombobox glSetCodeComboBox;
private JButton okButton = new JButton();
private GLProduct fromGLProduct;
private GLProduct toGLProduct;
private MaintainProductGLMaintForm form;
private String glSetCode;
private String glSetDescription;
private Map<String,List<GLProductDetail>> glDetailMap = new HashMap<String,List<GLProductDetail>>();
private AccountingDelegate accountingDelegate;
public MaintainProductGLCopyPopUp(MaintainProductGLMaintForm form,ResourceBundle useCaseResourceBundle,
GLProduct glProduct,Map<String,List<GLProductDetail>> glDetailMap) {
super();
this.form = form;
this.useCaseResourceBundle = useCaseResourceBundle;
this.toGLProduct = glProduct;
this.glDetailMap = glDetailMap;
}
#Override
public boolean isFormValidatable() {
return true;
}
public void init() {
initPanels();
initBindingAndValidation();
initCode();
initEventHandling();
}
private void initPanels() {
setLayout(new BorderLayout());
add(buildCopyPanel(), BorderLayout.CENTER);
}
private void initBindingAndValidation() {
fromGLProduct = new GLProduct();
presentationModelDelegate = PresentationModelFactory.getPresentationModel(this,
getFormBeans(), new String[]{GLProduct.class.getSimpleName()});
fromGLProduct.setBankingConcept(toGLProduct.getBankingConcept());
fromGLProduct.setModuleCode(toGLProduct.getModuleCode());
glSetCode = toGLProduct.getGlSetCode();
glSetDescription = toGLProduct.getGlSetDescription();
logger.debug("init in copy " );
logger.debug("toGLProduct " + toGLProduct.getGlSetCode());
logger.debug("toGLProduct " + toGLProduct.getGlSetDescription());
}
private void initCode() {
accountingDelegate = new AccountingDelegate();
Lov currencyLov = new CurrencyLov();
presentationModelDelegate.bindComboBoxWithValues(currencyComboBox, currencyLov);
}
private void initEventHandling() {
currencyComboBox.addActionListener(this);
okButton.addActionListener(this);
}
private JPanel buildCopyPanel() {
CustomizedPanelBuilder builder = PanelBuilderFactory.createPanelBuilder(LayoutType.SINGLE_CENTERED);
JPanel popupPanel = new JPanel();
popupPanel.setLayout(new BorderLayout());
popupPanel.setBorder(new TitledBorder (useCaseResourceBundle.getString("copyPanel")));
JPanel copyPanel = new JPanel();
currencyComboBox= new CustomizedCombobox();
glSetCodeComboBox= new CustomizedCombobox();
builder.addComponentGroup(useCaseResourceBundle.getString("currency"), "GLProduct.currencyCode", currencyComboBox);
builder.addComponentGroup(useCaseResourceBundle.getString("glSetCode"), "GLProduct.glSetCode", glSetCodeComboBox);
copyPanel = builder.getStandardPanel();
popupPanel.add(copyPanel, BorderLayout.CENTER);
popupPanel.add(buildButtonPanel(), BorderLayout.SOUTH);
return popupPanel;
}
private JPanel buildButtonPanel() {
JPanel innerButtonPanel = new JPanel();
okButton = new JButton();
okButton.setText(useCaseResourceBundle.getString("okButton"));
okButton.setIcon(IconFactory.createIcon(IconType.OK));
innerButtonPanel.add(okButton);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(innerButtonPanel,BorderLayout.EAST);
return buttonPanel;
}
public void registerComponentNames() {
}
#Override
protected void createFormBeans() {
fromGLProduct = new GLProduct();
}
#Override
public Model[] getFormBeans() {
return new Model[]{fromGLProduct};
}
#Override
protected void setFormBeans(final Model[] updatedBean) {
fromGLProduct = (GLProduct) updatedBean[0];
}
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
final Object sourceObject = event.getSource();
if (sourceObject.equals(okButton)) {
if(null!=fromGLProduct.getCurrencyCode() && null!=fromGLProduct.getGlSetCode()){
setCopyData();
searchFrame.dispose();
}
}
if (sourceObject.equals(currencyComboBox)) {
List<GLProduct> glSetCodeList = accountingDelegate.findAvailableGlProduct(fromGLProduct);
if(glSetCodeList.size()<=0) {
glSetCodeList.add(new GLProduct());
}
presentationModelDelegate.bindComboBoxWithValues(glSetCodeComboBox, glSetCodeList, "glSetCode",true);
glSetCodeComboBox.createListCellRendererHandler();
}
}
private void setCopyData() {
userSessionProfileStore.setApplicationQueryCall();
logger.debug("copying " );
logger.debug("toGLProduct1 " + toGLProduct.getGlSetCode());
logger.debug("toGLProduct1 " + toGLProduct.getGlSetDescription());
GLProduct copyProduct = accountingDelegate.copyGLProducts(fromGLProduct, toGLProduct);
logger.debug("fromGLProduct " + fromGLProduct.getGlSetCode());
logger.debug("fromGLProduct " + fromGLProduct.getGlSetDescription());
logger.debug("copyProduct " + copyProduct.getGlSetCode());
logger.debug("copyProduct " + copyProduct.getGlSetDescription());
GLField glField = new GLField();
if(null!=copyProduct){
// copyProduct.setGlSetCode(glSetCode);
// copyProduct.setGlSetDescription(glSetDescription);
// Model[] models = new Model[] {copyProduct, glField};
// form.getPresentationModelDelegate().reinitBean(copyProduct);
if(copyProduct.getGLProductDetailList().size()>0){
form.getGlSetTableManagerModel().clearItems();
BeanComparator comparator = new BeanComparator("glField");
Collections.sort(copyProduct.getGLProductDetailList(), comparator);
form.setGlSetTableManagerModel(copyProduct.getGLProductDetailList());
logger.debug("Copy List Size 2 " + copyProduct.getGLProductDetailList().size());
}
SelectionInList selectionInList = form.getGlSetTableManagerModel()
.getItemSelectionsList();
List<GLProductDetail> glProductDetails = new ArrayList<GLProductDetail>();
glProductDetails.clear();
for(int i=0;i<selectionInList.getSize();i++){
GLProductDetail glProductDetail = (GLProductDetail) selectionInList
.getElementAt(i);
glProductDetail.setAction(DataAccessMode.INSERT);
glProductDetails.add(glProductDetail);
}
glDetailMap.clear();
glDetailMap.put(useCaseResourceBundle.getString("defaultCategoryCode"),glProductDetails);
form.setGlProductDetailMap(glDetailMap);
for(String key :form.getGlProductDetailMap().keySet()){
List<GLProductDetail>gls = form.getGlProductDetailMap().get(key);
for(GLProductDetail gl:gls){
logger.debug("Map " +gls.size());
if(null!=gl.getGlCode()){
logger.debug("Map " + gl.getGlField());
logger.debug("Map " + gl.getGlCode());
}
}
}
}
}
}
Is there any way so that i can use any key or function in eclipse to open the java file refer by the useCaseResourceBundle from this class. In some case its easier because the class already declared it clearly.
Example
private ResourceBundle resourceBundle = config.getPropResourceBundle("KERN_BUNDLE_UIFRAMEWORK");
Ctrl+Shift+G
or
Menu -> Search -> References -> ...
Search for references to the selected
element in the workspace / Project / Hierarchy / Working Set...