I recently meet a bug that AJAX can't connect to Spring Boot. The resources/draw/index.html:
function saveTagForPart(imageID, x1, x2, y1, y2, description){
$.ajax({
type:"POST",
url:"/workplace/part/save",
dataType:"json",
data:{
imageID : imageID,
x1: x1,
x2: x2,
y1: y1,
y2: y2,
description : description
},
success : function (data) {
if(data.success){
alert("Success saved for part picture !");
}
else
alert("Error savedd for part picture !");
},
error : function () {
alert("Network warning for saving part picture !");
}
});}
var draw_tag = function () {
var tagX = startX<endX?startX:endX;
var tagY = startY<endY?startY:endY;
context.fillStyle = "black";
context.font = "20px Verdana";
context.textAlign = "center";
context.fillText($('#label-tag').val(),tagX,tagY);
var s= $('.canvas_container').css('background').substring(0).search("images/");
var e= $('.canvas_container').css('background').substring(0).search(".png");
var imageID = $('.canvas_container').css('background').substring(s+7,e);
saveTagForPart(imageID, startX, endX, startY, endY, $('#label-tag').val());};
In Spring Boot TagController.java:
#RestController("/workplace/part/")
public class TagPartController {
TagPartService tagPartService = new TagPartServiceImpl();
#RequestMapping(value = "/save", method = RequestMethod.POST)
#ResponseBody
public Response<Boolean> saveTagPart(String imageID, double x1, double x2, double y1, double y2, String description) throws IOException{
System.out.println("Get saved");
System.out.println(imageID);
return tagPartService.saveTagPart(imageID, x1, x2, y1, y2, description);
}
I try to check whether the URL, HTTP, or the data itself, but it all occurs right.
Map your url pattern with #RequestMapping instead of #RestController.
#RestController
#RequestMapping("/workplace/part/")
public class TagPartController {
TagPartService tagPartService = new TagPartServiceImpl();
#RequestMapping(value = "/save", method = RequestMethod.POST)
#ResponseBody
public Response<Boolean> saveTagPart(String imageID, double x1, double x2, double y1, double y2, String description) throws IOException{
System.out.println("Get saved");
System.out.println(imageID);
return tagPartService.saveTagPart(imageID, x1, x2, y1, y2, description);
}
Related
I'm trying to use a polygon shaped button in Java. I found this code for this purpose:
package testklassen;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PolygonButton extends JButton {
private Polygon shape;
public PolygonButton(int[] x, int[] y) {
this.shape = new Polygon();
this.initialize(x, y);
}
protected void initialize(int[] x, int[] y) {
Point p1, p2, p3, p4, p5;
this.setSize(90, 120);
p1 = new Point(x[0], y[0]);
p2 = new Point(x[1], y[1]);
p3 = new Point(x[2], y[2]);
p4 = new Point(x[3], y[3]);
p5 = new Point(x[4], y[4]);
this.shape.addPoint((int) Math.round(p1.getX()),
(int) Math.round(p1.getY()));
this.shape.addPoint((int) Math.round(p2.getX()),
(int) Math.round(p2.getY()));
this.shape.addPoint((int) Math.round(p3.getX()),
(int) Math.round(p3.getY()));
this.shape.addPoint((int) Math.round(p4.getX()),
(int) Math.round(p4.getY()));
this.shape.addPoint((int) Math.round(p5.getX()),
(int) Math.round(p5.getY()));
this.setMinimumSize(this.getSize());
this.setMaximumSize(this.getSize());
this.setPreferredSize(this.getSize());
}
// Hit detection
public boolean contains(int x, int y) {
return this.shape.contains(x, y);
}
// Draw Button
protected void paintComponent(Graphics g) {
Graphics2D gCopy = (Graphics2D) g.create();
gCopy.fillPolygon(this.shape);
}
}
To test this, I build a simple frame containing a PolygonButton and a normal Button:
package testklassen;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameForPolygonButton extends JFrame {
int[] x = {0, 50, 100, 100, 0};
int[] y = {0, 50, 0, 100, 100};
PolygonButton polygonButton = new PolygonButton(x, y);
JButton button = new JButton();
public FrameForPolygonButton() {
super();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 530;
int frameHeight = 400;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);
setVisible(true);
button.setBounds(200, 200, 50, 50);
cp.add(button);
//polygonButton.setBorder(null);
cp.add(polygonButton);
}
public static void main(String[] args) {
new FrameForPolygonButton();
}
}
That's how it looks like when starting. And that is exactly what I want.
But when I hover over the other JButton and then hover back over the PolygonButton
a picture of the JButton appears on the PolygonButton
Does anyone know, how I can avoid this?
I found out a solution for this problem. But I still don't know, why this was happening in the first place. If someone does know, I would be interested.
The solution, that worked vor me was to add this line:
polygonButton.setOpaque(false);
This is the code I made to attempt to calculate the perimeter and area of a rectangle.
public class Rectangle
{
public static void main (String [ ] args)
private double side1;
private double side2;
new Rectangle( )
{
This is where I get the first error
side1 = 1;
side2 = 1;
}
public Rectangle (double s1, double s2)
{
side1 = s1;
side2 = s2;
}
public double computePerimeter()
{
double perimeter;
perimeter = (side1 * 2) + (side2 *2);
return perimeter;
}
public double computeArea()
{
double area;
area = side1 * side2;
return area;
}
public double getSide1()
{
return side1;
}
public double getSide2()
{
return side2;
}
public void setSides(int firstSide, int secondSide)
{
side1 = firstSide;
side2 = secondSide;
}
public String toString()
{
System.out.println("Area is " + area);
System.out.println("Perimeter is " + perimeter);
}
{
Scanner scan = new Scanner(System.in);
int sideOne = scan.nextInt();
side1 = sideOne;
int sideTwo = scan.nextInt();
side2 = sideTwo;
computePerimeter();
computeArea();
}
This is where I keep getting the other two errors
}
}
I keep getting this message, but after line 10 I have a { and after line 67 a }. I'm just pretty confused.
"3 errors found:File: C:\Users\jrader\Desktop\GridWorldCode\projects\firstProject\Rectangle.java [line: 10] Error: Syntax error on token "{", { expected after this token [line: 67] Error: Syntax error, insert "}" to complete ClassBody [line: 67] Error: Syntax error, insert ";" to complete Statement"
This is a class definition so there is no main method, only constructors and method declarations. I realized my mistake.
I'm trying to mimic an iOS UICollectionView for hard-coded data. Really I just need to display 5 squares in a grid made of 2 columns and 3 rows (last one being half emp... full)
The width of each column should be half the screen, which is done using the Star (*). And I need the height to always be a little bit smaller than the width. The idea is to have thick rectangles.
Right now the Grid is inside a scrollview, I'm not sure that's relevant but we never know. I'm doing this so smaller phones will always be able to scroll through the grid, while others might just have blank space.
I've been fiddling aroudn trying to get the screen size or the column width. I can neither get the absolute value of my column width or my screenwidth at all (always -1 !?). I can easily get the Star value of my grid items, which is 1, but I would really need just the frame size, the double value, so I can just resize my grid in the constructor of my view and give it an absolute value.
Questions :
How do I get my column absolute width? Or how do I set my row height to a column-width-related value ?
If no possible, how do I get the screen width, so I can do the horrible rowheight = screenWdith/2 - padding ?
Maybe there is a very simple other way that makes this process trivial?
Or is this at all possible?
I will go with answers #2, get the screen width and height, you'll need a dependency service to do that you will need something like this:
interface IScreen
{
double Width { get; }
double Height { get; }
double convertPx(int px);
string locationName(double latitude, double longitude);
Task<string> locationNameAsync(double latitude, double longitude);
string Version { get; }
void ShowAlertMessage(string aTitle, string aMessage);
}
Android:
class Screen_Android : Java.Lang.Object, IScreen
{
public Screen_Android() { }
public double Width
{
get
{
var ctx = Forms.Context;
var metrics = ctx.Resources.DisplayMetrics;
return (ConvertPixelsToDp(metrics.WidthPixels));
}
}
public double Height
{
get
{
var ctx = Forms.Context;
var metrics = ctx.Resources.DisplayMetrics;
return (ConvertPixelsToDp(metrics.HeightPixels));
}
}
private static int ConvertPixelsToDp(float pixelValue)
{
var ctx = Forms.Context;
var dp = (int)((pixelValue) / ctx.Resources.DisplayMetrics.Density);
return dp;
}
public double convertPx(int px)
{
var ctx = Forms.Context;
//var dp = (int)((px) / ctx.Resources.DisplayMetrics.Density);
//return (int)((dp * ctx.Resources.DisplayMetrics.Density) + 0.5);
double density = ctx.Resources.DisplayMetrics.Density;
if (density >= 4.0)
{
//"xxxhdpi";
return px * 4;
}
if (density >= 3.0 && density < 4.0)
{
//"xxhdpi";
return px * 3;
}
if(density >= 2.0)
{
//xhdpi
return px * 2;
}
if(density >= 1.5 && density < 2.0)
{
//hdpi
return px * 1.5;
}
if(density >= 1.0 && density < 1.5)
{
//mdpi
return px * 1;
}
return px;
//return (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, px, ctx.Resources.DisplayMetrics);
//var resources = ctx.Resources;
//var metrics = resources.DisplayMetrics;
//int dp = px * ((int)metrics.DensityDpi / 160);
//return dp;
}
public string locationName(double latitude, double longitude)
{
//List<Address> addresses;
Geocoder geocoder = new Geocoder(Forms.Context, Locale.Default);
try
{
var addresses = geocoder.GetFromLocation(latitude, longitude, 10);
if (addresses.All(item => item == null)) return "";
string address = addresses[0].GetAddressLine(0);
string city = addresses[0].GetAddressLine(1);
string country = addresses[0].GetAddressLine(2);
return address + " " + city + " " + country;
}
catch
{
return "";
}
}
public string Version
{
get { throw new NotImplementedException(); }
}
public void ShowAlertMessage(string aTitle, string aMessage)
{
Toast.MakeText(Forms.Context, aMessage, ToastLength.Short).Show();
}
public System.Threading.Tasks.Task<string> locationNameAsync(double latitude, double longitude)
{
throw new NotImplementedException();
}
iOS:
public class Screen_iOS : IScreen
{
public double Width
{
get
{
return UIScreen.MainScreen.Bounds.Width;
}
}
public double Height
{
get
{
return UIScreen.MainScreen.Bounds.Height;
}
}
public double convertPx(int px)
{
throw new NotImplementedException();
}
public string locationName(double latitude, double longitude)
{
string locationName = "";
CLLocation c = new CLLocation(Math.Round(latitude, 2), Math.Round(longitude, 2));
CLGeocoder geocoder = new CLGeocoder();
geocoder.ReverseGeocodeLocation(c, (placemarks, error) =>
{
if ((placemarks != null) && (placemarks.Length > 0))
locationName = placemarks[0].Name + placemarks[0].PostalCode + placemarks[0].AdministrativeArea + placemarks[0].Country;
});
return locationName;
}
public string Version
{
get
{
NSObject ver = NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"];
return ver.ToString();
}
//get { throw new NotImplementedException(); }
}
public void ShowAlertMessage(String aTitle, string aMessage)
{
UIAlertView error = new UIAlertView(aTitle, aMessage, null, "OK" , null);
error.Show();
}
public async Task<string> locationNameAsync(double latitude, double longitude)
{
string locationName = "";
CLLocation loc = new CLLocation(latitude, longitude);
CLGeocoder geocoder = new CLGeocoder();
CLPlacemark[] r = null;
var task = Task.Factory.StartNew(() =>
{
r = geocoder.ReverseGeocodeLocationAsync(loc).Result;
Console.WriteLine("it ran! {0}", r.Length);
});
task.Wait(TimeSpan.FromSeconds(10));
if ((r != null) && (r.Length > 0))
locationName = r[0].Name + r[0].PostalCode + r[0].AdministrativeArea + r[0].Country;
return locationName;
}
}
I'm pulling my hair out trying the figure this out. I have a simple button, that checks for the mouse to be over, and then changes the texture if it is. It works fine. However, when I add a camera into the mix, it breaks everything. I've tried transforming both the mouse and rectangle I use for bounding-box collision, and it won't work. Here's my code for the button:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace x.Graphics.UI
{
public enum ButtonStates
{
Normal,
Hover,
Pressed
}
public delegate void ButtonPress();
public class Button
{
public Texture2D Texture
{
get
{
Texture2D result = null;
switch (ButtonState)
{
case ButtonStates.Normal:
result = NormalTexture;
break;
case ButtonStates.Hover:
result = HoverTexture;
break;
case ButtonStates.Pressed:
result = DownTexture;
break;
}
return result;
}
}
public Vector2 Position { get; set; }
public event ButtonPress ButtonPressed;
public ButtonStates ButtonState { get; set; }
public Rectangle CollisionRect { get; set; }
private Texture2D NormalTexture;
private Texture2D HoverTexture;
private Texture2D DownTexture;
private MouseState mouseState;
private MouseState previousMouseState;
public Button(Texture2D normalTexture, Texture2D hoverTexture, Texture2D downTexture,
Vector2 position)
{
NormalTexture = normalTexture;
HoverTexture = hoverTexture;
DownTexture = downTexture;
Position = position;
mouseState = Mouse.GetState();
previousMouseState = mouseState;
CollisionRect = new Rectangle((int)Position.X, (int)Position.Y,
Texture.Width,
Texture.Height);
}
public void Update (MouseState currentState)
{
mouseState = currentState;
if (CollisionRect.Contains(new Point(mouseState.X, mouseState.Y)))
{
if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
{
ButtonState = ButtonStates.Pressed;
ButtonPressed();
}
else
ButtonState = ButtonStates.Hover;
}
else
ButtonState = ButtonStates.Normal;
}
public void Update(MouseState currentState, Camera camera)
{
Vector2 mouse = new Vector2(mouseState.X, mouseState.Y);
mouse = Vector2.Transform(mouse, camera.InverseTransform);
CollisionRect = CalculateTransformedBoundingBox(CollisionRect, c.InverseTransform);
Console.WriteLine("Rectangle[X: {0}, y: {1}], Mouse:[X: {2}, Y: {3}]", CollisionRect.X, CollisionRect.Y, mouse.X, mouse.Y);
if (CollisionRect.Contains(new Point((int)mouse.X, (int)mouse.Y)))
{
if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
{
ButtonState = ButtonStates.Pressed;
ButtonPressed();
}
else
ButtonState = ButtonStates.Hover;
}
else
ButtonState = ButtonStates.Normal;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, null, Color.White, 0.0f,
Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f);
}
private Rectangle CalculateTransformedBoundingBox(Rectangle local, Matrix toWorldSpace)
{
Vector2 leftTop = new Vector2(local.Left, local.Top);
Vector2 rightTop = new Vector2(local.Right, local.Top);
Vector2 leftBottom = new Vector2(local.Left, local.Bottom);
Vector2 rightBottom = new Vector2(local.Right, local.Bottom);
Vector2.Transform(ref leftTop, ref toWorldSpace,
out leftTop);
Vector2.Transform(ref rightTop, ref toWorldSpace,
out rightTop);
Vector2.Transform(ref leftBottom, ref toWorldSpace,
out leftBottom);
Vector2.Transform(ref rightBottom, ref toWorldSpace,
out rightBottom);
// Find the minimum and maximum extents of the
// rectangle in world space
Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
Vector2.Min(leftBottom, rightBottom));
Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
Vector2.Max(leftBottom, rightBottom));
// Return that as a rectangle
return new Rectangle((int)min.X, (int)min.Y,
(int)(max.X - min.X), (int)(max.Y - min.Y));
}
}
}
And my code for the camera:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace x.Graphics
{
public class Camera
{
protected float _zoom;
protected Matrix _transform;
protected Matrix _inverseTransform;
protected Vector2 _pos;
protected float _rotation;
protected Viewport _viewport;
protected MouseState _mState;
protected KeyboardState _keyState;
protected Int32 _scroll;
public float Zoom
{
get { return _zoom; }
set { _zoom = value; }
}
public Matrix Transform
{
get { return _transform; }
set { _transform = value; }
}
public Matrix InverseTransform
{
get { return _inverseTransform; }
}
public Vector2 Pos
{
get { return _pos; }
set { _pos = value; }
}
public float Rotation
{
get { return _rotation; }
set { _rotation = value; }
}
public Camera(Viewport viewport)
{
_zoom = 1.0f;
_scroll = 1;
_rotation = 0.0f;
_pos = Vector2.Zero;
_viewport = viewport;
}
public void Update()
{
Input();
MathHelper.Clamp(_zoom, 0.01f, 10.0f);
_rotation = ClampAngle(_rotation);
_transform = Matrix.CreateRotationZ(_rotation) *
Matrix.CreateScale(new Vector3(_zoom, _zoom, 1)) *
Matrix.CreateTranslation(_pos.X, _pos.Y, 0);
_inverseTransform = Matrix.Invert(_transform);
}
protected virtual void Input()
{
_mState = Mouse.GetState();
_keyState = Keyboard.GetState();
//Check Move
if (_keyState.IsKeyDown(Keys.A))
{
_pos.X += 10f;
}
if (_keyState.IsKeyDown(Keys.D))
{
_pos.X -= 10f;
}
if (_keyState.IsKeyDown(Keys.W))
{
_pos.Y -= 10f;
}
if (_keyState.IsKeyDown(Keys.S))
{
_pos.Y += 10f;
}
}
protected float ClampAngle(float radians)
{
while (radians < -MathHelper.Pi)
{
radians += MathHelper.TwoPi;
}
while (radians > MathHelper.Pi)
{
radians -= MathHelper.TwoPi;
}
return radians;
}
}
}
I'm not 100% sure what's wrong, but the mouse position only changes when I press a button. I'm really confused, I've never worked with cameras before. Any help would be really appreciated. Thanks!
UPDATE:
It detects the mouse as being over the button before I try and move the camera. After that, the coorindates of the rectangle are continually incremented.
Don't transform bounding box... is easy to transform mouse coordinates ... ;)
Use the inverse transform of your camera matrix to transform mouse coords to the same space of your bounding box.
public class circle
{
double circle1;
double Xvalue;
double Yvalue;
double radius;
public double area = (3.14*(this.radius * this.radius));
public double getArea ()
{
return area;
}
}
//this is my second class that will create the objects
public class tester
{
public static void main(String args [])
{
circle circle1 = new circle();
circle1.Xvalue = 1;
circle1.Yvalue = 2;
circle1.radius = 4;
System.out.println(getArea());
//im not too sure why the print statement won't print the method getArea.
}
}
You need System.out.println(circle1.getArea());, otherwise it's trying to find a method called getArea() in your Tester class which has no such method.
Also, your code will always return an area of 0. This is because of how you initialize your data:
When you create your new circle object it creates xValue and because it is a primitive type (double instead of Double) it defaults to giving it a value of 0 (because it must have some value).
So when it gets down to where you define the area variable at that moment (since it is still creating your object, it does (area = 3.14*(0.0 * 0.0)) which is going to be 0.
What you really want is something more like this:
public class Circle {
double Xvalue;
double Yvalue;
double radius;
public Circle(double xValue, double yValue, double radius) {
this.xValue = xValue;
this.yValue = yValue;
this.radius = radius;
}
public double getArea ()
{
return 3.1415926*(this.radius * this.radius);
}
}
public class Tester
{
public static void main(String[] args)
{
Circle circle1 = new Circle(1, 2, 4);
System.out.println(circle1.getArea());
//im not too sure why the print statement won't print the method getArea.
}
}