if i was using a JOptionPane message dialog box how would I be able to show an the whole array in the message section such as this little snipit? or would that evenbe possible?
public void showTheMessage()
{
JOptionPane.showMessageDialog(null,"These are are all the colors to
choosfrom,\n"+ arrayOfcolors[the whole array], "Color box");
}
The easiest thing to do would be to concatenate all the elements of the array into one big string.
String colors = "";
for(int i = 0; i < arrayOfColors.length; i++)
colors += arrayOfColors[i] + " ";
The showOptionDialog method lets the user select a single element from an array of options, which I think is what you're looking for.
In case its an array of Color objects
String colors="";
for (Color c: arrayOfColors)
colors+= c.toString() + " ";
Otherwise if its an array of String objects
String colors="";
for (String s: arrayOfColors)
colors+= s + " ";
Just a note, using StringBuilder is much faster, but this is just a small array i guess.
Related
I've read in other posts, that instead of writing just System.out.println(finalPressedKey);
you should write System.out.println(Arrays.toString((finalPressedKey)); because otherwise it will just return the location where the String is saved (as far as I understood it).
public static String PressedKey[] = new String[2000];
public static String[][] finalPressedKey = {{ "", "", "", "", "", "", "", "", "", "", "", "" }}; // 12
public static String FPK3;
public static void upcounter(KeyEvent e) {
for (int x = 0; x < PressedKey.length; x++) {
if (PressedKey[x] != null && PressedKey[x + counter] != null) {
//FPK counter is supposed to be a line, and counter is where the words are supposed to be saved
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
System.out.println(Arrays.toString(finalPressedKey));
}
}
Whenever I Press a Button, it should be saved in my PressedKey Array, and finalPressedKey is supposed to contain itself, and PressedKey (also , only the last element of the array is supposed to be printed), but instead it just prints [[Ljava.lang.String;#76f42c4b]
I also tried using Arrays.deepToString(); but it gives me the same output as with Arrays.toString();
Thanks for your help!
A String[][] is not a 2-d array. It is an array of String[]. The difference is subtle but important.
The method Arrays.toString() takes an array, iterates through its elements, calls toString() on all of them, and adds a prefix, suffix, and delimiters. Since you give it a String[][] (an array of String[]), it will do the following:
Iterate through the elements (each of them a String[])
call toString() on each element - giving the default toString() value of an array - i.e. its memory address (not really but for this purpose it doesn't matter)
concatenate
Luckily for you, there is an easier way - just use Arrays.deepToString(). This behaves as you would expect.
I did not understand the whole code, but following statement is very suspicious:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
since it is adding an array (finalPressedKey[...]) to a string (PressedKey[...]), which will result in that strange text - the standard textual representation of an array (returned by toString). (from a mathematical point of view, it's strange to have 2 indexes )2D_ before the assignment and only one on the right side (1D) for same matrix)
I'm not sure, since we cannot see what counteris, but I believe you wanted something like:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter][counter] + PressedKey[x + counter];
that is, an additional [counter] on second line.
This can also be written as
finalPressedKey[FPKcounter][counter] += PressedKey[x + counter];
If you only want to store lines of strings, a normal String[] is good for you
finalPressedKey[FPKcounter] += PressedKey[x + counter];
even though I wouldn't recomment doing this, no matter what you're trying to accomplish, since this will create a new String object each time a key is pressed.
Maybe ask the question differently and tell us what you're trying to do. I guess String arrays might not be the way to go.
You have to print the elements of your array with
for(int i = 0; i<finalPressedKey[0].length; i++){
for(int j=0; j<finalPressedKey[1].length; j++){
System.out.println(finalPressedKey[i][j]);
}
}
if I understand it correctly.
I am making a homework planner GUI program in Java. One GUI takes in data from the user about the assignment, determines priority for the order the homework should be done in, then allows the user to view their schedule as another GUI that displays all their assignments in the appropriate days of the week that they will work on them.
My problem is that I can't get the Strings to format correctly in the JLists. See here:
I'm filling the JLists with String representations of Homework Objects from a PriorityQueue, like this:
while(!sun.isEmpty())
sundayListItems.add(sunday.poll().toString());
.
.
.
sundayList = new JList(sundayListItems.toArray());
My toString method in my Homework class looks like this, which works as it's supposed to in the console when I put in System.out.prints to see how it's working:
String string = nameOfAssignment + " for " + hoursPerDay +" hours";
if (string.length()>17) {//17 characters per line in this JList
String[] words = string.split(" ");
string = "";
int count = words.length;
int i = 0;
while(count>0) {
do{
string += words[i] + " "; //adding words to a line until 17 characters
i++;
count--;
} while(string.length() <= 17);
string += "\n";//skips line when 17 characters
do{
string += words[i] + " ";
count--;
i++;
} while(i < words.length);
string += "\n\n";//separates assignments w/ 2 lines
}
}
return string;
But, in the GUI JLists, the Strings are not formatting the way I want. I want the String to wrap around to the next line after 17 characters. Anyone have any ideas?
I have created a table and some buttons to remove/add rows.
Problem is, when I add a new row, I must insert a value in the field name which isn't already on that table. Let me explain.
Here is the default table:
Now imagine i remove Station 3:
If i add a new Station, I would want to add a new Station name Station 3 (which is missing on the list) but I am adding a new Station 5 (obviously as my code is not correct).
My code for the Add Button action event is as such:
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
String s2 = "";
String s1 = "Station 1 Station 2 Station 3 Station 4 Station 5";
int tb1rows = jTable1.getRowCount();
if (tb1rows == 5) {
// ERROR - MAXIMUM STATION NUMBER
}
else {
for (int i=0; i<tb1rows;i++) {
s2.concat(jTable1.getValueAt(i,1).toString());
s2.concat(" ");
}
String[] s3=s2.split(" ");
for (int i=0;i<s3.length;i++) {
if (s1.contains(s3[i])) {
System.err.println("contains");
System.out.println(s3[i]);
}
}
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
}
}
What's wrong with my logic? Is there a better way to handle the problem so that I can get the "Station x" that is missing in that column so that I can re-add it?
Thanks in advance for your answers.
As there is a space in "Station 1" split on space won't do. Instead using another separator like ";", better use a Set<String> values = new HashSet<String>().
So long as you have
"Station " + (jTable1.getRowCount()+1)
the new station is always going to be named "Station N + 1".
Assuming you fix the problem of splitting on a space described by another answer, your code should be something like
for (int i=0;i<s3.length;i++) {
if (s1.contains(s3[i])) {
System.err.println("contains");
System.out.println(s3[i]);
}
else {
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (i + 1) ,10,false,0,Color.BLACK});
}
}
instead of all that string manipulation, you could use set mainpulations:
HashSet<String> all = new HashSet<String>();
// then populate all with your 5 station strings (loop)
HashSet<String> have = new HashSet<String>();
// then populate all with the contents of your table (loop)
all.removeAll(have);
// all now contains the ones that weren't in the table.
if its ordered you can just find the first gap and insert there. so iterate over the rows and if nextrow.numberInIt > thisrow+1 you insert thisrow+1
Code should be something like this:
int nextNrToInsert;
for(int=0; i < tb1rows; i++){
thisrowNr = jTable1.getValueAt(i,1).toString();
NextrowNr = jTable1.getValueAt(i+1,1).toString();
if(nextrowNr > thisrowNr+1){
//found the gap
nextNrToInsert = thisrowNr+1;
break;
}
}
//change this to use nextNrToInsert
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
This line is the issue
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
You're always adding in the row with the rowCount() + 1. So even if you remove Station 3, there are 4 rows, and you're adding in row + 1.
This code has no effect:
for (int i=0; i<tb1rows;i++) {
s2.concat(jTable1.getValueAt(i,1).toString());
s2.concat(" ");
}
At loop exit, s2 will still be an empty string, so s3 will be an empty array.
But, the approach to concatenate strings and then split them is misguided, anyway. If all you need is find the lowest integer that, appended to "Station" will produce a unique string, the most natural approach is to make your own TableModel that uses a list of your own objects for each row's data. In that data you'll keep the integer itself, and not the entire string "Station n". Then it's going to be a trivial matter to find a hole in the list of integers.
I have a group of radio buttons and a group of checkboxes. I want to print out the selected radio buttons/checked boxes. To print out the radio button selected I use
Object table = radio.getValue();
System.out.println(table);
I get the radio button selected. To get which checkboxes have been selected I use the same:
Object columns = check.getValue();
System.out.println(columns);
I get the checkboxes which have been checked but with square brackets surrounding them, e.g
if I check the boxes
columnA, columnC, columnF
the printed line would look like this:
[columnA, columnC, columnF]
I want to put the strings of the selected checkboxes into my sql query so I have something like this data.executeQuery("Select " + columns + " From " + table);
It works with the table but it doesn't work with the columns.
For this paricular application, you do not need to split a string. You may use
String str = columns.toString(); // "[colummA, colummC, colummF]"
System.out.println(str.substring(1, str.length() - 1));
You may also form a comma-separated string using
StringBuilder sb = new StringBuilder();
for(Object obj : columns) {
if (sb.length() != 0) sb.append(",");
sb.append(obj);
}
However, to answer the question:
String is splitted via split(String) method using a Regular Expression syntax. As you have a list of items, converting it to a String and splitting it isnt an effective decision.
columns is an array containing all values of the selected checkboxes. Make sure that the default toString method outputs the items separated by a ","
this is because default
check.getValue().toString()
called and depending on if its a List or a HashSet and default toString() method of List/HashSet is called which by default appends [] while printing the values so for your case you could either use a collection with a overridden toString() method as per your requirement or just write you custom toString method and call it instead of the default toString Method
here is a sample implementation if it is HashSet
private String getHashSetString(Set<String> myset){
StringBuilder sb = new StringBuilder();
Iterator<String> i = myset.iterator();
if (! i.hasNext())
return "";
for (;;) {
Long e = i.next();
sb.append(e);
if (! i.hasNext())
return sb.toString();
sb.append(",");
}
}
So instead of
data.executeQuery("Select " + columns + " From " + table);
write
data.executeQuery("Select " + columns.getHashSetString() + " From " + table);
I'm trying to display the contents of an ordered array in something like a JTextField.
for (int i=0; i<array.length; i++) {
this.textField.setText(array[i]);
}
This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last.
Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?
Quick & Dirty Answer
for (int i=0; i<array.length; i++) {
this.myJTextField.setText(this.myJTextField.getText() + ", " + array[i]);
}
Correct Way
First, calling a member variable JTextField probably isn't wise. Since the class is already called like that, it will confuse readers. Naming conventions in Java state member variables are like myTextField for example. (note: original question changed).
User defined format
Note you can convert any number to a string by simply doing "" + number too. If you have many strings, consider using a string builder, as that's faster and won't update the GUI element multiple times: (also fixes the initial ", " before the first item, which happens above)
StringBuilder builder = new StringBuilder();
for (int i=0; i<array.length; i++) {
builder.append(array[i]));
if(i + 1 != array.length)
builder.append(", ");
}
this.myJTextField.setText(builder.toString());
Canonical array representation
Alternatively, you can use this:
this.myJTextField.setText(Arrays.toString(array));
It will look like [1, 4, 5, 6].
You can concatenate all those integers into a string the then present that value in the textfield.
StringBuilder sb = new StringBuilder();
for( int i : array ) { // <-- alternative way to iterate the array
sb.append( i );
sb.append( ", " );
}
sb.delete(sb.length()-2, sb.length()-1); // trim the extra ","
textField.setText( sb.toString() );
You can use a JTextArea instead of the textfield too.