I am trying to build a calculator that will give me the calculation for width length and Area and perimeter. Now where I'm stuck, once I label the text box ( txtWidth) and then I click on it to bring up the code editor what do I put in under the handler. Second question how do I enter the math for them. Like I know that to get the area I just do widthlength and for perimeter it's 2*width + 2*length. And I also need to add fractional decimal entries like 10.5 and 20.65. I hope this gives more insight to what I'm trying to do.
Assuming you're using C#... add two labels (lblArea & lblPerimeter) and a button (btnCalculate), and add an event for the button (double-click on it):
Here's your homework:
private void CalculateDisplayInfo()
{
double len = 0.0;
if (!double.TryParse(txtLength.Text, out len))
{
MessageBox.Show(this, "Invalid Length Input", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
double width = 0.0;
if (!double.TryParse(txtWidth.Text, out width))
{
MessageBox.Show(this, "Invalid Width Input", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
lblArea.Text = (width * len).ToString();
lblPerimeter.Text = (2 * (width + len)).ToString();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
CalculateDisplayInfo();
}
Related
I have a stackPane, filled with a Circle and a couple of lines.
I want to display a tooltip while hovering over the StackPane and the tooltip should contain the X/Y coords of the mouse.
I know how to get the Coords of the mouse, but I'm unable to find a way of showing the tool tip.
Can any of ou guys help me with that?..
Anshul Parashar's answer probably works, but ToolTip also has a 'installation' static helper method to handle display on hover.
Assuming n is a Node:
Tooltip tp = new Tooltip("at stack tool");
Tooltip.install(n, tp);
try this...
Tooltip tp = new Tooltip("at stack tool");
stackpane.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
Node node =(Node)t.getSource();
tp.show(node, FxApp.stage.getX()+t.getSceneX(), FxApp.stage.getY()+t.getSceneY());
}
});
I solved it like this:
Tooltip mousePositionToolTip = new Tooltip("");
gridPane.setOnMouseMoved(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
String msg = "(x: " + event.getX() + ", y: " + event.getY() + ")\n(sceneX: "
+ event.getSceneX() + ", sceneY: " + event.getSceneY() + ")\n(screenX: "
+ event.getScreenX() + ", screenY: " + event.getScreenY() + ")";
mousePositionToolTip.setText(msg);
Node node = (Node) event.getSource();
mousePositionToolTip.show(node, event.getScreenX() + 50, event.getScreenY());
}
});
It will show a ToolTip in right of your mouse-pointer. You can replace your StackPane with gridPane in my code and it should work. But i didn't test it.
The prior solution is OK, but it gets called for every mouse movement.
Instead, here's a solution that just gets called once when it's about to display the tooltip:
The JavaFx 8 Tooltip provides event callbacks just before and after the tooltip displays (and just before and after it's taken down). So, install an event handler for the "just before" call like this below. The window event doesn't give you the current mouse coordinates, unfortunately, but you can still get them at any time with java.awt.MouseInfo.getPointerInfo().getLocation() as below.
Tooltip t = new Tooltip();
Tooltip.install(yournode, t);
t.setOnShowing(ev -> {// called just prior to being shown
Point mouse = java.awt.MouseInfo.getPointerInfo().getLocation();
Point2D local = yournode.screenToLocal(mouse.x, mouse.y);
// my app-specific code to get the chart's yaxis value
// then set the text as I want
double pitch = yaxis.getValueForDisplay(local.getY()).doubleValue();
double freq = AudioUtil.pitch2frequency(pitch);
t.setText(String.format("Pitch %.1f: %.1f Hz %.1f samples", pitch, freq, audio.rate / freq));
});
Works for me.
I'm working on a program that reads in some images (.jpg) and text from source files and assembling them into a single PDF. I know processing probably isn't the best language to do it in, but its the only one I know how to do it in. Anyway, I am having an issue where processing calls setup two times. I've seen that this issue is resolved when size() is the first line within setup, however I can't have that happen, because I have to read in and store all my data, find the width of the widest image, then make sure its tall enough to accommodate pages with more than one image, and add text before I can decide on how wide and tall my window is. I am looking for suggestions as to how I might structure the code so that I can get all my information without having to call setup twice, because that's causing my PDF to contain two copies of all the data. I've included setup if it helps anyone. Thanks!
void setup(){
font = loadFont("TimesNewRomanPSMT-20.vlw");
File clientsFolder = new File("C:/Users/[my name]/Documents/Processing/ExerciseProgram/Clients");
clients = clientsFolder.listFiles();
for(File x : clients){
println(x.getName());
}
//test files to see if they end in .txt, and have a matching .pdf extension that is newer
String nextClient = needPdf();
File nextClientData = new File("C:/Users/[my name]/Documents/Processing/ExerciseProgram/Clients/" + nextClient);
//println(nextClientData.getName());
//open the file for reading
//setup can't throw the exception, and it needs it, so this should take care of it
try{
Scanner scan = new Scanner(nextClientData);
while(scan.hasNextLine() ){
exercises.add(scan.nextLine());
}
//println(exercises.toString());
printedData = new Exercise[exercises.size()];
println(exercises.size());
for(int i = 0; i < exercises.size(); i++){
printedData[i] = new Exercise((String)exercises.get(i));
}
//count the width and height
int w = 0, h = 0;
for(Exercise e: printedData){
if(e.getWidest() > w){
w = e.getWidest();
}
if(e.getTallest() > h){
h = e.getHeight();
}
}
//and finally we can create the freaking window
// this cuts the .txt off
size(w, h, PDF, "C:/Users/[my name]/Desktop/" + nextClient.substring(0, nextClient.length() - 4) + ".pdf");
}catch (FileNotFoundException e){
println("Unknown error in PApplet.setup(). Exiting.");
println(e.getMessage() );
exit();
}
}
How about moving all these functions to be done before setup()? Although processing usually complains that you are "mixing static and active modes", this hack seems to work at processing 2.0.1:
int i = beforeSetup();
int szX,szY;
int beforeSetup() {
println("look! I am happening before setup()!!");
szX = 800;
szY = 600;
return 0;
}
void setup() {
size(szX,szY);
println("awww");
}
You are essentially calling a function to fill int i just as a hack to run all the functions you want, thus having to compute whatever you want before having to set the window size.
perhaps you can resize your window after calcs are done? Once I made this sketch to see how resizing would work, it is expecting an image file, see if it can help you...
//no error handling for non image files!
PImage img;
int newCanvasWidth = MIN_WINDOW_WIDTH; // made global to use in draw
int newCanvasHeight = MIN_WINDOW_HEIGHT;
java.awt.Insets insets; //"An Insets object is a representation of the borders of a container"
//from http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Insets.html
void setup()
{
size(200, 200); // always first line
frame.pack(); insets = frame.getInsets();
frame.setResizable(true);
/// for debuging, system depende`nt, at least screen is...
print("MIN_WINDOW_WIDTH = " + MIN_WINDOW_WIDTH);
print(" MIN_WINDOW_HEIGHT = " + MIN_WINDOW_HEIGHT);
print(" screenWidth = " + displayWidth);
println(" screenHeight = " + displayHeight);
}
void draw()
{
if (img != null)
{
image(img, 0, 0, newCanvasWidth, newCanvasHeight);
}
}
void getImageAndResize(File selected)
{
String path = selected.getAbsolutePath();
if (path == null)
{
println ("nono :-|");
}
else
{
img = loadImage(path);
// a temp variable for readability
int widthInsets =insets.left + insets.right;
int heightInsets =insets.top + insets.bottom;
// constrain values between screen size and minimum window size
int newFrameWidth = constrain(img.width + widthInsets, MIN_WINDOW_WIDTH, displayWidth);
int newFrameHeight = constrain(img.height + heightInsets, MIN_WINDOW_HEIGHT, displayHeight -20);
// Canvas should consider insets for constraining? I think so...
newCanvasWidth = constrain(img.width, MIN_WINDOW_WIDTH - widthInsets, displayWidth - widthInsets);
newCanvasHeight = constrain(img.height, MIN_WINDOW_HEIGHT - heightInsets, displayHeight -20 - heightInsets);
// set canvas size to img size WITHOUT INSETS
setSize(newCanvasWidth, newCanvasHeight);
// set frame size to image + Insets size
frame.setSize(newFrameWidth, newFrameHeight);
//// for debuging
println(path);
println(" ");
print("imgW = " + img.width);
println(" imgH = " + img.height);
print("width+ins = " + widthInsets);
println(" height+ins = " + heightInsets);
print("nFrameW = " + newFrameWidth);
println(" nFrameH = " + newFrameHeight);
print("nCanvasw = " + newCanvasWidth);
println(" nCanvsH = " + newCanvasHeight);
println(" ------ ");
}
}
void mouseClicked()
{
img = null;
selectInput("select an image", "getImageAndResize" );
}
I am currently making a small application for a BMI calculation. The program compiles fine, but I get a run time error of
Format Exception Unhandled
in this line:
height = float.Parse(textBox1.Text);
The line is a part of the function:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
float height;
height = float.Parse(textBox1.Text);
height = height*height;
}
You haven't said what's in the text box when you parse it. Perhaps it's empty, or the user's typed something like "fred". You should always assume that the input could be invalid:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
float height;
if (!float.TryParse(textBox1.Text, out height))
{
// Indicate to the user that the input is invalid, and stop processing
// at this point. For example, you may want to highlight the textbox with
// a red box. Return at the end of the block.
}
// It parsed correctly: continue...
height = height*height;
...
}
(This would probably be structured slightly differently in an MVVM approach, but you'd still want to use float.TryParse to test the user input before accepting it.)
I was wondering on windows 7 there is the function that when your mouse hits the form left/right top it will auto size the window to half the screen. I am trying to do that with my MDI Child. Here is the code that I have, however the function does not work.
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Form1 f1 = new Form1();
if (e.X == f1.Width/2 - 30)
{
Form activeChild = this.ActiveMdiChild;
activeChild.Width = this.Width / 2;
activeChild.Height = this.Height;
activeChild.Dock = DockStyle.Left;
}
}
You might try doing that on the Move event of the actual child form. Handling the event based on a new instance of Form1 in any event won't work very well. Anyhow, here's some code as it would look inside the child. (Ugly, but it at least does something.)
private void SubForm_Move(object sender, EventArgs e)
{
if (Location.X <= 0)
{
Width = MdiParent.Width / 2;
Height = MdiParent.Height;
Location = new Point(0,0);
Dock = DockStyle.Left;
}
}
Im trying to get the direction of the vector pointing out of the camera, with respect to magnetic north. I'm under the impression that I need to use the values returned from getOrientation(), but I'm not sure what they represent. The values I get from getOrientation() don't change predictably when I change the orientation of the phone (rotating 90 degrees does not change values by 90 degrees). I need to know what the values returned by getOrientation() mean. What I have so far is written below:
package com.example.orientation;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;
public class Orientation extends Activity{
private SensorManager mSM;
private mSensorEventListener mSEL;
float[] inR = new float[16];
float[] outR= new float[16];
float[] I = new float[16];
float[] gravity = new float[3];
float[] geomag = new float[3];
float[] orientVals = new float[3];
final float pi = (float) Math.PI;
final float rad2deg = 180/pi;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSM = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSEL = new mSensorEventListener();
mSM.registerListener(mSEL,
mSM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
mSM.registerListener(mSEL,
mSM.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
private class mSensorEventListener implements SensorEventListener{
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {}
#Override
public void onSensorChanged(SensorEvent event) {
// If the sensor data is unreliable return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
return;
// Gets the value of the sensor that has been changed
switch (event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
gravity = event.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
geomag = event.values.clone();
break;
}
// If gravity and geomag have values then find rotation matrix
if (gravity != null && geomag != null){
// checks that the rotation matrix is found
boolean success = SensorManager.getRotationMatrix(inR, I, gravity, geomag);
if (success){
// Re-map coordinates so y-axis comes out of camera
SensorManager.remapCoordinateSystem(inR, SensorManager.AXIS_X,
SensorManager.AXIS_Z, outR);
// Finds the Azimuth and Pitch angles of the y-axis with
// magnetic north and the horizon respectively
SensorManager.getOrientation(outR, orientVals);
float azimuth = orientVals[0]*rad2deg;
float pitch = orientVals[1]*rad2deg;
float roll = orientVals[2]*rad2deg;
// Displays a pop up message with the azimuth and inclination angles
String endl = System.getProperty("line.separator");
Toast.makeText(getBaseContext(),
"Rotation:" +
outR[0] + " " + outR[1] + " " + outR[2] + endl +
outR[4] + " " + outR[5] + " " + outR[6] + endl +
outR[8] + " " + outR[9] + " " + outR[10] + endl +endl +
"Azimuth: " + azimuth + " degrees" + endl +
"Pitch: " + pitch + " degrees" + endl +
"Roll: " + roll + " degrees",
Toast.LENGTH_LONG).show();
} /*else
Toast.makeText(getBaseContext(),
"Get Rotation Matrix Failed", Toast.LENGTH_LONG).show();*/
}
}
}
}
I've looked at the documentation on the sensorManager class, but it hasn't helped solve this. If anyone could help me get meaning out of the this I would really appreciate it. I'm testing on a Nexus One running Android 2.1
Because I was new to android I was using toast to display the information on the screen. I changed it to just update text on a view and that seemed to fix it. I also figured out that what I assumed the orientVals actually were is correct. For what I need the roll is not used. Also didnt realize there was a way to convert from rad to deg built in so I just used that.
you can check out the logger application that displays raw values on the screen. In its description you'll find a link to the source code so that you can learn how it accesses the sensors.
HTH,
Daniele
You need to get the orientation of your device (Landscape/Portrait)
and make some compensation.
SensorManager.getOrientation(R, values);
mHeading = (int) Math.toDegrees(values[0]);
Display display =
((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int compensation = display.getRotation() * 90;
mHeading = mHeading+compensation;
I think you should have to use getInclination to get the direction instead of get orientation. as getRotationMatrix is calculating based on both gravity and geomagnetic feild and you will get the inlination from the magnetic field directly.
I Think you should change outR to inR in line getOrientation
boolean success = SensorManager.getRotationMatrix(inR, I, gravity, geomag);
if (success){
// Re-map coordinates so y-axis comes out of camera
SensorManager.remapCoordinateSystem(inR, SensorManager.AXIS_X,
SensorManager.AXIS_Z, outR);
// Finds the Azimuth and Pitch angles of the y-axis with
// magnetic north and the horizon respectively
**SensorManager.getOrientation(inR, orientVals);**