Why is my magnifying glass not following the mouse? - javafx-2

Im trying to migrate the JavaFX 1.3 Magnifying Glass example to JavaFX 2.0 at http://docs.oracle.com/javafx/1.3/tutorials/FXImage/ , but i've come across a problem.
I might have become blind, but i really cant figure out, why the glassgroup doesn't follow the mouse.
Here's the code:
package javafxapplication18;
import javafx.application.Application;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.EventHandler;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class JavaFXApplication18 extends Application {
private ImageView bgImageView = new ImageView();
private Image image;
private Scene scene;
private DoubleProperty magnification = new SimpleDoubleProperty();
private DoubleProperty GLASS_SIZE = new SimpleDoubleProperty();
private DoubleProperty GLASS_CENTER = new SimpleDoubleProperty();
private DoubleProperty centerX = new SimpleDoubleProperty();
private DoubleProperty centerY = new SimpleDoubleProperty();
private DoubleProperty factor = new SimpleDoubleProperty();
private DoubleProperty viewportCenterX = new SimpleDoubleProperty();
private DoubleProperty viewportCenterY = new SimpleDoubleProperty();
private DoubleProperty viewportSize = new SimpleDoubleProperty();
private ImageView magGlass = new ImageView();
private Group glassGroup = new Group();
private Text desc = new Text();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
DoubleBinding db = new DoubleBinding() {
{
super.bind(centerX, factor);
}
#Override
protected double computeValue() {
return centerX.get() * factor.get();
}
};
DoubleBinding db2 = new DoubleBinding() {
{
super.bind(centerY, factor);
}
#Override
protected double computeValue() {
return centerY.get() * factor.get();
}
};
viewportCenterX.bind(db);
viewportCenterY.bind(db2);
image = new Image(this.getClass().getResourceAsStream("/SANY0194.jpg"));
StackPane root = new StackPane();
scene = new Scene(root, 900, 700);
setupBgImageView();
setupFactor();
setupGLASS_SIZE();
magnification.setValue(1.5);
DoubleBinding db3 = new DoubleBinding() {
{
super.bind(GLASS_SIZE, factor, magnification);
}
#Override
protected double computeValue() {
return GLASS_SIZE.get() * factor.get() / magnification.get();
}
};
viewportSize.bind(db3);
setupMagGlass();
setupGlassGroup();
setupDesc();
bgImageView.requestFocus();
primaryStage.setTitle("Magnifying Glass");
primaryStage.setWidth(image.getWidth() / 2);
primaryStage.setHeight(image.getHeight() / 2);
root.getChildren().addAll(bgImageView, glassGroup, desc);
primaryStage.setScene(scene);
primaryStage.show();
//style: StageStyle.UNDECORATED
}
public void adjustMagnification(final double amount) {
DoubleProperty newMagnification = new SimpleDoubleProperty();
DoubleBinding db3 = new DoubleBinding() {
{
super.bind(magnification);
}
#Override
protected double computeValue() {
if (magnification.get() + amount / 4 < .5) {
return .5;
} else if (magnification.get() + amount / 4 > 10) {
return 10;
} else {
return magnification.get() + amount / 4;
}
}
};
newMagnification.bind(db3);
magnification.setValue(newMagnification.getValue());
}
private void setupGLASS_SIZE() {
DoubleBinding db = new DoubleBinding() {
{
super.bind(bgImageView.boundsInLocalProperty());
}
#Override
protected double computeValue() {
return bgImageView.boundsInLocalProperty().get().getWidth() / 4;
}
};
GLASS_SIZE.bind(db);
DoubleBinding db1 = new DoubleBinding() {
{
super.bind(GLASS_SIZE);
}
#Override
protected double computeValue() {
return GLASS_SIZE.get() / 2;
}
};
GLASS_CENTER.bind(db1);
}
private void setupFactor() {
DoubleBinding db = new DoubleBinding() {
{
super.bind(image.heightProperty(), bgImageView.boundsInLocalProperty());
}
#Override
protected double computeValue() {
return image.heightProperty().get() / bgImageView.boundsInLocalProperty().get().getHeight();
}
};
factor.bind(db);
}
private void setupBgImageView() {
bgImageView.setImage(image);
bgImageView.fitWidthProperty().bind(scene.widthProperty());
bgImageView.fitHeightProperty().bind(scene.heightProperty());
BooleanBinding bb = new BooleanBinding() {
{
super.bind(factor);
}
#Override
protected boolean computeValue() {
if (factor.get() != 1.0) {
return true;
} else {
return false;
}
}
};
bgImageView.cacheProperty().bind(bb);
bgImageView.setSmooth(true);
bgImageView.setPreserveRatio(true);
bgImageView.setOnMouseMoved(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
centerX.setValue(me.getX());
centerY.setValue(me.getY());
}
});
bgImageView.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent ke) {
if (ke.getCode() == KeyCode.EQUALS || ke.getCode() == KeyCode.PLUS) {
adjustMagnification(1.0);
} else if (ke.getCode() == KeyCode.MINUS) {
adjustMagnification(-1.0);
}
}
});
bgImageView.impl_setOnMouseWheelRotated(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
adjustMagnification(me.impl_getWheelRotation());
}
});
bgImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
if (me.getButton() != MouseButton.PRIMARY) {
magGlass.setSmooth(magGlass.isSmooth());
}
bgImageView.requestFocus();
}
});
}
private void setupMagGlass() {
magGlass.setImage(image);
magGlass.setPreserveRatio(true);
magGlass.fitWidthProperty().bind(GLASS_SIZE);
magGlass.fitHeightProperty().bind(GLASS_SIZE);
magGlass.setSmooth(true);
ObjectBinding ob = new ObjectBinding() {
{
super.bind(viewportCenterX, viewportSize, viewportCenterY);
}
#Override
protected Object computeValue() {
return new Rectangle2D(viewportCenterX.get() - viewportSize.get() / 2, (viewportCenterY.get() - viewportSize.get() / 2), viewportSize.get(), viewportSize.get());
}
};
magGlass.viewportProperty().bind(ob);
Circle clip = new Circle();
clip.centerXProperty().bind(GLASS_CENTER);
clip.centerYProperty().bind(GLASS_CENTER);
DoubleBinding db1 = new DoubleBinding() {
{
super.bind(GLASS_CENTER);
}
#Override
protected double computeValue() {
return GLASS_CENTER.get() - 5;
}
};
clip.radiusProperty().bind(db1);
magGlass.setClip(clip);
}
private void setupGlassGroup() {
DoubleBinding db = new DoubleBinding() {
{
super.bind(centerX, GLASS_CENTER);
}
#Override
protected double computeValue() {
return centerX.get() - GLASS_CENTER.get();
}
};
DoubleBinding db2 = new DoubleBinding() {
{
super.bind(centerY, GLASS_CENTER);
}
#Override
protected double computeValue() {
return centerY.get() - GLASS_CENTER.get();
}
};
System.out.println("glassGroup.getLayoutX() " + glassGroup.getLayoutX());
System.out.println("glassGroup.getLayoutY() " + glassGroup.getLayoutY());
glassGroup.translateXProperty().bind(db);
glassGroup.translateYProperty().bind(db2);
Text text = new Text();
DoubleBinding db3 = new DoubleBinding() {
{
super.bind(GLASS_CENTER);
}
#Override
protected double computeValue() {
return GLASS_CENTER.get() + GLASS_CENTER.get() / 2;
}
};
text.xProperty().bind(db3);
text.yProperty().bind(GLASS_SIZE);
text.setText("x{%2.2f magnification}");
Circle circle = new Circle();
circle.centerXProperty().bind(GLASS_CENTER);
circle.centerYProperty().bind(GLASS_CENTER);
DoubleBinding db4 = new DoubleBinding() {
{
super.bind(GLASS_CENTER);
}
#Override
protected double computeValue() {
return GLASS_CENTER.get() - 2;
}
};
circle.radiusProperty().bind(db4);
circle.setStroke(Color.GREEN);
circle.setStrokeWidth(3);
circle.setFill(null);
glassGroup.getChildren().addAll(magGlass, text, circle);
DropShadow dropShadow = new DropShadow();
dropShadow.setOffsetY(4);
glassGroup.setEffect(dropShadow);
}
private void setupDesc() {
desc.setX(10);
desc.setY(15);
if (!bgImageView.isFocused()) {
desc.setText("Click image to focus");
} else {
desc.setText("Use the +/- or mouse wheel to zoom. Right-click to make the magnification "
+ "{if (magGlass.smooth) less smooth. else more smooth.}");
}
desc.setFont(new Font(12));
}
}
any help will be appreciated :-)

1. You may want to upgrade to JavaFX 2.1 (developers preview).
You would have to change only impl_setOnMouseWheel handler to
bgImageView.setOnScroll(new EventHandler<ScrollEvent>() {
#Override
public void handle(ScrollEvent me) {
adjustMagnification(me.getDeltaY()/40);
}
});
2. To fix centering of the glass you need to fix your layout. StackPane put all chidren in the center which doesn't correlate with your math. Use Pane instead:
Pane root = new Pane();
scene = new Scene(root, 900, 700);
3. Then you do that your glassGroup will be positioned under the mouse, and mouse events will be consumed by it. So you should also add next call to setupGlassGroup:
glassGroup.setMouseTransparent(true);
4. Also, you can simplify your bindings. Instead of overriding computeValue each time you can use convenience methods like here: viewportCenterX.bind(centerX.multiply(factor));. See updated code below:
public class MagnifyingGlass extends Application {
private ImageView bgImageView = new ImageView();
private Image image;
private Scene scene;
private DoubleProperty magnification = new SimpleDoubleProperty();
private DoubleProperty GLASS_SIZE = new SimpleDoubleProperty();
private DoubleProperty GLASS_CENTER = new SimpleDoubleProperty();
private DoubleProperty centerX = new SimpleDoubleProperty();
private DoubleProperty centerY = new SimpleDoubleProperty();
private DoubleProperty factor = new SimpleDoubleProperty();
private DoubleProperty viewportCenterX = new SimpleDoubleProperty();
private DoubleProperty viewportCenterY = new SimpleDoubleProperty();
private DoubleProperty viewportSize = new SimpleDoubleProperty();
private ImageView magGlass = new ImageView();
private Group glassGroup = new Group();
private Text desc = new Text();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
viewportCenterX.bind(centerX.multiply(factor));
viewportCenterY.bind(centerY.multiply(factor));
viewportSize.bind(GLASS_SIZE.multiply(factor).multiply(magnification));
image = new Image(this.getClass().getResourceAsStream("/sample.jpg"));
Pane root = new Pane();
scene = new Scene(root, 900, 700);
setupBgImageView();
setupFactor();
setupGLASS_SIZE();
magnification.setValue(1.5);
setupMagGlass();
setupGlassGroup();
setupDesc();
bgImageView.requestFocus();
primaryStage.setTitle("Magnifying Glass");
primaryStage.setWidth(image.getWidth() / 2);
primaryStage.setHeight(image.getHeight() / 2);
root.getChildren().addAll(bgImageView, glassGroup, desc);
primaryStage.setScene(scene);
primaryStage.show();
}
public void adjustMagnification(final double amount) {
// no bindings is needed here - it's one time operation
double newValue = magnification.get() + amount / 4;
if (newValue < .5) {
newValue = .5;
} else if (newValue > 10) {
newValue = 10;
}
magnification.setValue(newValue);
}
private void setupGLASS_SIZE() {
DoubleBinding db = new DoubleBinding() {
{
super.bind(bgImageView.boundsInLocalProperty());
}
#Override
protected double computeValue() {
return bgImageView.boundsInLocalProperty().get().getWidth() / 4;
}
};
GLASS_SIZE.bind(db);
GLASS_CENTER.bind(GLASS_SIZE.divide(2));
}
private void setupFactor() {
DoubleBinding db = new DoubleBinding() {
{
super.bind(image.heightProperty(), bgImageView.boundsInLocalProperty());
}
#Override
protected double computeValue() {
return image.heightProperty().get() / bgImageView.boundsInLocalProperty().get().getHeight();
}
};
factor.bind(db);
}
private void setupBgImageView() {
bgImageView.setImage(image);
bgImageView.fitWidthProperty().bind(scene.widthProperty());
bgImageView.fitHeightProperty().bind(scene.heightProperty());
// comparing double requires precision
bgImageView.cacheProperty().bind(factor.isNotEqualTo(1.0, 0.05));
bgImageView.setSmooth(true);
bgImageView.setPreserveRatio(true);
bgImageView.setOnMouseMoved(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
centerX.setValue(me.getX());
centerY.setValue(me.getY());
}
});
bgImageView.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent ke) {
if (ke.getCode() == KeyCode.EQUALS || ke.getCode() == KeyCode.PLUS) {
adjustMagnification(1.0);
} else if (ke.getCode() == KeyCode.MINUS) {
adjustMagnification(-1.0);
}
}
});
bgImageView.setOnScroll(new EventHandler<ScrollEvent>() {
#Override
public void handle(ScrollEvent me) {
adjustMagnification(me.getDeltaY() / 40);
}
});
bgImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
if (me.getButton() != MouseButton.PRIMARY) {
magGlass.setSmooth(magGlass.isSmooth());
}
bgImageView.requestFocus();
}
});
}
private void setupMagGlass() {
magGlass.setImage(image);
magGlass.setPreserveRatio(true);
magGlass.fitWidthProperty().bind(GLASS_SIZE);
magGlass.fitHeightProperty().bind(GLASS_SIZE);
magGlass.setSmooth(true);
ObjectBinding ob = new ObjectBinding() {
{
super.bind(viewportCenterX, viewportSize, viewportCenterY);
}
#Override
protected Object computeValue() {
return new Rectangle2D(viewportCenterX.get() - viewportSize.get() / 2, (viewportCenterY.get() - viewportSize.get() / 2), viewportSize.get(), viewportSize.get());
}
};
magGlass.viewportProperty().bind(ob);
Circle clip = new Circle();
clip.centerXProperty().bind(GLASS_CENTER);
clip.centerYProperty().bind(GLASS_CENTER);
clip.radiusProperty().bind(GLASS_CENTER.subtract(5));
magGlass.setClip(clip);
}
private void setupGlassGroup() {
glassGroup.translateXProperty().bind(centerX.subtract(GLASS_CENTER));
glassGroup.translateYProperty().bind(centerY.subtract(GLASS_CENTER));
Text text = new Text();
text.xProperty().bind(GLASS_CENTER.multiply(1.5));
text.yProperty().bind(GLASS_SIZE);
text.textProperty().bind(Bindings.concat("x", magnification, " magnification"));
Circle circle = new Circle();
circle.centerXProperty().bind(GLASS_CENTER);
circle.centerYProperty().bind(GLASS_CENTER);
circle.radiusProperty().bind(GLASS_CENTER.subtract(2));
circle.setStroke(Color.GREEN);
circle.setStrokeWidth(3);
circle.setFill(null);
glassGroup.getChildren().addAll(magGlass, text, circle);
DropShadow dropShadow = new DropShadow();
dropShadow.setOffsetY(4);
glassGroup.setEffect(dropShadow);
glassGroup.setMouseTransparent(true);
}
private void setupDesc() {
desc.setX(10);
desc.setY(15);
if (!bgImageView.isFocused()) {
desc.setText("Click image to focus");
} else {
desc.setText("Use the +/- or mouse wheel to zoom. Right-click to make the magnification "
+ "{if (magGlass.smooth) less smooth. else more smooth.}");
}
desc.setFont(new Font(12));
}
}

Related

Change ImageView after choosing photo from Gallery

I am trying to change my imageview when its on click and then choose image from gallery then change it. But I don't think its working since when I tried running my project, it just crashes out of the app.
Navigation Drawer
ActivityResult
ActivityResultLauncher<String> mGetContent = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
ImageView
profileImage = (ImageView) findViewById(R.id.profilepic);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
p.s. The ImageView is inside my navigation drawer. what I wanted to do is that whenever I click or press the ImageView which is the Hamburger Icon, it will redirect to gallery to choose image and then change it once the user chose one.
MapsActivity.java
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private static final String TAG = "";
private DrawerLayout drawer;
LatLng carWash1 = new LatLng(6.106535, 125.187230);
LatLng carWash2 = new LatLng(6.106123, 125.189280);
private ArrayList<LatLng> locationArrayList;
private ImageView profileImage;
final static int Gallery_Pick = 1;
private GoogleMap mMap;
private ActivityMapsBinding binding;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location recentLocation;
private Marker currentMark;
private static final int Request_User_Location = 1234;
private List<Polyline> polylines = null;
protected LatLng start = null;
protected LatLng end = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
locationArrayList = new ArrayList<>();
locationArrayList.add(carWash1);
locationArrayList.add(carWash2);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
super.onBackPressed();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_User_Location:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
for (int i = 0; i < locationArrayList.size(); i++) {
mMap.addMarker(new MarkerOptions().position(locationArrayList.get(0)).title("Purok 5 Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
mMap.addMarker(new MarkerOptions().position(locationArrayList.get(1)).title("Stratford Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locationArrayList.get(i), 15));
mMap.moveCamera(CameraUpdateFactory.newLatLng(locationArrayList.get(i)));
}
boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
}
private BitmapDescriptor BitMapFromVector(Context context, int vectorResId) {
// below line is use to generate a drawable.
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
// below line is use to set bounds to our vector drawable.
vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
// below line is use to create a bitmap for our
// drawable which we have added.
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
// below line is use to add bitmap in our canvas.
Canvas canvas = new Canvas(bitmap);
// below line is use to draw our
// vector drawable in canvas.
vectorDrawable.draw(canvas);
// after generating our bitmap we are returning our bitmap.
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(#NonNull Location location) {
recentLocation = location;
if (currentMark != null) {
currentMark.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentMark = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(12));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

MailJava in a new Thread

I try to get emails from csv file and start mailing process. Everything works fine if I do it in the main thread. But if I start a new thread and try to do it threre it gives me NullPointer on this line:
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
For some reason it cannot get a list of emails.
Full code is here:
package com.company;
import javax.mail.MessagingException;
import javax.swing.*;
import static com.company.MainFormAppearance.mailingSubject;
import static com.company.MainFormAppearance.mailingText;
public class NewThead implements Runnable {
public JTextArea jTextAreaStatus;
public Reader readerEmail;
private boolean doStop = false;
public synchronized void doStop() {
this.doStop = true;
}
private synchronized boolean keepRunning() {
return this.doStop == false;
}
#Override
public void run() {
while (keepRunning()){
Email email = new Email();
try {
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
} catch (MessagingException e) {
e.printStackTrace();
}
}
jTextAreaStatus.setText("completed");
}
}
Main class:
public class MainFormAppearance {
private JTextArea jTextAreaText;
private JTextArea jTextAreaSubject;
private JTextArea jTextAreaEmail;
private JTextArea jTextAreaStatus;
private JLabel blueLabel;
private JLabel copyRightLabel;
public JButton parceButton;
private JButton mailButton;
private JButton stopButton;
private String FILE_PATH_TEXT = "c:/Users/R2D2/Desktop/Main.txt";
private String FILE_PATH_SUBJECT = "c:/Users/R2D2/Desktop/Subject.txt";
public String CsvEmailsPath = "C:\\Users\\R2D2\\Desktop\\Emailstest.csv";
public String CsvBusinessesPath = "C:\\Users\\R2D2\\Desktop\\Businessestest.csv";
public static String mailingText = null;
public static String mailingSubject = null;
public Reader readerEmail;
public Reader readerBusiness;
public JPanel createContentPanel() {
JPanel totalGui = new JPanel();
totalGui.setLayout(null);
totalGui.setBackground(new Color(72, 209, 204));
jTextAreaText = new JTextArea();
jTextAreaSubject = new JTextArea();
jTextAreaEmail = new JTextArea();
jTextAreaStatus = new JTextArea();
blueLabel = new JLabel("Java Mailing Program");
copyRightLabel = new JLabel("\u00a9" + " Alex B - 2018");
parceButton = new JButton("Upload");
mailButton = new JButton("!Start!");
stopButton = new JButton("Stop");
readerEmail = new Reader();
readerBusiness = new Reader();
NewThead newThead = new NewThead();
Thread thread = new Thread(newThead);
//set program label
copyRightLabel.setLocation(10, 230);
copyRightLabel.setSize(400, 20);
copyRightLabel.setFont(new Font("Courier New", Font.ITALIC, 12));
copyRightLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(copyRightLabel);
//set program label
blueLabel.setLocation(10, 10);
blueLabel.setSize(400, 20);
blueLabel.setFont(new Font("Courier New", Font.ITALIC, 15));
blueLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(blueLabel);
//set Button 1 and click
parceButton.setLocation(270, 50);
parceButton.setSize(100, 30);
totalGui.add(parceButton);
parceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//parce data from files to Strings
mailingText = readLineByLineJava8(FILE_PATH_TEXT);
mailingSubject = readLineByLineJava8(FILE_PATH_SUBJECT);
try {
readerEmail.readCsvFile(CsvEmailsPath);
readerBusiness.readCsvFile(CsvBusinessesPath);
} catch (IOException e1) {
e1.printStackTrace();
}
if (isNullOrEmpty(mailingText)) {
jTextAreaText.setText("Text is empty! Check it!!!");
} else {
jTextAreaText.setText("***Text is Ready***");
}
if (isNullOrEmpty(mailingSubject)) {
jTextAreaSubject.setText("Subject is empty! Check it!!!");
} else {
jTextAreaSubject.setText("***Subject is Ready***");
}
}
});
//set Button 2 and click
mailButton.setLocation(270, 100);
mailButton.setSize(100, 30);
totalGui.add(mailButton);
mailButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
newThead.doStop();
jTextAreaStatus.setText("Stopped");
}
});
stopButton.setLocation(270, 150);
stopButton.setSize(100, 30);
totalGui.add(stopButton);
jTextAreaText.setLocation(20, 52);
jTextAreaText.setSize(200, 16);
jTextAreaText.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaText.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaText);
jTextAreaSubject.setLocation(20, 82);
jTextAreaSubject.setSize(200, 16);
jTextAreaSubject.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaSubject.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaSubject);
jTextAreaEmail.setLocation(20, 112);
jTextAreaEmail.setSize(200, 16);
jTextAreaEmail.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaEmail.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaEmail);
jTextAreaStatus.setLocation(20, 182);
jTextAreaStatus.setSize(200, 16);
jTextAreaStatus.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaStatus.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaStatus);
totalGui.setOpaque(true);
return totalGui;
}
public static boolean isNullOrEmpty(String str) {
if (str != null && !str.isEmpty())
return false;
return true;
}
}
Class that reads emails from csv (should be correct):
package com.company;
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Reader {
public CSVReader reader;
public LinkedList myList;
public void readCsvFile(String path) throws IOException {
try {
reader = new CSVReader(new FileReader(path));
String[] column;
myList = new LinkedList<>();
LinkedList <String> map;
while ((column = reader.readNext()) != null) {
map = new LinkedList<String>();
map.add(column[0]);
myList.add(String.valueOf(map).replace("[","").replace("]",""));
//myList.add(String.valueOf(map));
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why i do it in another thread? Because I want to have a chance to stopp mailing process by clicking in stop button and killing a new thread.

Imagebutton overlays after zooming- how to fix?

I have a problem. Right now I have two imagebuttons. When I click on the first button to increase the image the button next to it is still availble in the screen. I dont know to set the selected screen in the foreground?
Can anybody help?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bewerbung);
final View thumb1View = findViewById(R.id.thumb_button_1);
thumb1View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
zoomImageFromThumb(thumb1View, R.drawable.anschreiben1);
}
});
final View thumb2View = findViewById(R.id.thumb_button_2);
thumb2View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
zoomImageFromThumb(thumb2View, R.drawable.anschreiben2);
}
});
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
private void zoomImageFromThumb(final View thumbView, int imageResId) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
final ImageView expandedImageView = (ImageView) findViewById(
R.id.expanded_image);
expandedImageView.setImageResource(imageResId);
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container)
.getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
> (float) startBounds.width() / startBounds.height()) {
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
AnimatorSet set = new AnimatorSet();
set
.play(ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
startScale, 1f)).with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator
.ofFloat(expandedImageView, View.X, startBounds.left))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.Y, startBounds.top))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.SCALE_X, startScaleFinal))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
}

Java fx frop drag and drop issue

How to do drag and drop within one listview
I have only one list view (Ed. "player")
My requirement is to move up and down in the same player list
Please find the code i have used
(Not: I am using jdk 1.7 with default javafx)
Example:(player = listView)
listView.setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Dragboard dragBoard = listView.startDragAndDrop(TransferMode.MOVE);
ClipboardContent content = new ClipboardContent();
content.putString(listView.getSelectionModel().getSelectedItem().getValue());
dragBoard.setContent(content);
}
});
listView.setOnDragDone(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragDone left");
}
});
listView.setOnDragEntered(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragEntered left");
}
});
listView.setOnDragExited(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragExited left");
listView.setBlendMode(null);
}
});
listView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragOver left");
dragEvent.acceptTransferModes(TransferMode.MOVE);
}
});
listView.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
String context = dragEvent.getDragboard().getString();
dragEvent.setDropCompleted(true);
}
}
});
I am new to javafx
Would you please help on this regard
Don't register the drag handlers on the ListView: you will have no way of knowing which cells the drag started and ended on. Instead, you need to register the handlers on the cells. The details get a little tricky, but the basic idea is to create a cell factory in which you create the custom cells; here you can set up the drag and drop handlers.
Here's an example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Callback;
public class DragAndDropListView extends Application {
#Override
public void start(Stage primaryStage) {
final ListView<String> listView = new ListView<>();
for (int i=1; i<=20; i++) {
listView.getItems().add("Item "+i);
}
final IntegerProperty dragFromIndex = new SimpleIntegerProperty(-1);
listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> lv) {
final ListCell<String> cell = new ListCell<String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(item);
}
}
};
cell.setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (! cell.isEmpty()) {
dragFromIndex.set(cell.getIndex());
Dragboard db = cell.startDragAndDrop(TransferMode.MOVE);
ClipboardContent cc = new ClipboardContent();
cc.putString(cell.getItem());
db.setContent(cc);
// Java 8 only:
// db.setDragView(cell.snapshot(null, null));
}
}
});
cell.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
if (dragFromIndex.get() >= 0 && dragFromIndex.get() != cell.getIndex()) {
event.acceptTransferModes(TransferMode.MOVE);
}
}
});
// highlight drop target by changing background color:
cell.setOnDragEntered(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
if (dragFromIndex.get() >= 0 && dragFromIndex.get() != cell.getIndex()) {
// should really set a style class and use an external style sheet,
// but this works for demo purposes:
cell.setStyle("-fx-background-color: gold;");
}
}
});
// remove highlight:
cell.setOnDragExited(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
cell.setStyle("");
}
});
cell.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
int dragItemsStartIndex ;
int dragItemsEndIndex ;
int direction ;
if (cell.isEmpty()) {
dragItemsStartIndex = dragFromIndex.get();
dragItemsEndIndex = listView.getItems().size();
direction = -1;
} else {
if (cell.getIndex() < dragFromIndex.get()) {
dragItemsStartIndex = cell.getIndex();
dragItemsEndIndex = dragFromIndex.get() + 1 ;
direction = 1 ;
} else {
dragItemsStartIndex = dragFromIndex.get();
dragItemsEndIndex = cell.getIndex() + 1 ;
direction = -1 ;
}
}
List<String> rotatingItems = listView.getItems().subList(dragItemsStartIndex, dragItemsEndIndex);
List<String> rotatingItemsCopy = new ArrayList<>(rotatingItems);
Collections.rotate(rotatingItemsCopy, direction);
rotatingItems.clear();
rotatingItems.addAll(rotatingItemsCopy);
dragFromIndex.set(-1);
}
});
cell.setOnDragDone(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
dragFromIndex.set(-1);
listView.getSelectionModel().select(event.getDragboard().getString());
}
});
return cell ;
}
});
BorderPane root = new BorderPane();
root.setCenter(listView);
Scene scene = new Scene(root, 250, 400);
scene.getStylesheets().add(getClass().getResource("drag-and-drop-list.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This will enable you to drag any element and drop it onto any other. For example dragging the third item in the list
and dropping it on the first item results in this:
In Java 8 you can also add the line
db.setDragView(cell.snapshot(null, null));
to the setOnDragDetected(...) method to get a better visual on the drag.

Java Painting issues

I need help with a "paint" program. I've got the GUI established, but I'm having issues with the actual drawing portion of the program. Everything I draw disappears immediately after I draw it, and I can't figure out why.
Here is what I have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPaint extends JFrame implements ActionListener, MouseListener, MouseMotionListener {
int x, y, x2, y2;
private int select = 0;
private Graphics g;
private PaintPanel DrawPanel = new PaintPanel(this);
private JPanel ButtonPanel = new JPanel();
private JTextArea Draw = new JTextArea(20,20);
private JButton jbtRed = new JButton("Red");
private JButton jbtGreen = new JButton("Green");
private JButton jbtBlue = new JButton("Blue");
private JButton jbtErase = new JButton("Eraser");
private JButton jbtClear = new JButton("Clear");
PaintPanel l=new PaintPanel(this);
public JPaint(){
super("Java Paint");
setSize(480,320);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//build draw panel
DrawPanel.setBackground(Color.WHITE);
add(DrawPanel, BorderLayout.CENTER);
DrawPanel.setVisible(true);
//build button panel
ButtonPanel.add(jbtRed);
ButtonPanel.add(jbtGreen);
ButtonPanel.add(jbtBlue);
ButtonPanel.add(jbtErase);
ButtonPanel.add(jbtClear);
add(ButtonPanel, BorderLayout.SOUTH);
ButtonPanel.setVisible(true);
jbtRed.addActionListener(this);
jbtGreen.addActionListener(this);
jbtBlue.addActionListener(this);
jbtErase.addActionListener(this);
jbtClear.addActionListener(this);
DrawPanel.addMouseMotionListener(this);
DrawPanel.addMouseListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbtRed){
DrawPanel.setToolTipText("Color set to 'Red'");
select = 1;
}
if(e.getSource() == jbtGreen){
DrawPanel.setToolTipText("Color set to 'Green'");
}
if(e.getSource() == jbtBlue){
DrawPanel.setToolTipText("Color set to 'Blue'");
}
if(e.getSource() == jbtErase){
DrawPanel.setToolTipText("Erase Selected");
}
if(e.getSource() == jbtClear){
DrawPanel.setToolTipText("Drawing cleared");
}
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
DrawPanel.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
DrawPanel.repaint();
}
}
class PaintPanel extends JPanel
{
JPaint p;
PaintPanel(JPaint in){
p=in;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// clear the screen
g.setColor(Color.white);
g.setColor(Color.RED);
g.drawLine(p.x, p.y, p.x2, p.y2);
p.x2 = p.x;
p.y2 = p.y;
}
}
class Run_JPaint {
public static void main(String[] args){
JPaint P = new JPaint();
P.setVisible(true);
}
}
You would probably want to remove the following line of code:
super.paintComponent(g);
from inside your PaintPanel class. Otherwise with each draw command your GUI resets the screen.
Good Luck!

Resources