Can't get JBox2d Testbed to work - jbox2d

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..

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 test swt wizard GUI with jmeter

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.

Creating custom plugin for chinese tokenization

I'm working towards properly integrating the stanford segmenter within SOLR for chinese tokenization.
This plugin involves loading other jar files and model files. I've got it working in a crude manner by hardcoding the complete path for the files.
I'm looking for methods to create the plugin where the paths need not be hardcoded and also to have the plugin in conformance with the SOLR plugin architecture. Please let me know if there are any recommended sites or tutorials for this.
I've added my code below :
public class ChineseTokenizerFactory extends TokenizerFactory {
/** Creates a new WhitespaceTokenizerFactory */
public ChineseTokenizerFactory(Map<String,String> args) {
super(args);
assureMatchVersion();
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
#Override
public ChineseTokenizer create(AttributeFactory factory, Reader input) {
Reader processedStringReader = new ProcessedStringReader(input);
return new ChineseTokenizer(luceneMatchVersion, factory, processedStringReader);
}
}
public class ProcessedStringReader extends java.io.Reader {
private static final int BUFFER_SIZE = 1024 * 8;
//private static TextProcess m_textProcess = null;
private static final String basedir = "/home/praveen/PDS_Meetup/solr-4.9.0/custom_plugins/";
static Properties props = null;
static CRFClassifier<CoreLabel> segmenter = null;
private char[] m_inputData = null;
private int m_offset = 0;
private int m_length = 0;
public ProcessedStringReader(Reader input){
char[] arr = new char[BUFFER_SIZE];
StringBuffer buf = new StringBuffer();
int numChars;
if(segmenter == null)
{
segmenter = new CRFClassifier<CoreLabel>(getProperties());
segmenter.loadClassifierNoExceptions(basedir + "ctb.gz", getProperties());
}
try {
while ((numChars = input.read(arr, 0, arr.length)) > 0) {
buf.append(arr, 0, numChars);
}
} catch (IOException e) {
e.printStackTrace();
}
m_inputData = processText(buf.toString()).toCharArray();
m_offset = 0;
m_length = m_inputData.length;
}
#Override
public int read(char[] cbuf, int off, int len) throws IOException {
int charNumber = 0;
for(int i = m_offset + off;i<m_length && charNumber< len; i++){
cbuf[charNumber] = m_inputData[i];
m_offset ++;
charNumber++;
}
if(charNumber == 0){
return -1;
}
return charNumber;
}
#Override
public void close() throws IOException {
m_inputData = null;
m_offset = 0;
m_length = 0;
}
public String processText(String inputText)
{
List<String> segmented = segmenter.segmentString(inputText);
String output = "";
if(segmented.size() > 0)
{
output = segmented.get(0);
for(int i=1;i<segmented.size();i++)
{
output = output + " " +segmented.get(i);
}
}
System.out.println(output);
return output;
}
static Properties getProperties()
{
if (props == null) {
props = new Properties();
props.setProperty("sighanCorporaDict", basedir);
// props.setProperty("NormalizationTable", "data/norm.simp.utf8");
// props.setProperty("normTableEncoding", "UTF-8");
// below is needed because CTBSegDocumentIteratorFactory accesses it
props.setProperty("serDictionary",basedir+"dict-chris6.ser.gz");
props.setProperty("inputEncoding", "UTF-8");
props.setProperty("sighanPostProcessing", "true");
}
return props;
}
}
public final class ChineseTokenizer extends CharTokenizer {
public ChineseTokenizer(Version matchVersion, Reader in) {
super(matchVersion, in);
}
public ChineseTokenizer(Version matchVersion, AttributeFactory factory, Reader in) {
super(matchVersion, factory, in);
}
/** Collects only characters which do not satisfy
* {#link Character#isWhitespace(int)}.*/
#Override
protected boolean isTokenChar(int c) {
return !Character.isWhitespace(c);
}
}
You can pass the argument through the Factory's args parameter.

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.

Problem with GWT connector in a straight ended connection

I am trying to make a straight ended connection between widgets.But when I am doing so, the orientation of my connector is coming wrong.Its always coming parallel to the required one.Also , it is independent of the connecting widgets i.e when I move my widget, my connector does not move.Snippet of my code is given as :
Link to snapshot of the problem: http://goo.gl/JUEmJ
public class DragNDropPage {
SyncCurrentUser cu = SyncCurrentUser.getUser();
private AbsolutePanel area = new AbsolutePanel();
HorizontalPanel toolsPanel = new HorizontalPanel();
AbsolutePanel canvas = new AbsolutePanel();
DragController toolboxDragController;
Label startLabel = new Label("START");
Label stopLabel = new Label("STOP");
Label activityLabel = new Label("ACTIVITY");
Label processLabel = new Label("PROCESS");
Button stopDrag = new Button("Done Dragging");
Button saveButton = new Button("Save");
PickupDragController dragController = new PickupDragController(area, true);
AbsolutePositionDropController dropController = new AbsolutePositionDropController(area);
private List<Widget> selected = new ArrayList<Widget>();
private List<Widget> onCanvas = new ArrayList<Widget>();
private List<Connection> connections = new ArrayList<Connection>();
private CActivity[] aItems;
private CProcess[] pItems;
MyHandler handler = new MyHandler();
int mouseX,mouseY;
String style;
public DragNDropPage() {
toolboxDragController = new ToolboxDragController(dropController, dragController);
RootPanel.get("rightbar").add(area);
area.setSize("575px", "461px");
area.add(toolsPanel);
toolsPanel.setSize("575px", "37px");
toolsPanel.add(startLabel);
startLabel.setSize("76px", "37px");
toolboxDragController.makeDraggable(startLabel);
toolsPanel.add(stopLabel);
stopLabel.setSize("66px", "37px");
toolboxDragController.makeDraggable(stopLabel);
toolsPanel.add(activityLabel);
activityLabel.setSize("82px", "36px");
toolboxDragController.makeDraggable(activityLabel);
toolsPanel.add(processLabel);
processLabel.setSize("85px", "36px");
toolboxDragController.makeDraggable(processLabel);
stopDrag.addClickHandler(handler);
toolsPanel.add(stopDrag);
stopDrag.setWidth("114px");
saveButton.addClickHandler(handler);
toolsPanel.add(saveButton);
area.add(canvas, 0, 36);
canvas.setSize("575px", "425px");
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
//46 is the key code for Delete Button
if(event.getNativeEvent().getKeyCode() == 46 && !selected.isEmpty()) {
for (Iterator<Widget> i = selected.listIterator(); i.hasNext();) {
Widget w = (Widget) i.next();
UIObjectConnector.unwrap(w);
i.remove();
w.removeFromParent();
onCanvas.remove(i);
}
}
}
});
aItems = cu.currentUser.getcActivity();
pItems = cu.currentUser.getcProcess();
}
private class ToolboxDragController extends PickupDragController {
public ToolboxDragController(final DropController dropController, final DragController nodesDragController) {
super(area ,false);
setBehaviorDragProxy(true);
registerDropController(dropController);
addDragHandler(new DragHandlerAdapter(){
public void onPreviewDragEnd(DragEndEvent event) throws VetoDragException {
Widget node = (Widget) event.getSource();
int left = event.getContext().desiredDraggableX;
int top = event.getContext().desiredDraggableY;
AbsolutePanel panel = (AbsolutePanel) dropController.getDropTarget();
createConnector((Label) node, panel, left, top);
throw new VetoDragException();
}
});
}
}
protected UIObjectConnector createConnector(Label proxy, AbsolutePanel panel, int left, int top) {
Widget w;
String str = proxy.getText();
if(str.equals("START") || str.equals("STOP")){
w = new Label(proxy.getText()){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
w.getElement().setClassName("dnd-start-stop");
}
else{
w = new ListBox(){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
if(str.equals("ACTIVITY")){
getAItems((ListBox)w);
//w.getElement().addClassName("dnd-activity");
}
else if(str.equals("PROCESS")){
getPItems((ListBox)w);
//w.getElement().addClassName("dnd-process");
}
}
onCanvas.add(w);
left -= panel.getAbsoluteLeft();
top -= panel.getAbsoluteTop();
//panel.add(w,10,10);
panel.add(w, left, top);
dragController.makeDraggable(w);
return UIObjectConnector.wrap(w);
}
private void getAItems(ListBox w) {
for(int i=0;i<aItems.length;i++)
w.addItem(aItems[i].getActivityName());
}
private void getPItems(ListBox w) {
/*for(int i=0;i<pItems.length;i++)
w.addItem(pItems[i].getProcessName());*/
w.addItem("Process1");
}
protected void select(Widget w){
if(selected.isEmpty()) {
selected.add(w);
w.getElement().addClassName("color-green");
} else if(selected.contains(w)){
selected.remove(w);
w.getElement().removeClassName("color-green");
} else if(selected.size() == 1) {
Widget w2 = (Widget) selected.get(0);
connect(UIObjectConnector.getWrapper(w2), UIObjectConnector.getWrapper(w));
selected.clear();
}
}
protected void connect(Connector a, Connector b) {
//System.out.println(a.getLeft());
//System.out.println(b.getLeft());
add(new StraightTwoEndedConnection(a,b));
}
private void add(StraightTwoEndedConnection c) {
canvas.add(c);
connections.add(c);
c.update();
}
protected void remove(Connection c) {
connections.remove(c);
}
class MyHandler implements ClickHandler{
#Override
public void onClick(ClickEvent event) {
Button name = (Button) event.getSource();
if(name.equals(stopDrag)){
if(name.getText().equals("Done Dragging")){
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeNotDraggable(w);
}
name.setText("Continue");
}
else {
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeDraggable(w);
}
name.setText("Done Dragging");
}
}
else{
}
}
}
}
I know this is quite old, but I was having similar issues with the gwt-connector library.
The connectors will not appear in the correct placement if you are using standards mode. Use quirks mode instead.
Additionally, you need to manually perform a connector.update() while your dnd components are being dragged (in your drag listener) for the connection to move with the endpoint while you are dragging.