How to get int value from spinner - java

I'm using NetBeans 7.1 to code in Java. I have a JFrame where I have spinner with integer values on it, I want to know how to get the active value in the spinner, I mean, the one that the user picks when the program is running; to use it on another methods.

spinner.getValue() should do the trick. You can cast it to Integer, like
int value = (Integer) spinner.getValue();
Note from reggoodwin: You should also call spinner.commitEdit() prior to calling getValue() to ensure manually typed values with the editor are propagated to the model, otherwise you will only get the old value.
Hence, it should be something like below,
try {
spinner.commitEdit();
} catch ( java.text.ParseException e ) { .. }
int value = (Integer) spinner.getValue();

String value = getSpinner().getValue() + "";
Integer.parseInt(value)
My solution, this working for me...
Not work:
Integer.parseInt( getSpinner().getValue().toString()) //get object toString
I do not understand, but it works, I leave it in case anyone needs it.

String spinner = "catch Value";
Integer myint = (Integer) jSpinner1.getValue();
spinner = myint.toString();
jTextField1.setText(spinner);
This worked for me. Wanted to write the Integer value from jSpinner to a textfield.

Related

Handle long min value condition

When I ran a program, long min value is getting persisted instead of original value coming from the backend.
I am using the code:
if (columnName.equals(Fields.NOTIONAL)) {
orderData.notional(getNewValue(data));
As output of this, i am getting long min value, instead of original value.
I tried using this method to handle the scenario
public String getNewValue(Object data) {
return ((Long)data).getLong("0")==Long.MIN_VALUE?"":((Long)data).toString();
}
but doesn't work.
Please suggest
EDITED: I misread the code in the question; rereading it, I now get what the author is trying to do, and cleaned up the suggestion as a consequence.
(Long) data).getLong("0") is a silly way to write null, because that doesn't do anything. It retrieves the system property named '0', and then attempts to parse it as a Long value. As in, if you start your VM with java -D0=1234 com.foo.YourClass, that returns 1234. I don't even know what you're attempting to accomplish with this call. Obviously it is not equal to Long.MIN_VALUE, thus the method returns ((Long) data).toString(). If data is in fact a Long representing MIN_VALUE, you'll get the digits of MIN_VALUE, clearly not what you wanted.
Try this:
public String getNewValue(Object data) {
if (data instanceof Number) {
long v = ((Number) data).longValue();
return v == Long.MIN_VALUE ? "" : data.toString();
}
// what do you want to return if the input isn't a numeric object at all?
return "";

Comparing button Tag with String in android

I am working on an android project where it needs to get data from database as grid view (contains multiple buttons). I have already done up to that part. Now I need to compare those data with a given string.
Here, I have tagged the status from the database to the button before put it in to the grid view.
holder.btn.setTag(data.get(position).getStatus());
the following code has shown that how I am trying to compare those values.
String x = "NA";
String y = holder.btn.getTag().toString();
if (x.equals(y)) {
holder.btn.setEnabled(false);
}
But it is not working. Please Help me to solve this issue.
Additionally, in my database there is a column call status....it contains values such as A and NA (Available and Not Available). I have already got that values from data base and set it to the item objects array list call data. in that item object i have declared field call status and then I have assigned that data base values to that.
Thanks in advance.
The method getTag() returns an Object, not a String. So you have to cast it to a String when you retrieve it. Try this:
String x = "NA";
String y = (String) holder.btn.getTag();
if (x.equals(y)) {
holder.btn.setEnabled(false);
}
Also keep in mind that if you are originally setting the Tag with something other than a String, then you'll have to convert it to a String when you use getTag(). So, for example, if your line holder.btn.setTag(data.get(position).getStatus()); sets an int as the tag, you would have to do String y = (String) Integer.toString(holder.btn.getTag()); or something similar.
Maybe the problem is at line if getStatus() returns no string
holder.btn.setTag(data.get(position).getStatus());
You can try with
holder.btn.setTag(data.get(position).getStatus().toString());

Validate boolean true

I have a boolean inside a Checkbox and i want to validate if it is set to True.
So my entitie object looks kind of like this
#Validate("required,min=1")
private int Int1;
In my tml File (im using Tapestry 5.3.8) there is a Textfield which allows me to set a value for Int1
this works perfectly. If i put something else then an numeric number (or an int small 1) it shows me an error dialog.
but i can't figure out how to do that with a boolean. It needs to be checked an the user should get the same behauvior as with Int1 on a false entry.
Think of it like an Agree to the TOS checkbox which allways has to be checked to proceed.
Greetings Ilja
If I'm not mistaken a checkbox works with a boolean. So the following should achieve your result:
#Component(id = "agreeCheckbox")
private Checkbox agreeCheckbox;
#OnEvent(component = "agreeCheckbox", value = EventConstants.VALIDATE)
private void handleAgreeValidate(boolean agree) {
if(!agree) {
throw new ValidationException("Hey there! You have to agree or we can't do business with you.");
}
}
Disclaimer: I have not tested this code.

Typing Number Into JSpinner with Subclassed SpinnerListModel

I want to have a JSpinner that displays an non-patterened sequence of numbers (say, a sequence of prime numbers). This pattern is too complicated for a SpinnerNumberModel, so I decided to subclass SpinnerListModel. The constructor looks something like this:
public CustomSpinnerListModel() {
Vector<Integer> values = new Vector<Integer>();
values.add(1);
values.add(3);
values.add(5);
values.add(7);
this.setList(values);
}
This generates the model just fine and I can move through the values using the buttons on the JSpinner. However, typing a value in doesn't work. For instance, if the spinner is set to 3 and I type in 7, it remains at 3 (presumably because it doesn't think that 7 is a valid value). This works with the SpinnerNumberModel, so I'm not sure what's going on.
EDIT: I found out that if I save the numbers as string values, typing works. However, SpinnerNumberModel saves everything as Integers and that works too. So I'm not sure why my integers don't work, but SpinnerNumberModel's do.
I think the following solution is better than the suggestion to implement a Formatter, as it is not a formatting issue, but an issue of restricting the possible values, which should be the responsibility of the model. I had a similar problem and stumbling upon this threads solution, lead to a very ugly implementation. So hopefully what I came up with will keep you out of trouble.
This generates the model just fine and I can move through the values using the buttons on the JSpinner. However, typing a value in doesn't work. For instance, if the spinner is set to 3 and I type in 7, it remains at 3 (presumably because it doesn't think that 7 is a valid value). This works with the SpinnerNumberModel, so I'm not sure what's going on.
The Problem here is that setting a new model with setModel has the undocumented side effect of changing the JTextFieldEditor attribute depending on the type of the Model:
http://fuseyism.com/classpath/doc/javax/swing/JSpinner-source.html
By default, JSpinner uses a model of class SpinnerNumberModel with an editor of class DefaultNumberEditor. When you set the model to SpinnerListModel, it will instead use a ListEditor. In your case this is a bad choice, since it requires you to enter every prime number into a list to give it to the SpinnerListModel for input verification. Otherwise, as you pointed out, your input is ignored.
So the simple solution here is to subclass SpinnerNumberModel, which allows any number, instead of a specific list of values:
class PrimeNumberModel extends SpinnerNumberModel {
Object currentValue;
#Override
public Object getNextValue() {
return findNextPrimeFrom(currentValue);
}
#Override
public Object getPreviousValue() {
return findPreviousPrimeFrom(currentValue);
}
#Override
public void setValue(Object o) {
throwOnNonePrime(o); //Verify Input
super.setValue(o);
}
private void throwOnNonePrime(Object o) {
try {
int num = Integer.valueOf(o.toString());
if(!isPrime(num))
throw new IllegalArgumentException(o.toString());
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(o.toString());
}
}
}
I think you could do it with strings and then use a method to get the number.
like this:
Spinner1(){
String[] values={"1","3","5","7"};
SpinnerModel model=new SpinnerListModel(values);
JSpinner spinner=new JSpinner(model);
}
int getValue(Object obj){
int out=0;
return out=Integer.parseInt((String)obj);
}

Nightmare Class - floats/strings

This is my class reponsible for new item entries, and from the start it has been a complete nightmare, I can't seem to resolve the issues I am facing which are:
setStock(float) in Item cannot be applied to ()
Item entry:
private void writeItemRecord()
{
// Check to see if we can connect to database table
if ( DataBaseHandler.makeConnectionToitemDB() == -1)
{
JOptionPane.showMessageDialog (frame, "Unable to connect to database table (Item)");
}
else // Ok, so first read data from the text fields
{
// Read data from form and store data
String Itemname = ItemnameTxtField.getText();
String Itemcode = ItemcodeTxtField.getText();
String Description = DescriptionTxtField.getText();
String Unitprice = UnitpriceTxtField.getText();
String Style = StyleTxtField.getText();
String Finish = FinishTxtField.getText();
String Stock = StockTxtField.getText();
// Convert priceStr to a float
Float fvar = Float.valueOf(Unitprice);
float price = fvar.floatValue();
Float svar = Float.valueOf(Stock);
float stock = svar.floatValue();
// Create a Item oject
Item Item = new Item();
// Set the attributes for the Item object
Item.setItemname (Itemname);
Item.setItemcode (Itemcode);
Item.setDescription (Description);
Item.setUnitprice (price);
Item.setStock(stock);
Item.setStyle(Style);
Item.setFinish(Finish);
// Write Item record. Method writeToItemTable() returns
// 0 of OK writing record, -1 if there is a problem. I store
// the returned value in a variable called error.
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
Item.setStock(),
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address)
);
// Check if there is a problem writing the record, in
// which case error will contain -1
if (error == -1)
{
JOptionPane.showMessageDialog (frame, "Problem writing record to Item Table");
}
// Clear the form - actual method is coded below
clearForm();
// Close database connection. Report an error message
// if there is a problem.
if ( DataBaseHandler.closeConnection() == -1 )
{
JOptionPane.showMessageDialog (frame, "Problem closing data base conection");
}
}
} // End
Any help is much appreciated!
And item extracts:
public void setStock(float StockIn)
{
Stock = StockIn;
}
public float getStock()
{
return Stock;
}
For starters, adhere to Java naming conventions. Nothing except class/interface names is allowed to use CamelCase. Use lowerCamelCase. As for your "problem", you wrote
Item.setStock(),
so obviously it's giving you the error. It is also giving you the exact line number of the error, something that would obviously have helped us to diagnose your problem.
Solution: use Item.getStock() (i suppose, it's hard to tell). Calling Item.setStock at that position (as an argument to a method call) is meaningless anyway, given that setStock is a void method.
Java compiler errors come with a line number - pay attention to it. This is your problem:
Item.setStock()
setStock() requires a parameter, you are trying to call it without one. Perhaps you meant getStock()? And I suspect that all the calls to set methods in the parameter list to writeToItemTable are also wrong, as those set methods will have void as return value, so you can't use them that way.
The setStock method looks like this:
public void setStock(float StockIn)
To call it, you need to pass a float as an argument. Somewhere in your code, you call the method, like this:
Item.setStock(),
The method needs to be called with the float argument, but instead it's called with none, hence you see a compilation error.
In this code:
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
// Right here --> Item.setStock(),
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address)
);
Notice that you're calling Item.setStock(), Item.setStyle(Style), etc. instead of Item.getStock(), Item.getStyle(), etc. This is probably the source of your problem - you're trying to call the setStock() method with no arguments, hence the error.
Hope this helps!
This line
// Create a Item oject
Item Item = new Item();
Is problematic. Not only is it bad style in Java to use uppercase names for variables, this particular instance results in a compile error. Also, you're calling setStock without a parameter. You need to fix that as well.
Here is your error:
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
Item.setStock(), // <<< here! should be getStock()
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address));
But again... consider naming/coding conventions.

Categories