How can opencv image processing run faster? - android-studio

I am working on android studio with OpenCV library. I am dealing with ColorBlobDetectionActivity class so I want to rearrenge its processing. OpenCV processes all screen but I want to process just particular region to make it faster on android camera.Can someone help me?
Here it is ColorBlobDetectionActivity Class Code:
private boolean mIsColorSelected = false;
private Mat mRgba;
private Scalar mBlobColorRgba;
private Scalar mBlobColorHsv;
private ColorBlobDetector mDetector;
private Mat mSpectrum;
private Size SPECTRUM_SIZE;
private Scalar CONTOUR_COLOR;
private CameraBridgeViewBase mOpenCvCameraView;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
mOpenCvCameraView.setOnTouchListener(ColorBlobDetectionActivity.this);
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public ColorBlobDetectionActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.color_blob_detection_surface_view);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.color_blob_detection_activity_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
#Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
mDetector = new ColorBlobDetector();
mSpectrum = new Mat();
mBlobColorRgba = new Scalar(255);
mBlobColorHsv = new Scalar(255);
SPECTRUM_SIZE = new Size(200, 64);
CONTOUR_COLOR = new Scalar(255,0,0,255);
}
public void onCameraViewStopped() {
mRgba.release();
}
public boolean onTouch(View v, MotionEvent event) {
int cols = mRgba.cols();
int rows = mRgba.rows();
int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;
int x = (int)event.getX() - xOffset;
int y = (int)event.getY() - yOffset;
Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");
if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;
Rect touchedRect = new Rect();
touchedRect.x = (x>4) ? x-4 : 0;
touchedRect.y = (y>4) ? y-4 : 0;
touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;
Mat touchedRegionRgba = mRgba.submat(touchedRect);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
// Calculate average color of touched region
mBlobColorHsv = Core.sumElems(touchedRegionHsv);
int pointCount = touchedRect.width*touchedRect.height;
for (int i = 0; i < mBlobColorHsv.val.length; i++)
mBlobColorHsv.val[i] /= pointCount;
mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);
Log.i(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");
mDetector.setHsvColor(mBlobColorHsv);
Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);
mIsColorSelected = true;
touchedRegionRgba.release();
touchedRegionHsv.release();
return false; // don't need subsequent touch events
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
if (mIsColorSelected) {
mDetector.process(mRgba);
List<MatOfPoint> contours = mDetector.getContours();
Log.e(TAG, "Contours count: " + contours.size());
Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);
Mat colorLabel = mRgba.submat(4, 68, 4, 68);
colorLabel.setTo(mBlobColorRgba);
Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
mSpectrum.copyTo(spectrumLabel);
}
return mRgba;
}
private Scalar converScalarHsv2Rgba(Scalar hsvColor) {
Mat pointMatRgba = new Mat();
Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);
return new Scalar(pointMatRgba.get(0, 0));
}
}

Related

Recycle View Inside Of Fragment Not Calling OnViewCreate

So basically, it's as the title says. I'm implementing a recycle view inside a fragment to create a map on one part of the screen. I need two recycle views on the page but only one isn't working. When I run the debugger in Android Studio it never reaches the override methods in the Adapter class. Below is the code, unfortunately it's a lot.
I should also mention
Number of items is caclulated and is not zero
Adapter is added to recycler view
Layout manager is added to recycler view
Why aren't any of the overriden methods being called?
Please let me know if you require further information
FRAGMENT
public class FragmentMap extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
MapData mapData;
StructureData structures;
public FragmentMap(MapData mapData, StructureData structures)
{
this.mapData = mapData;
this.structures = structures;
}
public FragmentMap() {
// Required empty public constructor
}
public static FragmentMap newInstance(String param1, String param2) {
FragmentMap fragment = new FragmentMap();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
RecyclerView rv = view.findViewById(R.id.mapRecyclerView);
SelectorAdapter myAdapter = new SelectorAdapter(structures);
MapAdapter mapAdapter = new MapAdapter(mapData);
rv.setAdapter(mapAdapter);
rv.setLayoutManager(new GridLayoutManager(
getActivity(),
MapData.HEIGHT,
GridLayoutManager.HORIZONTAL,
false));
return view;
}
}
ADAPTER
public class MapAdapter extends RecyclerView.Adapter<MapViewHolder>{
MapData mapData;
public MapAdapter(MapData mapData)
{
this.mapData = mapData;
}
#NonNull
#Override
public MapViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.grid_cell,parent,false);
MapViewHolder myViewHolder = new MapViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MapViewHolder holder, int position) {
int row = position % MapData.HEIGHT;
int col = position / MapData.HEIGHT;
MapElement mapElement = mapData.get(row, col);
holder.cellOne.setImageResource(mapElement.getNorthEast());
}
#Override
public int getItemCount() {
Log.d("TAG", "getItemCount: " + MapData.HEIGHT * MapData.WIDTH);
return MapData.HEIGHT * MapData.WIDTH;
}
}
VIEWHOLDER
public class MapViewHolder extends RecyclerView.ViewHolder {
ImageView cellOne, cellTwo, cellThree, cellFour, structure;
ConstraintLayout parent;
public MapViewHolder(#NonNull View itemView) {
super(itemView);
cellOne = itemView.findViewById(R.id.imageOne);
cellTwo = itemView.findViewById(R.id.imageTwo);
cellThree = itemView.findViewById(R.id.imageThree);
cellFour = itemView.findViewById(R.id.imageFour);
parent = itemView.findViewById(R.id.parent);
int size = parent.getMeasuredHeight() / MapData.HEIGHT + 1;
ViewGroup.LayoutParams lp = itemView.getLayoutParams();
lp.width = size;
lp.height = size;
}
}
MAPDATA
public class MapData
{
public static final int WIDTH = 30;
public static final int HEIGHT = 10;
private static final int WATER = R.drawable.ic_water;
private static final int[] GRASS = {R.drawable.ic_grass1, R.drawable.ic_grass2,
R.drawable.ic_grass3, R.drawable.ic_grass4};
private static final Random rng = new Random();
private MapElement[][] grid;
private static MapData instance = null;
public static MapData get()
{
if(instance == null)
{
instance = new MapData(generateGrid());
}
return instance;
}
private static MapElement[][] generateGrid()
{
final int HEIGHT_RANGE = 256;
final int WATER_LEVEL = 112;
final int INLAND_BIAS = 24;
final int AREA_SIZE = 1;
final int SMOOTHING_ITERATIONS = 2;
int[][] heightField = new int[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
heightField[i][j] =
rng.nextInt(HEIGHT_RANGE)
+ INLAND_BIAS * (
Math.min(Math.min(i, j), Math.min(HEIGHT - i - 1, WIDTH - j - 1)) -
Math.min(HEIGHT, WIDTH) / 4);
}
}
int[][] newHf = new int[HEIGHT][WIDTH];
for(int s = 0; s < SMOOTHING_ITERATIONS; s++)
{
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
int areaSize = 0;
int heightSum = 0;
for(int areaI = Math.max(0, i - AREA_SIZE);
areaI < Math.min(HEIGHT, i + AREA_SIZE + 1);
areaI++)
{
for(int areaJ = Math.max(0, j - AREA_SIZE);
areaJ < Math.min(WIDTH, j + AREA_SIZE + 1);
areaJ++)
{
areaSize++;
heightSum += heightField[areaI][areaJ];
}
}
newHf[i][j] = heightSum / areaSize;
}
}
int[][] tmpHf = heightField;
heightField = newHf;
newHf = tmpHf;
}
MapElement[][] grid = new MapElement[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
MapElement element;
if(heightField[i][j] >= WATER_LEVEL)
{
boolean waterN = (i == 0) || (heightField[i - 1][j] < WATER_LEVEL);
boolean waterE = (j == WIDTH - 1) || (heightField[i][j + 1] < WATER_LEVEL);
boolean waterS = (i == HEIGHT - 1) || (heightField[i + 1][j] < WATER_LEVEL);
boolean waterW = (j == 0) || (heightField[i][j - 1] < WATER_LEVEL);
boolean waterNW = (i == 0) || (j == 0) || (heightField[i - 1][j - 1] < WATER_LEVEL);
boolean waterNE = (i == 0) || (j == WIDTH - 1) || (heightField[i - 1][j + 1] < WATER_LEVEL);
boolean waterSW = (i == HEIGHT - 1) || (j == 0) || (heightField[i + 1][j - 1] < WATER_LEVEL);
boolean waterSE = (i == HEIGHT - 1) || (j == WIDTH - 1) || (heightField[i + 1][j + 1] < WATER_LEVEL);
boolean coast = waterN || waterE || waterS || waterW ||
waterNW || waterNE || waterSW || waterSE;
grid[i][j] = new MapElement(
!coast,
choose(waterN, waterW, waterNW,
R.drawable.ic_coast_north, R.drawable.ic_coast_west,
R.drawable.ic_coast_northwest, R.drawable.ic_coast_northwest_concave),
choose(waterN, waterE, waterNE,
R.drawable.ic_coast_north, R.drawable.ic_coast_east,
R.drawable.ic_coast_northeast, R.drawable.ic_coast_northeast_concave),
choose(waterS, waterW, waterSW,
R.drawable.ic_coast_south, R.drawable.ic_coast_west,
R.drawable.ic_coast_southwest, R.drawable.ic_coast_southwest_concave),
choose(waterS, waterE, waterSE,
R.drawable.ic_coast_south, R.drawable.ic_coast_east,
R.drawable.ic_coast_southeast, R.drawable.ic_coast_southeast_concave),
null);
}
else
{
grid[i][j] = new MapElement(
false, WATER, WATER, WATER, WATER, null);
}
}
}
return grid;
}
private static int choose(boolean nsWater, boolean ewWater, boolean diagWater,
int nsCoastId, int ewCoastId, int convexCoastId, int concaveCoastId)
{
int id;
if(nsWater)
{
if(ewWater)
{
id = convexCoastId;
}
else
{
id = nsCoastId;
}
}
else
{
if(ewWater)
{
id = ewCoastId;
}
else if(diagWater)
{
id = concaveCoastId;
}
else
{
id = GRASS[rng.nextInt(GRASS.length)];
}
}
return id;
}
protected MapData(MapElement[][] grid)
{
this.grid = grid;
}
public void regenerate()
{
this.grid = generateGrid();
}
public MapElement get(int i, int j)
{
return grid[i][j];
}
}
MAP ELEMENT
public class MapElement
{
private final boolean buildable;
private final int terrainNorthWest;
private final int terrainSouthWest;
private final int terrainNorthEast;
private final int terrainSouthEast;
private Structure structure;
public MapElement(boolean buildable, int northWest, int northEast,
int southWest, int southEast, Structure structure)
{
this.buildable = buildable;
this.terrainNorthWest = northWest;
this.terrainNorthEast = northEast;
this.terrainSouthWest = southWest;
this.terrainSouthEast = southEast;
this.structure = structure;
}
public boolean isBuildable()
{
return buildable;
}
public int getNorthWest()
{
return terrainNorthWest;
}
public int getSouthWest()
{
return terrainSouthWest;
}
public int getNorthEast()
{
return terrainNorthEast;
}
public int getSouthEast()
{
return terrainSouthEast;
}
/**
* Retrieves the structure built on this map element.
* #return The structure, or null if one is not present.
*/
public Structure getStructure()
{
return structure;
}
public void setStructure(Structure structure)
{
this.structure = structure;
}
}
You are initializing only one RecyclerView in onCreateView, if you want to have two Recyclerviews you just need to initialize second one in the same way.

Issues with runaway thread

I'm pretty new to android studio. I noticed that my program had a very severe performance hiccup and I believe it is slowing down after I run the app every time. I think I have a runaway thread and I will attach pictures at the end of my post. I could really use some help. The first picture shows an example of the thread and then the second picture shows the thread after 5 minutes or so of waiting. I attached two codes. CameraSurfaceView runs the code while FaceDetectionThread creates the thread.
package com.example.phliip_vision;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import com.example.phliip_vision.Point;
import com.example.phliip_vision.MeasurementStepMessage;
import com.example.phliip_vision.MessageHUB;
import com.example.phliip_vision.Util;
public class CameraSurfaceView extends SurfaceView implements Callback,
Camera.PreviewCallback {
public static final int CALIBRATION_DISTANCE_A4_MM = 294;
public static final int CALIBRATION_MEASUREMENTS = 10;
public static final int AVERAGE_THREASHHOLD = 5;
private static final String TAG = "CameraSurfaceView";
/**
* Measured distance at calibration point
*/
private float _distanceAtCalibrationPoint = -1;
private float _currentAvgEyeDistance = -1;
// private int _facesFoundInMeasurement = -1;
/**
* in cm
*/
private float _currentDistanceToFace = -1;
private final SurfaceHolder mHolder;
private Camera mCamera;
private Face _foundFace = null;
private int _threashold = CALIBRATION_MEASUREMENTS;
private FaceDetectionThread _currentFaceDetectionThread;
private List<Point> _points;
protected final Paint _middlePointColor = new Paint();
protected final Paint _eyeColor = new Paint();
private Size _previewSize;
// private boolean _measurementStartet = false;
private boolean _calibrated = false;
private boolean _calibrating = false;
private int _calibrationsLeft = -1;
public CameraSurfaceView(final Context context, final AttributeSet attrs) {
super(context, attrs);
_middlePointColor.setARGB(100, 200, 0, 0);
_middlePointColor.setStyle(Paint.Style.FILL);
_middlePointColor.setStrokeWidth(2);
_eyeColor.setColor(Color.GREEN);
mHolder = getHolder();
mHolder.addCallback(this);
}
public void setCamera(final Camera camera) {
mCamera = camera;
if (mCamera != null) {
requestLayout();
Log.d(TAG, "mCamera RANNNNNNN!!!!");
Camera.Parameters params = mCamera.getParameters();
camera.setDisplayOrientation(90);
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
Log.d(TAG, "FOCUS_MODE_AUTO RANNNNNNN!!!!");
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
}
}
}
/**
* Variables for the onDraw method, in order to prevent variable allocation
* to slow down the sometimes heavily called onDraw method
*/
private final PointF _middlePoint = new PointF();
private final Rect _trackingRectangle = new Rect();
private final static int RECTANGLE_SIZE = 20;
private boolean _showEyes = false;
private boolean _showTracking = true;
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(final Canvas canvas) {
// super.onDraw(canvas);
if (_foundFace != null) {
_foundFace.getMidPoint(_middlePoint);
Log.d(TAG, "_middlePoint RANNNNNNN!!!!");
Log.i("Camera", _middlePoint.x + " : " + _middlePoint.y);
// portrait mode!
float heightRatio = getHeight() / (float) _previewSize.width;
float widthRatio = getWidth() / (float) _previewSize.height;
Log.i("Drawcall", _middlePoint.x + " : " + _middlePoint.y);
int realX = (int) (_middlePoint.x * widthRatio);
int realY = (int) (_middlePoint.y * heightRatio);
Log.i("Drawcall", "Real :" + realX + " : " + realY);
int halfEyeDist = (int) (widthRatio * _foundFace.eyesDistance() / 2);
if (_showTracking) {
// Middle point
Log.d(TAG, "_showTracking RANNNNNNN!!!!");
_trackingRectangle.left = realX - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _middlePointColor);
}
if (_showEyes) {
// Left eye
Log.d(TAG, "_showEyes RANNNNNNN!!!!");
_trackingRectangle.left = realX - halfEyeDist - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX - halfEyeDist + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _eyeColor);
// Right eye
_trackingRectangle.left = realX + halfEyeDist - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX + halfEyeDist + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _eyeColor);
}
}
}
public void reset() {
Log.d(TAG, "reset RANNNNNNN!!!!");
_distanceAtCalibrationPoint = -1;
_currentAvgEyeDistance = -1;
_calibrated = false;
_calibrating = false;
_calibrationsLeft = -1;
}
/**
* Sets this current EYE distance to be the distance of a peace of a4 paper
* e.g. 29,7cm
*/
public void calibrate() {
Log.d(TAG, "calibrate RANNNNNNN!!!!");
if (!_calibrating || !_calibrated) {
_points = new ArrayList<>();
_calibrating = true;
_calibrationsLeft = CALIBRATION_MEASUREMENTS;
_threashold = CALIBRATION_MEASUREMENTS;
}
}
private void doneCalibrating() {
Log.d(TAG, "doneCalibrating RANNNNNNN!!!!");
_calibrated = true;
_calibrating = false;
_currentFaceDetectionThread = null;
// _measurementStartet = false;
_threashold = AVERAGE_THREASHHOLD;
_distanceAtCalibrationPoint = _currentAvgEyeDistance;
MessageHUB.get().sendMessage(MessageHUB.DONE_CALIBRATION, null);
}
public boolean isCalibrated() {
Log.d(TAG, "isCalibrated RANNNNNNN!!!!");
return _calibrated || _calibrating;
}
public void showMiddleEye(final boolean on) {
Log.d(TAG, "showMiddleEye RANNNNNNN!!!!");
_showTracking = on;
}
public void showEyePoints(final boolean on) {
Log.d(TAG, "showEyePoints RANNNNNNN!!!!");
_showEyes = on;
}
private void updateMeasurement(final FaceDetector.Face currentFace) {
if (currentFace == null) {
Log.d(TAG, "updateMeasurement RANNNNNNN!!!!");
// _facesFoundInMeasurement--;
return;
}
_foundFace = _currentFaceDetectionThread.getCurrentFace();
_points.add(new Point(_foundFace.eyesDistance(),
CALIBRATION_DISTANCE_A4_MM
* (_distanceAtCalibrationPoint / _foundFace
.eyesDistance())));
while (_points.size() > _threashold) {
_points.remove(0);
Log.d(TAG, "Removing points RANNNNNNN!!!!");
}
float sum = 0;
for (Point p : _points) {
sum += p.getEyeDistance();
Log.d(TAG, "adding points RANNNNNNN!!!!");
}
_currentAvgEyeDistance = sum / _points.size();
_currentDistanceToFace = CALIBRATION_DISTANCE_A4_MM
* (_distanceAtCalibrationPoint / _currentAvgEyeDistance);
_currentDistanceToFace = Util.MM_TO_CM(_currentDistanceToFace);
MeasurementStepMessage message = new MeasurementStepMessage();
message.setConfidence(currentFace.confidence());
message.setCurrentAvgEyeDistance(_currentAvgEyeDistance);
message.setDistToFace(_currentDistanceToFace);
message.setEyesDistance(currentFace.eyesDistance());
message.setMeasurementsLeft(_calibrationsLeft);
message.setProcessTimeForLastFrame(_processTimeForLastFrame);
MessageHUB.get().sendMessage(MessageHUB.MEASUREMENT_STEP, message);
}
private long _lastFrameStart = System.currentTimeMillis();
private float _processTimeForLastFrame = -1;
#Override
public void onPreviewFrame(final byte[] data, final Camera camera) {
Log.d(TAG, "onPreviewFrame RANNNNNNN!!!!" + _calibrationsLeft);
if (_calibrationsLeft == -1)
return;
if (_calibrationsLeft > 0) {
// Doing calibration !
Log.d(TAG, "_calibrationLeft RANNNNNNN!!!!" + _calibrationsLeft);
if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
Log.d(TAG, "_currentFaceDectectionThread RANNNNNNN!!!!" + _currentFaceDetectionThread);
// Drop Frame
return;
}
// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();
if (_currentFaceDetectionThread != null) {
Log.d(TAG, "_calibrationLeft-- RANNNNNNN!!!!");
_calibrationsLeft--;
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());
if (_calibrationsLeft == 0) {
Log.d(TAG, "Calibrating done RANNNNNNN!!!!");
doneCalibrating();
invalidate();
return;
}
}
_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
invalidate();
} else {
// Simple Measurement
if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
Log.d(TAG, "Dropping frames RANNNNNNN!!!!");
// Drop Frame
return;
}
// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();
if (_currentFaceDetectionThread != null)
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());
Log.d(TAG, "Updating measurements RANNNNNNN!!!!");
_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
Log.d(TAG, "invalidate RANNNNNNN!!!!");
invalidate();
}
}
/*
* SURFACE METHODS, TO CREATE AND RELEASE SURFACE THE CORRECT WAY.
*
* #see
* android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder
* )
*/
#Override
public void surfaceCreated(final SurfaceHolder holder) {
synchronized (this) {
// This allows us to make our own drawBitmap
this.setWillNotDraw(false);
}
}
#Override
public void surfaceDestroyed(final SurfaceHolder holder) {
mCamera.release();
mCamera = null;
}
#Override
public void surfaceChanged(final SurfaceHolder holder, final int format,
final int width, final int height) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
Parameters parameters = mCamera.getParameters();
_previewSize = parameters.getPreviewSize();
// mCamera.setDisplayOrientation(90);
// mCamera.setParameters(parameters);
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
mCamera.setPreviewCallback(this);
} catch (Exception e) {
Log.d("This", "Error starting camera preview: " + e.getMessage());
}
}
}
Here is the other code.
package com.example.phliip_vision;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera.Size;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.Log;
public class FaceDetectionThread extends Thread {
public static final String FACEDETECTIONTHREAD_TAG = "FaceDetectionThread_Tag";
private static final String TAG = "FaceDetectionThread";
private Face _currentFace;
private final byte[] _data;
private final Size _previewSize;
private Bitmap _currentFrame;
public FaceDetectionThread(final byte[] data, final Size previewSize) {
Log.d(TAG, "What are we waiting on in FaceDetectionThread????");
_data = data;
_previewSize = previewSize;
}
public Face getCurrentFace() {
Log.d(TAG, "What are we waiting on in Current faces????");
return _currentFace;
}
public Bitmap getCurrentFrame() {
return _currentFrame;
}
/**
* bla bla bla
*/
#Override
public void run() {
long t = System.currentTimeMillis();
YuvImage yuvimage = new YuvImage(_data, ImageFormat.NV21,
_previewSize.width, _previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!yuvimage.compressToJpeg(new Rect(0, 0, _previewSize.width,
_previewSize.height), 100, baos)) {
Log.e("Camera", "compressToJpeg failed");
}
Log.i("Timing", "Compression finished: "
+ (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inPreferredConfig = Bitmap.Config.RGB_565;
_currentFrame = BitmapFactory.decodeStream(new ByteArrayInputStream(
baos.toByteArray()), null, bfo);
Log.i("Timing", "Decode Finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
// Rotate the so it siuts our portrait mode
Matrix matrix = new Matrix();
matrix.postRotate(90);
matrix.preScale(-1, 1);
// We rotate the same Bitmap
_currentFrame = Bitmap.createBitmap(_currentFrame, 0, 0,
_previewSize.width, _previewSize.height, matrix, false);
Log.i("Timing",
"Rotate, Create finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
if (_currentFrame == null) {
Log.e(FACEDETECTIONTHREAD_TAG, "Could not decode Image");
return;
}
FaceDetector d = new FaceDetector(_currentFrame.getWidth(),
_currentFrame.getHeight(), 1);
Face[] faces = new Face[1];
d.findFaces(_currentFrame, faces);
Log.i("Timing",
"FaceDetection finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
_currentFace = faces[0];
Log.d(FACEDETECTIONTHREAD_TAG, "Found: " + faces[0] + " Faces");
}
}
enter image description here
enter image description here

NullPointerException in working with JButtons

public class Node extends JButton {
private Node rightConnection ;
private Node downConnection ;
private Node rightNode ,downNode, leftNode ,upNode;
private ArrayList<String> buttonImages = new ArrayList<String>();
public static void connectNodes(ArrayList<Node> nodes) {
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).setRightNode((nodes.get(i).getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + 1) : null);
nodes.get(i).setDownNode((nodes.get(i).getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + Integer.parseInt(SetMap.getMapSize())) : null);
nodes.get(i).setLeftNode((nodes.get(i).getLocation().x / 150 > 0) ? nodes.get(i - 1) : null);
nodes.get(i).setUpNode((nodes.get(i).getLocation().y / 150 > 0) ? nodes.get(i - Integer.parseInt(SetMap.getMapSize())) : null);
}
}
public class SetContent {
private JPanel contentPanel;
private int imgNum;
public SetContent() {
contentPanel = new JPanel(null);
contentPanel.setLocation(1166, 0);
contentPanel.setSize(200, 768);
makeOptionNodes();
}
private void makeOptionNodes() {
MouseListener mouseListener = new DragMouseAdapter();
for (int row = 0; row < 13; row++) {
for (int col = 0; col < 2; col++) {
Node button = new Node();
button.setSize(100, 50);
button.setLocation(col * 100, row * 50);
ImageIcon img = new ImageIcon("src/com/company/" + this.imgNum++ + ".png");
button.setIcon(new ImageIcon(String.valueOf(img)));
// to remote the spacing between the image and button's borders
//button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
//button.setBackground( ... );
button.setTransferHandler(new TransferHandler("icon"));
button.addMouseListener(mouseListener);
contentPanel.add(button);
}
}
}
}
public class DragMouseAdapter extends MouseAdapter{
String name= new String();
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
name = handler.getDragImage().toString();// here is another nullpointerException
for(int i = 0 ; i< Integer.parseInt(SetMap.getMapSize()) ; i++) {
if (c.getName().equals(String.valueOf(i))) {
((Node) c).getButtonImages().add(name);
}
}
}
}
public class SetMap {
private static String mapSize;
private JPanel nodesPanel;
private ArrayList<Node> nodes;
public SetMap() {
nodes = new ArrayList<Node>();
for (Node node : nodes) {
node = new Node();
}
nodesPanel = new JPanel(null);
nodesPanel.setLocation(0, 0);
nodesPanel.setSize(1166, 768);
this.mapSize = JOptionPane.showInputDialog(null, "enter map size:");
makeMapNodes();
Node.connectNodes(this.nodes);
makeConnections();
}
private void makeMapNodes() {
for (int row = 0; row < Integer.parseInt(this.mapSize); row++) {
for (int col = 0; col < Integer.parseInt(this.mapSize); col++) {
final Node button = new Node();
button.setRightNode(null);
button.setDownNode(null);
button.setLeftNode(null);
button.setUpNode(null);
button.setRightConnection(null);
button.setDownConnection(null);
button.setTransferHandler(new TransferHandler("icon"));
button.setSize(100, 100);
button.setLocation(col * 150, row * 150);
this.nodes.add(button);
nodesPanel.add(button);
Node.setNodeName(this.nodes, this.nodes.indexOf(button));
button.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int index = nodes.indexOf(button);
nodes.remove(button);
Node.setNodeName(nodes, index);
button.invalidate();
button.setVisible(false);
if (button.getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getRightConnection().invalidate();
button.getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getDownConnection().invalidate();
button.getDownConnection().setVisible(false);
}
if (button.getLocation().x / 150 > 0) {
button.getLeftNode().getRightConnection().invalidate();
button.getLeftNode().getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 > 0) {
button.getUpNode().getDownConnection().invalidate();
button.getUpNode().getDownConnection().setVisible(false);
}
}
});
}
}
}
private void makeConnections() {
for (Node button : this.nodes){
final Node rightConnection = new Node();
final Node downConnection = new Node();
rightConnection.setSize(50, 35);
downConnection.setSize(35, 50);
rightConnection.setLocation(button.getLocation().x + 100, button.getLocation().y + 35);
downConnection.setLocation(button.getLocation().x + 35, button.getLocation().y + 100);
button.setRightConnection(rightConnection);
button.setDownConnection(downConnection);
ImageIcon imgH = new ImageIcon("src/com/company/horizontal.png");
rightConnection.setIcon(new ImageIcon(String.valueOf(imgH)));
ImageIcon imgV = new ImageIcon("src/com/company/vertical.png");
downConnection.setContentAreaFilled(false);
downConnection.setIcon(new ImageIcon(String.valueOf(imgV)));
if(button.getLocation().x / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(rightConnection);
}
if(button.getLocation().y / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(downConnection);
}
rightConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
rightConnection.invalidate();
rightConnection.setVisible(false);
}
});
downConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
downConnection.invalidate();
downConnection.setVisible(false);
}
});
}
}
}
public class File {
public static void writeInFile(ArrayList<Node> nodes) {
try {
FileWriter fileWriter = new FileWriter("G:\\file.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("[" + SetMap.getMapSize() + "]" + "[" + SetMap.getMapSize() + "]");
bufferedWriter.newLine();
Iterator itr = nodes.iterator();
while (itr.hasNext()) {
Node node = (Node) itr.next();
if (node != null) {
bufferedWriter.write(node.getText());
bufferedWriter.newLine();
bufferedWriter.write("R" + ((node.getRightConnection() != null) ? node.getRightNode().getText() : null) + " D" + ((node.getDownConnection() != null) ? node.getDownNode().getText() : null) + " L" + ((node.getLeftNode().getRightConnection() != null) ? node.getLeftNode().getText() : null) + " U" + ((node.getUpNode().getDownConnection() != null) ? node.getUpNode().getText() : null));//here is the NullPOinterException
bufferedWriter.newLine();
bufferedWriter.write("image");
bufferedWriter.newLine();
Iterator it = node.getButtonImages().iterator();
while (it.hasNext()){
String images = (String) it.next();
bufferedWriter.write(" " + images);
}
}
}
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
public class Main {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(null);
final SetMap map = new SetMap();
SetContent options = new SetContent();
mainFrame.add(map.getNodesPanel());
mainFrame.add(options.getContentPanel());
JButton saveButton = new JButton("save");
saveButton.setSize(100, 25);
saveButton.setLocation(1050, 10);
saveButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
File.writeInFile(map.getNodes());
}
});
map.getNodesPanel().add(saveButton);
mainFrame.setVisible(true);
JOptionPane.showMessageDialog(null, "choose nodes and connections you want to remove");
}
}
I'm trying to write the changes that are made on some nodes I added in mapPanel but in the File class the line (which is commented), I get NullPointerException and also for another line in class DragMouseAdapter I get this exception again.
I've omitted some unimportant part of code. I know it's a lot to check code but I would be thankful for any simple help in this case cause I'm a real noob in programming.

JavaFX, apply setStyle to all LineCharts in ObservableList

I have ObservableList<LineChart> backCharts. Also I have class StackChartSeries to compare data's scale. Depending on that I add new backchart with new scale or add series to existed backchart.
Applying style to chart must work with every chart of the specified scale. But it works only with the first chart of the specified scale.
Code next:
public class StackChart extends StackPane {
private LineChart baseChart;
private final ObservableList<LineChart> backCharts = FXCollections.observableArrayList();
private final double yAxisWidth = 60;
private final AnchorPane details;
private final double yAxisSeparation = 20;
private double strokeWidth = 0.5;
private int size = 0;
public StackChart(LineChart baseChart) {
this(baseChart, null);
}
public StackChart(LineChart baseChart, Double strokeWidth) {
if (strokeWidth != null) {
this.strokeWidth = strokeWidth;
}
this.baseChart = baseChart;
baseChart.setCreateSymbols(false);
baseChart.setLegendVisible(false);
baseChart.getXAxis().setAutoRanging(false);
baseChart.getXAxis().setAnimated(false);
baseChart.getXAxis().setStyle("-fx-font-size:" + 18);
baseChart.getYAxis().setAnimated(false);
baseChart.getYAxis().setStyle("-fx-font-size:" + 18);
setFixedAxisWidth(baseChart);
setAlignment(Pos.CENTER_LEFT);
backCharts.addListener((Observable observable) -> rebuildChart());
details = new AnchorPane();
bindMouseEvents(baseChart, this.strokeWidth);
rebuildChart();
}
private void bindMouseEvents(LineChart baseChart, Double strokeWidth) {
getChildren().add(details);
details.prefHeightProperty().bind(heightProperty());
details.prefWidthProperty().bind(widthProperty());
details.setMouseTransparent(true);
setOnMouseMoved(null);
setMouseTransparent(false);
final Axis xAxis = baseChart.getXAxis();
final Axis yAxis = baseChart.getYAxis();
final Line xLine = new Line();
final Line yLine = new Line();
yLine.setFill(Color.GRAY);
xLine.setFill(Color.GRAY);
yLine.setStrokeWidth(strokeWidth/2);
xLine.setStrokeWidth(strokeWidth/2);
xLine.setVisible(false);
yLine.setVisible(false);
final Node chartBackground = baseChart.lookup(".chart-plot-background");
for (Node n: chartBackground.getParent().getChildrenUnmodifiable()) {
if (n != chartBackground && n != xAxis && n != yAxis) {
n.setMouseTransparent(true);
}
}
chartBackground.setCursor(Cursor.CROSSHAIR);
chartBackground.setOnMouseEntered((event) -> {
chartBackground.getOnMouseMoved().handle(event);
xLine.setVisible(true);
yLine.setVisible(true);
details.getChildren().addAll(xLine, yLine);
});
chartBackground.setOnMouseExited((event) -> {
xLine.setVisible(false);
yLine.setVisible(false);
details.getChildren().removeAll(xLine, yLine);
});
chartBackground.setOnMouseMoved(event -> {
double x = event.getX() + chartBackground.getLayoutX();
double y = event.getY() + chartBackground.getLayoutY();
xLine.setStartX(65);
xLine.setEndX(details.getWidth()-10);
xLine.setStartY(y+5);
xLine.setEndY(y+5);
yLine.setStartX(x+5);
yLine.setEndX(x+5);
yLine.setStartY(12);
yLine.setEndY(details.getHeight()-28);
});
}
private void setFixedAxisWidth(LineChart chart) {
chart.getYAxis().setPrefWidth(yAxisWidth);
chart.getYAxis().setMaxWidth(yAxisWidth);
}
private void rebuildChart() {
getChildren().clear();
getChildren().add(resizeBaseChart(baseChart));
for (LineChart lineChart : backCharts) {
getChildren().add(resizeBackgroundChart(lineChart));
}
getChildren().add(details);
}
private Node resizeBaseChart(LineChart lineChart) {
HBox hBox = new HBox(lineChart);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.prefHeightProperty().bind(heightProperty());
hBox.prefWidthProperty().bind(widthProperty());
lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
return lineChart;
}
private Node resizeBackgroundChart(LineChart lineChart) {
HBox hBox = new HBox(lineChart);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.prefHeightProperty().bind(heightProperty());
hBox.prefWidthProperty().bind(widthProperty());
hBox.setMouseTransparent(true);
lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
lineChart.translateXProperty().bind(baseChart.getYAxis().widthProperty());
lineChart.getYAxis().setTranslateX((yAxisWidth + yAxisSeparation) * backCharts.indexOf(lineChart));
return hBox;
}
private LineChart prepareLineChart(String seriesName){
NumberAxis yAxis = new NumberAxis();
NumberAxis xAxis = new NumberAxis();
// xAxis
xAxis.setAutoRanging(false);
xAxis.setVisible(false);
xAxis.setOpacity(0.0);
xAxis.lowerBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).lowerBoundProperty());
xAxis.upperBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).upperBoundProperty());
xAxis.tickUnitProperty().bind(((NumberAxis) baseChart.getXAxis()).tickUnitProperty());
// yAxis
yAxis.setSide(Side.RIGHT);
yAxis.setLabel(seriesName);
// create chart
LineChart lineChart = new LineChart(xAxis, yAxis);
lineChart.setAnimated(false);
lineChart.setLegendVisible(false);
setFixedAxisWidth(lineChart);
return lineChart;
}
public void addSeries(List<StackChartSeries> series){
Collections.sort(series, (x, y) -> (int) (x.getMaxY() - y.getMaxY()));
LineChart lineChart = null;
size = series.size();
for (int i = 0; i < size; i++) {
if (i == 0 || series.get(i).getMaxY() / series.get(i-1).getMaxY() >= 10
|| series.get(i).getMaxY() / series.get(i-1).getMaxY() <= 0.1
|| Math.abs(series.get(i).getMaxY() - series.get(i-1).getMaxY()) >= 900
) {
lineChart = prepareLineChart("Scale" + i);
//new chart with new scale
backCharts.add(lineChart);
}
lineChart.getData().add(series.get(i).getSeries());
}
int j = 0;
for (LineChart chart : backCharts) {
styleBackChart(chart);
//HERE
setLineStyle(chart, j+3);
}
}
private void styleBackChart(LineChart lineChart) {
setStyle(lineChart);
Node contentBackground = lineChart.lookup(".chart-content").lookup(".chart-plot-background");
contentBackground.setStyle("-fx-background-color: transparent;");//
lineChart.setVerticalZeroLineVisible(false);
lineChart.setHorizontalZeroLineVisible(false);
lineChart.setVerticalGridLinesVisible(false);
lineChart.setHorizontalGridLinesVisible(false);
lineChart.setCreateSymbols(false);
lineChart.getXAxis().setStyle("-fx-font-size:" + 18);
lineChart.getYAxis().setStyle("-fx-font-size:" + 18);
}
private void setStyle(LineChart chart) {
chart.getYAxis().lookup(".axis-label").setStyle("-fx-font-size: 24;");
Node seriesLine = chart.lookup(".chart-series-line");
seriesLine.setStyle("-fx-stroke-width: " + strokeWidth + ";");
}
public Node getLegend() {
HBox hbox = new HBox();
final CheckBox baseChartCheckBox = new CheckBox(baseChart.getYAxis().getLabel());
baseChartCheckBox.setSelected(true);
baseChartCheckBox.setDisable(true);
baseChartCheckBox.getStyleClass().add("readonly-checkbox");
baseChartCheckBox.setOnAction(event -> baseChartCheckBox.setSelected(true));
hbox.getChildren().add(baseChartCheckBox);
for (final LineChart lineChart : backCharts) {
CheckBox checkBox = new CheckBox(lineChart.getYAxis().getLabel());
checkBox.setSelected(true);
checkBox.setOnAction(event -> {
if (backCharts.contains(lineChart)) {
backCharts.remove(lineChart);
} else {
backCharts.add(lineChart);
}
});
hbox.getChildren().add(checkBox);
}
hbox.setAlignment(Pos.CENTER);
hbox.setSpacing(20);
hbox.setStyle("-fx-padding: 0 10 20 10");
return hbox;
}
private void setLineStyle (LineChart chart, Integer k) {
Node seriesLine = chart.lookup(".chart-series-line");
seriesLine.setStyle(" -fx-stroke-dash-array: " + k + " 5 15 5;");
}
}
StackChartSeries.java:
import javafx.scene.chart.XYChart;
import org.apache.commons.lang.ArrayUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
public class StackChartSeries {
private XYChart.Series series;
private final double[] xValues;
private final double[] yValues;
private Optional<Double> maxY;
public StackChartSeries(double[] xValues, double[] yValues) {
this.xValues = xValues;
this.yValues = yValues;
}
public XYChart.Series getSeries() {
return series != null ? series : (series = prepareSeries(xValues, yValues));
}
private static XYChart.Series<Number, Number> prepareSeries( double[] xValues, double[] yValues) {
XYChart.Series<Number, Number> series = new XYChart.Series<>();
for (int i = 0; i < yValues.length; i++){
series.getData().add(new XYChart.Data(xValues[i], yValues[i]));
}
return series;
}
public double getMaxY(){
if (maxY != null){
return maxY.get();
}
else {
Double d = C?ollections.max(Arrays.asList(ArrayUtils.toObject(yValues)));
maxY = Optional.of(d);
return maxY.get();
}
}
public double[] getXValues() {
return xValues;
}
public double[] getYValues() {
return yValues;
}
}

Why does this Dialog immediately dispose in this situation?

There is a user defined component , derived from Container, inside my Form. It has a pointerPressed method implemented in its class code. In the code of that method I show a Dialog containing a List , and in the class code of the derived Dialog ( in the constructor ) I set the setDisposeWhenPointerOutOfBounds method with the argument value to true.
The problem is that in run time when I click the user defined component ( ListBox ) in my Form then the Dialog is shown , of course , but immediately it closes ( disposes ) , although I don't click outside the boundary of the Dialog !
So why does it have such a behavior ?
Codes :
public class ListBox extends Container
{
private Form containerForm;
private Container cListBox = new Container(new BorderLayout());
private Label[] tLabel;
private int[] tLabelW;
private int largestLabelW;
private Label libelle = new Label();
private Label arrow = new Label((MenuPrincipalForm.r).getImage("listboxarrow"));
private int preferredWidth, preferredHeight, screenWidth, screenHeight;
private Vector vData = new Vector();
private final int leftPadding = 3;
private int listW;
private List list;
private DialogListBox dialog;
private String selectedData;
public ListBox(Form containingForm, String[] lData, int prefHeight, int formWidth, int formHeight, int topMargin, int bottomMargin)
{
super(new FlowLayout(Component.CENTER));
setFocusable(true);
containerForm = containingForm;
screenWidth = formWidth;
screenHeight = formHeight;
tLabel = new Label[lData.length + 1];
tLabelW = new int[lData.length + 1];
if (lData.length > 0)
{
for (int i = 0 ; i < lData.length + 1 ; i++)
{
if (i < lData.length)
{
vData.addElement(new String(lData[i]));
tLabel[i] = new Label(lData[i]);
tLabelW[i] = tLabel[i].getPreferredW();
}
else
{
vData.addElement(new String(""));
tLabel[i] = new Label("");
tLabelW[i] = 0;
}
}
}
else
{
vData.addElement(new String(""));
tLabel[0] = new Label("");
tLabelW[0] = 0;
}
largestLabelW = Comparator.max(tLabelW);
preferredWidth = leftPadding + largestLabelW + arrow.getPreferredW();
preferredHeight = prefHeight - 2 ;
selectedData = String.valueOf(vData.lastElement());
libelle.setText(String.valueOf(vData.lastElement()));
libelle.setTextPosition(Label.LEFT);
libelle.setPreferredW(preferredWidth);
libelle.setPreferredH(preferredHeight);
arrow.setAlignment(Label.CENTER);
arrow.setPreferredH(preferredHeight);
dialog = new DialogListBox(leftPadding, this);
list = dialog.getList();
cListBox.addComponent(BorderLayout.WEST, libelle);
cListBox.addComponent(BorderLayout.EAST, arrow);
cListBox.setPreferredH(preferredHeight);
getUnselectedStyle().setPadding(Component.LEFT, leftPadding);
getSelectedStyle().setPadding(Component.LEFT, leftPadding);
getUnselectedStyle().setBorder(Border.createLineBorder(1));
getSelectedStyle().setBorder(Border.createLineBorder(1));
addComponent(cListBox);
setPreferredH(preferredHeight);
getUnselectedStyle().setMargin(Component.TOP, topMargin);
getSelectedStyle().setMargin(Component.TOP, topMargin);
getUnselectedStyle().setMargin(Component.BOTTOM, bottomMargin);
getSelectedStyle().setMargin(Component.BOTTOM, bottomMargin);
}
public void setSelectedIndex(int idx)
{
list.setSelectedIndex(idx);
selectedData = String.valueOf(vData.elementAt(idx));
libelle.setText(String.valueOf(vData.elementAt(idx)));
repaint();
}
public void setSelectedData(String data)
{
selectedData = data;
libelle.setText(selectedData);
repaint();
}
public String getSelectedData()
{
return selectedData;
}
public int getLastIndex()
{
return vData.indexOf(vData.lastElement());
}
public Vector getListBoxDataSource()
{
return vData;
}
private void showListBoxDialog()
{
int espaceVertRestant, top, bottom, left, right;
espaceVertRestant = screenHeight - ( libelle.getAbsoluteY() + preferredHeight );
if (espaceVertRestant > list.getPreferredH())
{
top = getAbsoluteY() + preferredHeight - 1 ;
bottom = screenHeight - ( getAbsoluteY() + preferredHeight + list.getPreferredH() ) ;
}
else
{
top = screenHeight - ( list.getPreferredH() + preferredHeight + espaceVertRestant ) ;
bottom = getAbsoluteY() - 1 ;
}
left = getAbsoluteX() ;
right = screenWidth - ( getAbsoluteX() + getPreferredW() );
listW = screenWidth - left - right ;
containerForm.setTintColor(containerForm.getSelectedStyle().getBgColor());
dialog.setListW(listW);
dialog.show(top, bottom, left, right, false, false);
}
public void keyPressed(int keyCode)
{
int gameAction = (Display.getInstance()).getGameAction(keyCode);
if (gameAction == Display.GAME_FIRE)
showListBoxDialog();
else
super.keyPressed(keyCode);
}
public void pointerPressed(int x, int y)
{
showListBoxDialog();
}
}
public class DialogListBox extends Dialog implements ActionListener
{
private Vector vData;
private CListCellListBox listRenderer;
private List list;
private ListBox theListBox;
public DialogListBox(int leftPadding, ListBox listBox)
{
super();
setFocusable(true);
setDisposeWhenPointerOutOfBounds(true);
getContentPane().getSelectedStyle().setPadding(0, 0, 0, 0);
getContentPane().getUnselectedStyle().setPadding(0, 0, 0, 0);
getContentPane().getStyle().setPadding(0, 0, 0, 0);
theListBox = listBox;
listRenderer = new CListCellListBox(false);
vData = listBox.getListBoxDataSource();
list = (new CList(vData, false)).createList(listRenderer, this);
list.setItemGap(0);
list.setSelectedIndex(vData.indexOf(vData.lastElement()));
list.getSelectedStyle().setPadding(0, 0, leftPadding, 0);
list.getUnselectedStyle().setPadding(0, 0, leftPadding, 0);
list.getUnselectedStyle().setBorder(Border.createLineBorder(1), false);
list.getSelectedStyle().setBorder(Border.createLineBorder(1), false);
list.setIsScrollVisible(false);
addComponent(list);
}
protected void onShow()
{
list.requestFocus();
repaint();
}
public void setListW(int prefW)
{
list.setPreferredW(prefW);
}
public List getList()
{
return list;
}
private void refreshListBox()
{
dispose();
if (list.getSelectedItem() instanceof Content)
{
Content valeur = (Content)list.getSelectedItem();
theListBox.setSelectedData(valeur.getEnreg());
}
}
public void keyPressed(int keyCode)
{
int gameAction = (Display.getInstance()).getGameAction(keyCode);
if (gameAction == Display.GAME_FIRE)
refreshListBox();
else
super.keyPressed(keyCode);
}
public void actionPerformed(ActionEvent ae) {
if ( (ae.getSource() instanceof List) && ((List)ae.getSource()).equals(list) )
refreshListBox();
}
}
public class CList {
private Vector data = new Vector();
private boolean showPhoto;
private Content[] contents;
public CList(Vector vData, boolean displayPhoto)
{
data = vData;
showPhoto = displayPhoto;
contents = new Content[vData.size()];
}
public List createList(CListCell renderer, ActionListener listener)
{
List theList;
if (showPhoto)
{
for(int i = 0; i < data.size(); i++)
{
Image img = getFirstImage(Formatage.getColumnValueAt(String.valueOf(data.elementAt(i)), 0));
contents[i] = new Content(img, String.valueOf(data.elementAt(i)));
}
}
else
{
for(int i = 0; i < data.size(); i++)
{
contents[i] = new Content(String.valueOf(data.elementAt(i)));
}
}
theList = new List(contents);
theList.setListCellRenderer(renderer);
theList.setFixedSelection(List.FIXED_NONE_CYCLIC);
theList.addActionListener(listener);
return theList;
}
// ... other methods
}
You should always use pointerReleased/keyReleased for navigation to different forms/dialogs.
Otherwise the pointer/key released will be sent to the next form/dialog and trigger an action there.
Pointer pressed is mostly used internally in LWUIT and for some special cases.

Resources