This question already has answers here:
JLabel - Show longer text as multiple lines?
(4 answers)
How to format JLabel/JTextField so text wraps [duplicate]
(1 answer)
Closed 4 years ago.
I have 12 labels and 12 car objects in an ArrayList. The for loop sets the for each label and its corresponding car object. However the text in the labels does not wrap and just carries on.
What do I have to put in the loop to make the text wrap?
In theory the text is supposed to look like this:
2012 Toyota Corolla
70000 Miles
$12,000.00
But instead in the labels all I get in a single line is:
2012 Toyota Corolla 700...
Code
InventoryFileReader reader = new InventoryFileReader();
ArrayList<Car> cars = reader.getAllCars();
//will format getPrice to currency.
Locale locale = new Locale("en", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
JLabel[] labels = new JLabel[]{jLabel1, jLabel2, jLabel3, jLabel4,
jLabel5, jLabel6, jLabel7, jLabel8,
jLabel9, jLabel10, jLabel11, jLabel12};
for(int i = 0; labels.length > i; i ++){
labels[i].setText(cars.get(i).getYear() + " " + cars.get(i).getMake() +
" " + cars.get(i).getModel() + " " + "\n" + cars.get(i).getMiles()
+ " miles" + '\n' + " " + formatter.format(cars.get(i).getPrice()));
}
The getYear(), getMiles(), and getPrice(), actually return integer values.
Related
This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 3 years ago.
I'm trying to make this "Overall Grade Calculator" using javax.swing.*; that I recently learned. However, I can't find what is wrong with my code. My IDE, which is Ecliple, isn't detecting any error on my codes but it won't run when I try to run my codes. Where did I mess up?
BTW: This is by far my latest knowledge of Java Coding because I am self taught so I might not know any codes that are more advanced that these.
import javax.swing.*;
public class gradeCalcMk3 {
public static double average(double a, double b, double c, double d) {
double ave = a*0.3 + b*0.5 + c*0.1 + d*0.1;
return ave;
}
public static void main(String[] args) {
double grade[] = {0,0,0,0,0};
JTextField name = new JTextField(10);
JTextField q = new JTextField(3);
JTextField ex = new JTextField(3);
JTextField cs = new JTextField(3);
JTextField ilm = new JTextField(3);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Name:"));
myPanel.add(name);
myPanel.add(new JLabel("Q:"));
myPanel.add(q);
myPanel.add(new JLabel("Ex:"));
myPanel.add(ex);
myPanel.add(new JLabel("CS:"));
myPanel.add(cs);
myPanel.add(new JLabel("ILM:"));
myPanel.add(ilm);
grade[0] = Double.parseDouble(q.getText());
grade[1] = Double.parseDouble(ex.getText());
grade[2] = Double.parseDouble(cs.getText());
grade[3] = Double.parseDouble(ilm.getText());
grade[4] = average(grade[0], grade[1], grade[2], grade[3]);
double confirm = JOptionPane.showConfirmDialog
(null, myPanel, "Enter Values", JOptionPane.OK_CANCEL_OPTION);
if(confirm == JOptionPane.OK_OPTION) {
JOptionPane.showMessageDialog(null, "Name: " + name.getText()
+ "\n\nQuiz: " + grade[0]
+ "\n\nExam: " + grade[1]
+ "\n\nCS: " + grade[2]
+ "\n\nILM: " + grade[3]
+ "Average: " + grade[4]);
}
}
}
Here's the output when I try to run it
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at gradeCalcMk3.main(gradeCalcMk3.java:32)
You will need a bit more to make this work.
Basically all of the code that extracts the values from the text field needs to be placed into a method that is triggered when you click on a button or menu (or something else to activate it). i.e. you need at least two methods, a "setup form" method and a "process the inputs" method.
As posted, your JTextFields contain no text (the constructor you are using does not set the text - it sets the "number of columns").
Once all of the text fields have been created and added to the form, the very next step is to extract the empty strings from them and attempt to parse them as doubles. This will generate the exception you encountered.
Because the code is all contained in a single method, there is zero chance to allow you to enter any values into the fields before they are read and processed.
At the very least, comment out (for now) the code that attempts to extract values, parse them and compute the average. This extract, parse and calculate code can later be moved into the event handler attached to a button or menu that I mentioned above.
I hope this helps.
You're simply using the wrong constructor when creating instances of JTextField
JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
Instead of providing an int, use a string, for example new JTextField("10")
JTextField(String text)
Constructs a new TextField initialized with the specified text.
Nvm, I found where I messed up and fixed it by doing this:
if(confirm == JOptionPane.OK_OPTION) {
grade[0] = Double.parseDouble(q.getText());
grade[1] = Double.parseDouble(ex.getText());
grade[2] = Double.parseDouble(cs.getText());
grade[3] = Double.parseDouble(ilm.getText());
grade[4] = average(grade[0], grade[1], grade[2], grade[3]);
JOptionPane.showMessageDialog(null, "Name: " + name.getText()
+ "\n\nQuiz: " + grade[0]
+ "\n\nExam: " + grade[1]
+ "\n\nCS: " + grade[2]
+ "\n\nILM: " + grade[3]
+ "Average: " + grade[4]);
}
I read, some StackOverflow questions that I need to use HTML stuffs.
But what would be the easiest it without any of HTML stuff.
Here's the code
label.setText(label.getText() + (String)boxTimes.getSelectedItem() + input);
This code will produce this
What I want is:
You must know a bit of basic String format:
\n line break
\t tab
So your code will be like:
String myLabel =
// 4
label.getText() + "\n\n" +
// 7:00
(String)boxTimes.getSelectedItem() + "\t" +
// - Going out....
"- " + input;
label.setText(myLabel);
But as long as JLabel does not accept \n as Abishek Manoharan pointed, you must use <br>.
String myLabel =
"<html>" +
label.getText() +
"<br/><br/>" +
(String)boxTimes.getSelectedItem() + " - " + input +
"</html>;
label.setText(myLabel);
I was faced with the same problem too and couldn't find a viable solution.
So I went ahead and used a JTextArea instead of JLabel.
JTextArea label = new JTextArea();
label.setEditable(false);
label.setBackground(null);
It gives the same look and feel of a JLabel
You can use '\n' and '\t' as you like,
and what more, the text is selectable which is not possible in JLabel.
This question already has answers here:
Splitting a Java String by the pipe symbol using split("|")
(7 answers)
Closed 7 years ago.
I'm sending this string from the client to the server:
Ar|0.04107356|-0.31299785|-0.9991561
That string is as printed out by the server - So it is correct.
"Ar" is the packet name, and the values are the velocity of an arrow that the archer is going to shoot.
So to get those values, I'm using
String[] values = str.split("|");
And then
a.shoot(Float.valueOf(values[1]), Float.valueOf(values[2]), Float.valueOf(values[3])); //a is an archer
The problem is, values1, values[2], and values[3] seem to be corrupt or unrecognizable.
My full code is this:
public void handleMessage(String str){
System.out.println(str);
String[] values = str.split("|");
if (values[0].contains("Ar")){
System.out.println("X: " + values[1] + " Y: " + values[2] + " Z: " + values[3]);
}
System.out.println("Vals: " + values[0] + " " + values[1] + " " + values[2] + " " + values[3]);
if (true) return; //Returning so I can analyze de-bug messages without crashes.
for (Archer a : GameServer.archers){
a.shoot(Float.valueOf(values[1]), Float.valueOf(values[2]), Float.valueOf(values[3]));
}
When I print out the "Vals" message, it comes out like this:
Vals: A r |
What is going wrong here?
The horizontal bar has a special meaning in Java regular expressions which you must escape in order to use as a literal:
String[] values = str.split("\\|");
This question already has answers here:
Java String split is not working
(3 answers)
Closed 7 years ago.
I have come across an unexpected feature in the split function of String in Java, here is my code:
final String line = "####";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
This code gives me an ArrayIndexOutOfBoundsException, whereas I would expect it to print "" and "" (two empty Strings), or maybe null and null (two null Strings).
If I change my code for
final String line = " # # # #";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
Then it prints " " and " " (the expected behaviour).
How can I make my first code not throwing an exception, and giving me an array of empty Strings?
Thanks
You can use the limit attribute of split method to achieve this. Try
final String line = "####";
final String[] lineData = line.split("#", -1);
System.out.println("Array length : " + lineData.length);
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
As always, answer is written in the Javadoc
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Since your array is composed only by empty strings, they are not added to it, thus trying to access the values result in an ArrayOutOfBoundException.
If I understand your question, this would do it -
final String line = " # ";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
The problem is that the empty string isn't a character.
I want to format some numbers in our jsp pages.
first i define some resources in my porperties
format.number.with2Decimal={0,number,#0.00}
......
Question1:
i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00
who can tell me the differences between them? thanks!
Question2:
if i define a BigDecimal type in my action
BigDecimal number1;
Then my page should using a format to show this value,
1.if number1=null then show -NIL-
2.if number1=0 then show -NIL-
3.if number1>0 then show 1.00,3434.98 .....
please ignore number<0
Question3:
change number1 to a String,
1.if number1=null or empty or blank then show -NIL-
2.if number1=Hello then show Hello ....
could you give me help?
Here you go :
<s:property value="getText('{0,number,#,##0.00}',{profit})"/>
This is how I format numbers in my projects. You can use it with <s:if> to attain what you require.
Question1: i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00 who can tell me the differences between them? thanks!
0 means that a number must be printed, no matter if it exists
# means that a number must be printed if it exists, omitted otherwise.
Example:
System.out.println("Assuming US Locale: " +
"',' as thousand separator, " +
"'.' as decimal separator ");
NumberFormat nf = new DecimalFormat("#,##0.0##");
System.out.println("\n==============================");
System.out.println("With Format (#,##0.0##) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
nf = new DecimalFormat("#,000.000");
System.out.println("\n==============================");
System.out.println("With Format (#,000.000) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
Running Example
Output:
Assuming US Locale: ',' as thousand separator, '.' as decimal separator)
==============================
With Format (#,##0.0##)
------------------------------
1234.0 = 1,234.0
123.4 = 123.4
12.34 = 12.34
1.234 = 1.234
==============================
==============================
With Format (#,000.000)
------------------------------
1234.0 = 1,234.000
123.4 = 123.400
12.34 = 012.340
1.234 = 001.234
==============================
In Struts2, you can apply this kind of format with the getText() function from ActionSupport.
P.S: Question 2 and 3 are trivial (and messy).