How to test swt wizard GUI with jmeter - eclipse

public class CloudDeploymentOptionsCreationWizardPage3ACO extends WizardPage {
class MedianBestChart {
JFreeChart chart;
ChartComposite innerChartComposite;
java.awt.Color awtRedColor;
Shape downTriangleShap;
Shape upTriangleShape;
XYPlot plot;
XYLineAndShapeRenderer renderer;
XYSeries bestValsSeries;
XYSeries medianValsSeries;
XYSeries diffValsSeries;
XYSeriesCollection dataset;
MedianBestChart(String title, String yAxisText) {
this.bestValsSeries = new XYSeries("Best candidate");
this.medianValsSeries = new XYSeries("Median");
this.diffValsSeries = new XYSeries("Diff");
this.dataset = new XYSeriesCollection();
this.dataset.addSeries(this.bestValsSeries);
this.dataset.addSeries(this.medianValsSeries);
this.dataset.addSeries(this.diffValsSeries);
this.awtRedColor = SWTUtils.toAwtColor(SWTResourceManager
.getColor(SWT.COLOR_RED));
this.downTriangleShap = ShapeUtilities.createDownTriangle(3);
this.upTriangleShape = ShapeUtilities.createUpTriangle(3);
this.chart = createChart(title, yAxisText);
this.innerChartComposite = new ChartComposite(
CloudDeploymentOptionsCreationWizardPage3ACO.this.chartParentComposite,
SWT.FILL, this.chart, true);
// grid data for the composite;
final GridData chartCompositeGridData = new GridData(SWT.FILL, // horizontalAlignment;
SWT.FILL, // verticalAlignment;
true, // grabExcessHorizontalSpace;
true); // grabExcessVerticalSpace;
chartCompositeGridData.grabExcessHorizontalSpace = true;
chartCompositeGridData.grabExcessVerticalSpace = true;
this.innerChartComposite.setLayoutData(chartCompositeGridData);
this.innerChartComposite.setRangeZoomable(false);
this.innerChartComposite.setDomainZoomable(false);
this.innerChartComposite.setVisible(true);
this.chart.setBorderVisible(false);
CloudDeploymentOptionsCreationWizardPage3ACO.this.chartParentComposite
.layout(true);
}
JFreeChart createChart(String title, String yAxisText) {
// create the chart...
final JFreeChart chart = ChartFactory.createXYLineChart(title,
"Nr. candidates", // x
// axis
// label
yAxisText, // y axis label
this.dataset, // data
PlotOrientation.VERTICAL, true, // include legend
false, // tooltips
false // urls
);
chart.setBackgroundPaint(SWTUtils.toAwtColor(Display.getDefault()
.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)));
Font titleFontTmp = chart.getTitle().getFont();
Font chartTitleFont = new Font("Plot title font",
titleFontTmp.getStyle(), titleFontTmp.getSize() - 6);
chart.getTitle().setFont(chartTitleFont);
this.plot = chart.getXYPlot();
this.plot.setBackgroundPaint(java.awt.Color.white);
this.plot.setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
this.plot.setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
this.renderer = new XYLineAndShapeRenderer(true, true) {
private static final long serialVersionUID = 8963966491796723264L;
#Override
public LegendItem getLegendItem(int datasetIndex, int series) {
if (series != 2) {
return super.getLegendItem(datasetIndex, series);
}
else {
return null;
}
}
};
this.renderer.setSeriesLinesVisible(0, true);
this.renderer.setSeriesShapesVisible(0, false);
this.renderer.setSeriesPaint(0, java.awt.Color.blue);
this.renderer.setSeriesLinesVisible(1, true);
this.renderer.setSeriesShapesVisible(1, false);
this.renderer.setSeriesPaint(1, new java.awt.Color(210, 105, 30));
this.renderer.setSeriesStroke(2, new BasicStroke(3.0f,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f,
new float[] { 2.0f, 6.0f }, 0.0f));
this.plot.setRenderer(this.renderer);
final NumberAxis domainAxis = (NumberAxis) this.plot
.getDomainAxis();
domainAxis
.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
final NumberAxis rangeAxis = (NumberAxis) this.plot.getRangeAxis();
rangeAxis.setNumberFormatOverride(NumberFormat
.getInstance(Locale.US));
return chart;
}
XYSeries getXYSeries(List<Double> vals, XYSeries series) {
series.clear();
for (int i = 0; i < vals.size(); ++i) {
series.add(i + 1, vals.get(i));
}
return series;
}
void updateChart(List<Double> bestVals, List<Double> medianVals) {
int size = bestVals.size();
this.bestValsSeries = getXYSeries(bestVals, this.bestValsSeries);
this.medianValsSeries = getXYSeries(medianVals,
this.medianValsSeries);
this.diffValsSeries.clear();
if (size > 1) {
this.diffValsSeries.add(size, bestVals.get(size - 1));
this.diffValsSeries.add(size, medianVals.get(size - 1));
}
this.renderer.setSeriesPaint(2, java.awt.Color.green);
this.renderer.setSeriesShape(2, this.upTriangleShape);
if (this.dataset.getItemCount(0) > 0) {
if (betterThanMedian(this.dataset.getSeries(0),
this.dataset.getSeries(1), false)) {
this.renderer.setSeriesPaint(2, java.awt.Color.red);
this.renderer.setSeriesShape(2, this.downTriangleShap);
}
}
// Refresh chart
this.plot.setDataset(this.dataset);
}
}
private Label lblLcloudenvironmentval;
private Label lblVMsAtStartVal;
private Label reconfigRulesVal;
private Label lCostVal;
private Label lCostBetterThanVal;
private Label lMedianResponseTimesVal;
private Label lMedianResponseTimesBetterThanVal;
private Label lTimeoutsVal;
private Label lTimeoutsBetterThanVal;
private ProgressBar currentCDOprogressBar;
private ProgressBar overallProgressBar;
private boolean optimizationStarted;
private CDOCreationOptimizedAutomaticMethod cdoCreationJob;
private boolean saveBestFoundCDO;
private Label lblRunning;
private Label lblSimulatedCandidates;
private Label lRunningVal;
private Label lSimulatedCandidatesVal;
private Date optimizationStartedDate;
private Group grpBestFoundCandidate;
private Label lblCurrentCloudDeployment;
private Label lblOverallProgress;
private Button btnDetailsBestCDO;
private final Color swtBlackColor;
private final Color swtGreenColor;
private final Color swtRedColor;
private MedianBestChart costChart;
private MedianBestChart responseTimeChart;
private MedianBestChart slaViolationsChart;
private final Job elapsedTimeUpdaterJob = new Job(
"Elapsed Time Updater Job") {
private volatile boolean cancel = false;
#Override
protected void canceling() {
this.cancel = true;
}
#Override
protected IStatus run(
IProgressMonitor arg0) {
while (true) {
Display.getDefault()
.asyncExec(
new Runnable() {
#Override
public void run() {
CloudDeploymentOptionsCreationWizardPage3ACO.this.lRunningVal
.setText(Utilities
.getElapsedTime(CloudDeploymentOptionsCreationWizardPage3ACO.this.optimizationStartedDate));
}
});
try {
getThread();
Thread.sleep(1000);
if (this.cancel) {
return Status.OK_STATUS;
}
}
catch (InterruptedException e) {
Utilities
.logError(e
.getMessage());
}
}
}
};
private Composite chartParentComposite;
private final AbstractHandler updateChartsHandler = new AbstractHandler() {
#Override
public Object execute(
ExecutionEvent ee)
throws ExecutionException {
Map<String, Pair<List<Double>, List<Double>>> applicationContext = (Map<String, Pair<List<Double>, List<Double>>>) ee
.getApplicationContext();
final Pair<List<Double>, List<Double>> costsBestAndMedianVals = applicationContext
.get(org.cloudmig.cloudmigxpress.activity.generation.transformation.ga.Messages.CDOEvaluator_lowCostObjective);
final Pair<List<Double>, List<Double>> responseTimesBestAndMedianVals = applicationContext
.get(org.cloudmig.cloudmigxpress.activity.generation.transformation.ga.Messages.CDOEvaluator_lowResponseTimesObjective);
final Pair<List<Double>, List<Double>> nrTimeoutsBestAndMedianVals = applicationContext
.get(org.cloudmig.cloudmigxpress.activity.generation.transformation.ga.Messages.CDOEvaluator_lowNrSLAViolationsObjective);
Display.getDefault()
.asyncExec(
new Runnable() {
#Override
public void run() {
updateCharts(
costsBestAndMedianVals,
responseTimesBestAndMedianVals,
nrTimeoutsBestAndMedianVals);
}
});
return null;
}
};
/**
* Create the wizard.
*/
public CloudDeploymentOptionsCreationWizardPage3ACO() {
super("wizardPage");
setImageDescriptor(ResourceManager
.getPluginImageDescriptor("org.cloudmig.cloudmigxpress",
"icons/iconfinder_com_1327065738_question-type-one-correct.png"));
setTitle("Compute Best Suited Cloud Deployment Option");
setDescription("Step 3 of 3 - Run the cloud deployment optimization process");
this.optimizationStarted = false;
this.saveBestFoundCDO = true;
this.swtBlackColor = SWTResourceManager.getColor(SWT.COLOR_BLACK);
this.swtGreenColor = SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN);
this.swtRedColor = SWTResourceManager.getColor(SWT.COLOR_RED);
}
I have swt components in my code which I have mentioned here.This is swt gui from where user can select inputs from GUI and perform job.I want to unit test that job and measure performance.But I have no idea how to take input from GUI and give it to jmeter.Or can we bind jmeter code into existing API without writing jmetersmpler.
I have two question in my mind that i want to share with you:
1)Can Jmeter support swt GUI testing?If yes than can you provide simple demo
2)How to implement jmeter in swt GUI with existing code and how to test them.

JMeter cannot test standalone desktop applications out of the box. Normally load testing of the desktop applications is not required as they are used only by single person and if the application reaction time is ok - you don't need to take any extra steps.
However if your application communicates with the backend server - you might want to test the server to check how does it handle the load from multiple concurrent application instances. In that case here are the options:
If application uses HTTP or HTTPS to communicate with the backend server - you can capture the requests via JMeter's HTTP(S) Test Script Recorder and then replay them
If other protocol is being used - you can check available JMeter Samplers and JMeter Plugins to see whether protocol is being supported and use the relevant sampler
There are also options to do some coding via the following Test Elements:
if you have JUnit tests - you can reuse and run them in multithreaded manner via JUnit Request Sampler
there is also possibility to use one of scripting languages which comply with JSR-223 specification like javascript, jexl, beanshell, etc.

Related

imagej image type conversion

I am new to java programing.
I am trying to write a java application using netbeans that uses imagej jar to open a dicom image & process it. I was able to do that using the following java code:
public class user_interface extends java.awt.Frame {
/** Creates new form user_interface */
public user_interface() {
initComponents();
}
private void initComponents() {
btn_open_image = new java.awt.Button();
btn_invert_image = new java.awt.Button();
slbl_display = new javax.swing.JLabel();
setBackground(java.awt.Color.orange);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btn_open_image.setLabel("Open Image");
btn_open_image.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_open_imageMouseClicked(evt);
}
});
btn_open_image.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_open_imageActionPerformed(evt);
}
});
add(btn_open_image, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 80, -1));
btn_invert_image.setLabel("Invert Image");
btn_invert_image.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btn_invert_imageMouseClicked(evt);
}
});
add(btn_invert_image, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 150, 80, -1));
slbl_display.setBackground(new java.awt.Color(51, 51, 51));
add(slbl_display, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, -1, -1));
pack();
}// </editor-fold>
/**
* Exit the Application
*/
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}
private ImagePlus IPL_image;
private ImageJ ImageJ_image;
private ImageJ CovImageJ_image;
private ImageProcessor ip;
private Image AWT_image;
private ImageIcon AWT_icon;
private void btn_open_imageMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String MacroName ="C:\\Program Files\\ImageJ\\macros\\RadFz\\DrawGraticule(Worksfine).txt";
String ImgName = "G:\\PV-QA Images\\01-31-2016\\6MV-FS-OF\\RI\\5x5-6MV-MLC.dcm";
//(01) open image
IPL_image = IJ.openImage(ImgName);
int ImgType = IPL_image.getType();
System.out.println("Image Type = " + ImgType);
//IJ.runMacroFile(MacroName);
//(02) pass it to processor to acess each pixel
// ip.convertToColorProcessor();
ip = IPL_image.getProcessor();
//(03) reset the image window & level
ip.resetMinAndMax();
//get width & height
int imgWdth = ip.getWidth();
int imgHgth = ip.getHeight();
// set line color and width
ip.setColor(Color.red);
ip.setLineWidth(3);
ip.drawLine(0, imgHgth/2, imgWdth, imgHgth/2);
ip.drawLine(imgWdth/2, 0, imgWdth/2, imgHgth);
//IPL_image.show(); // Display image in imagej window
//String IIP = IJ.runMacroFile(MacroName);
//convert image from imagej format to one that you can
//display in image container
AWT_image = ip.createImage();
AWT_icon = new ImageIcon(AWT_image);
slbl_display.setIcon(AWT_icon);
System.out.println("Width = " + imgWdth + " pixels");
System.out.println("Height = " + imgHgth + " pixels");
GetDICOMTagVal("300A,012C");
}
private void btn_invert_imageMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
ip.invert();
AWT_image = ip.createImage();
AWT_icon = new ImageIcon(AWT_image);
slbl_display.setIcon(AWT_icon);
}
private void btn_open_imageActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void GetDICOMTagVal(String DICOMTag) {
String imgInfoStr = IPL_image.getInfoProperty();
//"0002,0003" "300A,012C"
System.out.println("imgInfoStr = \n"+ imgInfoStr );
String InfoLines[];
InfoLines = split(imgInfoStr, "\n");
//System.out.println(" Number of lines = " + InfoLines.length);
int i;
for (i =0; i<InfoLines.length; i++){
//System.out.println(i+" -->" + InfoLines[i].startsWith(DICOMTag));
if(InfoLines[i].startsWith(DICOMTag)) {
String Tag;
Tag = InfoLines[i].substring(DICOMTag.length());
System.out.println(DICOMTag + " = " + Tag);
} else {
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new user_interface().setVisible(true);
}
});
}
// Variables declaration - do not modify
private java.awt.Button btn_invert_image;
private java.awt.Button btn_open_image;
private javax.swing.JLabel slbl_display;
// End of variables declaration
}
I am able to open the image and process it (draw on it) using black lines only. That is because the image is opened as an 8 bit gray image. I am not sure how to convert image to RGB. The convertToRGB() is available in the ij package in the processing folder in the image converter class.
How can I do that?
Indeed as you said, the abstract class ImageProcessor has a method convertToRGB():
public ImageProcessor convertToRGB()
{
if ( type == RGB ) return ip ;
ImageProcessor ip2 = ip.convertToByte(doScaling) ;
return new ColorProcessor(ip2.createImage()) ;
}
It does exactly what you need: convert a ByteProcessor (8 bits) into a ColorProcessor (24 bits).

How to move the graph viewport when adding time-based items to a series at runtime?

I'm trying to create a graph with displays the last n seconds of data arriving by bluetooth. I want to add to the series from within a timer by adding a DataPoint with a Date as X value. All I get is a white screen. I think that the problem lies with the values used in ´graph.getViewport().setMinX`.
What value should I set for minX and maxX if I want to display the last n seconds of data?
public class MainActivity extends ActionBarActivity {
private Handler mHandler;
private GraphView graph;
LineGraphSeries<DataPoint> serFl = new LineGraphSeries<DataPoint>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initGraph();
mHandler = new Handler();
startRepeatingTask();
}
private void initGraph() {
try {
graph = (GraphView) findViewById(R.id.graph);
serFl.setColor(Color.BLUE);
graph.addSeries(serFl);
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(System.currentTimeMillis() - 10000);
graph.getViewport().setMaxX(System.currentTimeMillis() + 1000);
graph.getViewport().setYAxisBoundsManual(true);
graph.getViewport().setMinY(0);
graph.getViewport().setMaxY(20);
final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
graph.getGridLabelRenderer().setLabelFormatter(
new DefaultLabelFormatter() {
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
Date d = new Date((long) value);
return sdf.format(d);
} else {
// show currency for y values
return super.formatLabel(value, isValueX);
}
}
});
} catch (Exception x) {
System.err.println(x);
}
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updateStatus();
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
protected void updateStatus() {
DataMessage msg = source.fetch();
long d = msg.getTimestamp();
serFl.appendData(new DataPoint(d, msg.getFl()), true,
settings.getMaxSeriesSize());
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
}
You did not
graph.onDataChanged(false, false);
after setting the graph.getViewport().setMaxY(20);.
This helped in my case.

Can't get JBox2d Testbed to work

I have followed this tutorial and the testbed launches, but nothing ever happens. The GUI appears but the tests never run, it just sits there. The testbed is launched from the driver class and you add the testbed test. Anyone else have this problem?
Driver Class
public class Driver {
public static final String GRAVITY_SETTING = "Gravity";
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestbedModel model = new TestbedModel(); // create our model
// add tests
model.addCategory("My Tests");
model.addTest(new MJWTest2());
model.addTest(new VerticalStack());
// add our custom setting "My Range Setting", with a default value of 10, between 0 and 20
model.getSettings().addSetting(new TestbedSetting(GRAVITY_SETTING, SettingType.ENGINE, false));
TestbedPanel panel = new TestPanelJ2D(model); // create our testbed panel
JFrame testbed = new TestbedFrame(model, panel, null); // put both into our testbed frame
// etc
testbed.setVisible(true);
testbed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Testbed Test class
public class MJWTest2 extends TestbedTest {
public static final String GRAVITY_SETTING = "Gravity";
#Override
public void initTest(boolean argDeserialized) {
setTitle("Couple of Things Test");
getWorld().setGravity(new Vec2());
for (int i = 0; i < 2; i++) {
PolygonShape polygonShape = new PolygonShape();
polygonShape.setAsBox(1, 1);
FixtureDef fix = new FixtureDef();
fix.shape = polygonShape;
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(5 * i, 0);
bodyDef.angle = (float) (Math.PI / 4 * i);
bodyDef.allowSleep = false;
Body body = getWorld().createBody(bodyDef);
body.createFixture(fix);
body.applyForce(new Vec2(-10000 * (i - 1), 0), new Vec2());
}
}
#Override
public void step(TestbedSettings settings) {
super.step(settings); // make sure we update the engine!
TestbedSetting gravity = settings.getSetting(GRAVITY_SETTING); // grab our setting
if (gravity.enabled) {
getWorld().setGravity(new Vec2(0, -9));
}
else {
getWorld().setGravity(new Vec2());
}
}
#Override
public String getTestName() {
return "Couple of Things";
}
}
There was an updated to the engine w/o an update to the wiki. Whoops! sorry. You need to create a controller and start is, as shown here:
https://github.com/dmurph/jbox2d/blob/master/jbox2d-testbed/src/main/java/org/jbox2d/testbed/framework/j2d/TestbedMain.java
Try this
public class MJWTest2 extends TestbedTest {
#Override
public void initTest(boolean argDeserialized) {
setTitle("Couple of Things Test");
getWorld().setGravity(new Vec2());
for (int i = 0; i < 2; i++)
{
// CircleShape circleShape = new CircleShape();
// circleShape.m_radius = 1;
// Shape shape = circleShape;
PolygonShape polygonShape = new PolygonShape();
polygonShape.setAsBox(1, 1);
Shape shape = polygonShape;
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(5 * i, 0);
bodyDef.angle = (float) (Math.PI / 4 * i);
bodyDef.allowSleep = false;
Body body = getWorld().createBody(bodyDef);
body.createFixture(shape, 5.0f);
body.applyForce(new Vec2(-10000 * (i - 1), 0), new Vec2());
}
}
/**
* #see org.jbox2d.testbed.framework.TestbedTest#getTestName()
*/
#Override
public String getTestName() {
return "Couple of Things";
}
}
And so called 'driver class'
public class App2 {
public static final String GRAVITY_SETTING = "Gravity";
public static void main(String[] args) {
// TODO Auto-generated method stub
TestbedModel model = new TestbedModel(); // create our model
// add tests
model.addCategory("My Tests");
model.addTest(new MJWTest2());
model.addTest(new VerticalStack());
// add our custom setting "My Range Setting", with a default value of 10, between 0 and 20
model.getSettings().addSetting(new TestbedSetting(GRAVITY_SETTING, SettingType.ENGINE, false));
TestbedPanel panel = new TestPanelJ2D(model); // create our testbed panel
JFrame testbed = new TestbedFrame(model, panel); // put both into our testbed frame
// etc
testbed.setVisible(true);
testbed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
worked fine for me.. hope that it works for you as well..

Android, ListView adapter

I have some question regarding Android programming. More specific, I have a ListView where every single row is containg five widgets and each trigger event. I have created custom adapter and defined events handler for every widgets in the getView method. Everything works fine, however the code looks quite long, unreadable and nasty because of all these event handlers inside. Is there any better design? Maybe Creating event handlers outside the getView method or something else?
greetings
According to suggestion I posted part of the source code. As you can see I have created few event handlers outside the getView method and two inside. I really do not know which design is better.
public class ListViewAdapter extends ArrayAdapter<HourReport> {
private static Activity context;
private int resourcecId;
private TextView fromTime;
private TextView toTime;
private TextView total;
private HourReport rowModelBean;
private HourReport rowBean;
private CheckBox billable;
private ArrayList<HourReport> list;
private HourReportCatalog catalog;
private Map<Integer, Integer>selectedItems;
private Map<Integer, Integer>selectedRoles;
public ListViewAdapter(Activity context, int resourcecId,
ArrayList<HourReport> list, HourReportCatalog catalog) {
super(context, resourcecId, list);
this.catalog = catalog;
ListViewAdapter.context = context;
this.resourcecId = resourcecId;
this.list = list;
selectedItems = new HashMap<Integer, Integer>();
selectedRoles = new HashMap<Integer, Integer>();
}
// event handler for delete button "-"
private OnClickListener delete = new OnClickListener() {
#Override
public void onClick(View deletBtnF) {
int myPosition = (Integer) deletBtnF.getTag();
HourReport r = list.remove(myPosition);
selectedItems.put(myPosition, 0);
selectedRoles.put(myPosition, 0);
r.setTimeFinished(null);
r.setTimeStarted(null);
r.setTaks(null);
r.setTotal(0.0);
r.setBillable(false);
r.setEngagementContractID(0);
list.add(myPosition, r);
notifyDataSetChanged();
if (r.getDateCreated() != null) {
Log.e("Listview adapter", "inside the if statement");
Long id = r.getHourReportID();
Log.e("", "date created" + r.getDateCreated());
catalog.deleteHourReport(r);
r.setDateCreated(null);
}
}
};
// event handler for textView which is responsible for defining dateFrom
Calendar c = Calendar.getInstance();
OnClickListener onClickLisOnDateFrom = new OnClickListener() {
#Override
public void onClick(View editField) {
Integer position1 = (Integer) editField.getTag();
TableRow parent = (TableRow) editField.getParent();
fromTime = (TextView) parent.findViewById(R.id.viewTextFrom);
total = (TextView) parent.findViewById(R.id.textViewShowsTotal);
rowBean = getModel(position1);
TimePickerDialog.OnTimeSetListener timeListener1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
String time = hour + ":" + minutes;
fromTime.setText(time);
setTimeFieldFrom(time);
String totalTime = totalHourCalculator();
total.setText(totalTime);
}
};
new TimePickerDialog(context, timeListener1,
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true)
.show();
}
};
// event handler for textView which is responsible for defining dateTo
private OnClickListener onClickLisOnDateTo = new OnClickListener() {
#Override
public void onClick(View editField) {
Integer position1 = (Integer) editField.getTag();
Log.e("ListView - Timer ", "position: " + position1);
TableRow parent = (TableRow) editField.getParent();
toTime = (TextView) parent.findViewById(R.id.viewTextFrom);
total = (TextView) parent.findViewById(R.id.textViewShowsTotal);
rowBean = getModel(position1);
TimePickerDialog.OnTimeSetListener timeListener2 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
String time = hour + ":" + minutes;
toTime.setText(time);
setTimeFieldTo(time);
String totalTime = totalHourCalculator();
total.setText(totalTime);
}
};
new TimePickerDialog(context, timeListener2,
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true)
.show();
}
};
// event handler for check box
private OnClickListener checkBoxListener = new OnClickListener() {
#Override
public void onClick(View checkBox) {
Integer num = (Integer) checkBox.getTag();
rowBean = getModel(num);
if (rowBean.isBillable()) {
rowBean.setBillable(false);
} else {
rowBean.setBillable(true);
}
}
};
#Override
public View getView( int position, View convertView, ViewGroup parent) {
getHourReportList();
TextView deleteBtnV = null;
View row = convertView;
Spinner taskSpinner, roleSpinner;
TextView addReport;
final ViewHolder viewHolder;
if (row == null) {
LayoutInflater layoutInflater = context.getLayoutInflater();
row = layoutInflater.inflate(resourcecId, parent, false);
viewHolder = new ViewHolder(row);
fromTime = viewHolder.getFromTime();
deleteBtnV = viewHolder.getDeleteBtnVView();
deleteBtnV.setOnClickListener(delete);
billable = viewHolder.getCheckBox();
addReport = viewHolder.getAddButtonView();
// event handler for the button "+" which adds extra row
addReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Integer myPosition = (Integer) view.getTag();
HourReport report = list.get(myPosition);
HourReport nReport = new HourReport();
nReport.setClaimDate(report.getClaimDate());
nReport.setEmployeeID(report.getEmployeeID());
nReport.setBillable(false);
nReport.setEngagementContractID(0);
list.add(myPosition + 1, nReport);
notifyDataSetChanged();
}
});
viewHolder.adapter = new SpinerAdapter(context);
taskSpinner = viewHolder.getSpinnerTask();
roleSpinner = viewHolder.getSpinnerRole();
//event handler for the spinner
taskSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View spin,
int selected, long arg3) {
Spinner spinner = (Spinner) spin.getParent();
Integer myPosition = (Integer) spinner.getTag();
viewHolder.adapter.setSelected(selected);
String task = viewHolder.adapter.getSelectcetdTask();
long engmId = viewHolder.adapter.getSelectedTaskID();
rowBean = getModel(myPosition);
rowBean.setTaks(task);
rowBean.setEngagementContractID(engmId);
selectedItems.put(myPosition, selected);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
////event handler for the spinner
roleSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View spin,
int selectedRole, long arg3) {
Spinner spinner = (Spinner) spin.getParent();
Integer myPosition = (Integer) spinner.getTag();
selectedRoles.put(myPosition, selectedRole);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
fromTime = viewHolder.getFromTime();
toTime = viewHolder.getToTime();
fromTime.setOnClickListener(onClickLisOnDateFrom);
toTime.setOnClickListener(onClickLisOnDateTo);
billable.setOnClickListener(checkBoxListener);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
fromTime = viewHolder.getFromTime();
toTime = viewHolder.getToTime();
taskSpinner = viewHolder.getSpinnerTask();
roleSpinner = viewHolder.getSpinnerRole();
total = viewHolder.getTotal();
billable = viewHolder.getCheckBox();
TextView date = viewHolder.getDate();
deleteBtnV = viewHolder.getDeleteBtnVView();
addReport = viewHolder.getAddButtonView();
}
HourReport model = getModel(position);
Integer selection = 0;
if (selectedItems.get(position) != null) {
selection = selectedItems.get(position);
}
int selectionR = 0;
if (selectedRoles.get(position) != null) {
selectionR = selectedRoles.get(position);
}
viewHolder.getFromTime().setText(
parseDateToString(model.getTimeStarted()));
viewHolder.getToTime().setText(
parseDateToString(model.getTimeFinished()));
viewHolder.getTotal().setText(
convertDoubleTotToStringTot(model.getTotal()));
viewHolder.getDate().setText(
parseDateToStringDDate(model.getClaimDate()));
viewHolder.getCheckBox().setChecked(model.isBillable());
Log.e("", "tag " + selection + " date " + model.getClaimDate());
viewHolder.taskSpinner.setSelection(selection);
viewHolder.roleSpinner.setSelection(selectionR);
fromTime.setTag(Integer.valueOf(position));
toTime.setTag(Integer.valueOf(position));
taskSpinner.setTag(Integer.valueOf(position));
roleSpinner.setTag(Integer.valueOf(position));
billable.setTag(Integer.valueOf(position));
deleteBtnV.setTag(Integer.valueOf(position));
addReport.setTag(Integer.valueOf(position));
return row;
}![here you have screen shoot of single row][1]
Create a single instance of OnClickListener (for example as an inner class) and assign this instance to every widget. If you need to know which row this widget belongs to, you can call setTag("pos", position) on that widget. By doing this you will be able to get position by calling view.getTag("pos") in onClick(View view) method of the listener. Hope this helps.

How can I get the column number in a SWT table in Eclipse RCP?

My question is How can we find the currently selected column number in the selected row of a SWT Table in Eclipse RCP?
Inside a Listener - e.g. for SWT.Selection - you can use viewer.getCell(...) as illustrated in the following example:
myTableViewer.getTable().addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
Point p = new Point(event.x, event.y);
ViewerCell cell = myTableViewer.getCell(p);
int columnIndex = cell.getColumnIndex();
//...
}
});
If you want to be sure that the columnindex is updated prior to calling the selectionlistener, then the mousedown event will also work fine:
table.addMouseListener( new MouseAdapter() {
private static final long serialVersionUID = 1L;
#Override
public void mouseDown(MouseEvent event) {
try {
Point p = new Point(event.x, event.y);
ViewerCell cell = viewer.getCell(p);
selectedColumn = cell.getColumnIndex();
} catch (Exception e) {
e.printStackTrace();
}
}
});