ArrayList, Iterator, save last element
Hi,
I have a JPanel where a user can click with the mouse... I can save the coordinates of the mouseclicks in an ArrayList. However, I don't know how I can save the last clicked coordinate in a separate variable...
private List <Point>playerCoordinatesList = new ArrayList<Point>();
private Point playerCoordinates, playerCoordinatesOld;
Iterator i;
protected void paintComponent( Graphics g ) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for(i = playerCoordinatesList.iterator(); i.hasNext(); ) {
playerCoordinates = (Point)i.next();
g2.drawOval(playerCoordinates.x, playerCoordinates.y, OVALWIDTH, OVALHEIGHT);
public void updatePlayerPosition(MouseEvent evt) {
playerCoordinatesList.add(evt.getPoint());
}Thanks!
Firstly, why to use Vector instead ArrayList? The only difference is that Vector is synchronized, and I cannot see the need for it.
Secondly, what do you mean by "saving the last coordinates in a separate variable"? If you stored each click's coordinate in the list, simply take its last item (don't forget to check for empty list):
list.get(list.size()-1);
Similar Messages
-
How to delete the last element of a collection without iterating it?
how to delete the last element of a collection without iterating it?
To add to jverd's reply, even if you could determine the last element, in some collections it is not guaranteed to always be the same.
From HashSet:
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. -
Lots of blank space when printing array with only last element printed
I have a slight problem I have been trying to figure it out for days but can't see where my problem is, its probably staring me in the face but just can't seem to see it.
I am trying to print out my 2 dimensional array outdie my try block. Inside the trying block I have two for loops in for the arrays. Within the second for loop I have a while to put token from Stringtokeniser into my 2 arrays. When I print my arrays in this while bit it prints fine however when I print outside the try block it only print the last element and lots of blank space before the element.
Below is the code, hope you guys can see the problem. Thank you in advance
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;
public class javaflights4
public static final String MESSAGE_SEPERATOR = "#";
public static final String MESSAGE_SEPERATOR1 = "*";
public static void main(String[] args) throws IOException
String data = null;
File file;
BufferedReader reader = null;
file = new File("datafile.txt");
String flights[] [];
//String flightdata[];
flights = new String[21][7];
int x = 0;
//flightdata = new String[7];
int y = 0;
try
reader = new BufferedReader(new FileReader(file));
//data = reader.readLine();
while((data = reader.readLine())!= null)
data.trim();
StringTokenizer tokenised = new StringTokenizer(data, MESSAGE_SEPERATOR1);
for(x = 0; x<=flights.length; x++)
for(y = 0; y<=flights.length; y++)
while(tokenised.hasMoreTokens())
//System.out.println(tokenised.nextToken());
flights [x] [y] = tokenised.nextToken();
//System.out.print("*"+ flights [x] [y]+"&");
System.out.println();
catch(ArrayIndexOutOfBoundsException e1)
System.out.println("error at " + e1);
catch(Exception e)
finally
try
reader.close();
catch(Exception e)
int i = 0;
int j = 0;
System.out.print(flights [j]);
//System.out.println();A number of problems.
First, I bet you see a lot of "error at" messages, don't you? You create a 21x7 array, then go through the first array up to 21, going through the second one all the way to 21 as well.
your second for loop should go to flights[x].length, not flights.length. That will eliminate the need for ArrayIndexOutOfBounds checking, which should have been an indication that you were doing something wrong.
Second, when you get to flights[0][0] (the very first iteration of the inner loop) you are taking every element from the StringTokenizer and setting flights[0][0] to each, thereby overwriting the previous one. There will be nothing in the StringTokenizer left for any of the other (21x7)-1=146 array elements. At the end of all the loops, the very first element in the array (flights[0][0]) should contain the last token in the file.
At the end, you only print the first element (i=0, j=0, println(flight[ i][j])) which explains why you see the last element from the file.
I'm assuming you have a file with 21 lines, each of which has 7 items on the line. Here is some pseudo-code to help you out:
count the lines
reset the file
create a 2d array with the first dimension set to the number of lines.
int i = 0;
while (read a line) {
Tokenize the line;
count the tokens;
create an array whose size is the number of tokens;
stuff the tokens into the array;
set flights[i++] to this array;
} -
Last element of DefaultStyledDocument has \n appended, why?
Hello!
I have some trouble getting the text of styledDocument in JTextPane. I get the text recursively by traversing the Elements and convert that to xml and save it. I do not understand why I get \n as last leaf-Element. There is no \n when I call getText in Document or JTextPane. So with every saving and loading the document gets longer and longer because there is \n appended every time.
Here is a small program that shows the problem:
import javax.swing.*;
import javax.swing.text.*;
public class TextPaneWriter extends JFrame {
public TextPaneWriter() {
DefaultStyledDocument doc = new DefaultStyledDocument();
try {
SimpleAttributeSet a = new SimpleAttributeSet();
StyleConstants.setBold(a, true);
doc.insertString(doc.getLength(),
"I wish I was in Carrickfergus\n", a);
a = new SimpleAttributeSet();
StyleConstants.setItalic(a, true);
doc.insertString(doc.getLength(),
"Only for nights in Ballygrant\n", a);
a = new SimpleAttributeSet();
StyleConstants.setUnderline(a, true);
doc.insertString(doc.getLength(),
"I would swim over the deepest ocean,\n", a);
a = new SimpleAttributeSet();
StyleConstants.setBold(a, true);
doc.insertString(doc.getLength(),
"For my love to find", a);
catch (BadLocationException x) {
JTextPane tp = new JTextPane(doc);
this.getContentPane().add(tp);
System.out.println("Get text of JTextPane:");
System.out.println(tp.getText() + "END");
System.out.println();
System.out.println("Get text of Document:");
try {
System.out.println(doc.getText(0, doc.getLength()) + "END");
catch (BadLocationException x) {
System.out.println();
System.out.println("Get text recursively:");
this.writeDocRec(doc.getDefaultRootElement(), doc);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200,200);
this.setVisible(true);
private String getTextOfElement(Element styledElement,
DefaultStyledDocument doc) {
String text = "";
int startOffset = styledElement.getStartOffset();
int endOffset = styledElement.getEndOffset();
try {
text = doc.getText(startOffset, endOffset-startOffset);
catch (BadLocationException x) {
x.printStackTrace();
return text;
private void writeDocRec(javax.swing.text.Element element,
DefaultStyledDocument doc) {
if (element.isLeaf()) return;
for (int i=0; i<element.getElementCount(); i++) {
javax.swing.text.Element child = element.getElement(i);
if (child.isLeaf()) {
System.out.print(this.getTextOfElement(child, doc) + "END OF ELEMENT\n");
writeDocRec(child, doc);
* @param args
public static void main(String[] args) {
new TextPaneWriter();
}And this is what I am getting:
Get text of JTextPane:
I wish I was in Carrickfergus
Only for nights in Ballygrant
I would swim over the deepest ocean,
For my love to findEND
Get text of Document:
I wish I was in Carrickfergus
Only for nights in Ballygrant
I would swim over the deepest ocean,
For my love to findEND
Get text recursively:
I wish I was in Carrickfergus
END OF ELEMENT
Only for nights in Ballygrant
END OF ELEMENT
I would swim over the deepest ocean,
END OF ELEMENT
For my love to findEND OF ELEMENT
END OF ELEMENT
So why is there another element with \n?
I can only think of digging in the xml-document after parsing finding the last element and removing the last \n. Or is it \n\r or \r\n?!?!? It does not feel good to do something like that........
Thank you!
Annette
Message was edited by:
AnnetteSometimes a bit of sleep is better than any thinking!
I had an idea this morning and it seams to be working. I change the recursive method to:
private void writeDocRec(javax.swing.text.Element element,
DefaultStyledDocument doc) {
if (element.isLeaf()) return;
for (int i=0; i<element.getElementCount(); i++) {
javax.swing.text.Element child = element.getElement(i);
if (child.isLeaf()) {
int start = child.getStartOffset();
int end = child.getEndOffset();
int len = doc.getLength();
if (end > len) System.out.println("len " + len
+ " start " + start + " end " + end);
else System.out.print(this.getTextOfElement(child, doc)
+ "END OF ELEMENT\n");
writeDocRec(child, doc);
}I found that the last element, that I do NOT want and that contains that \n has endIndex > doc.getLength(). So if I find an element that satisfies this condition I know it is the last, not wanted element, and skip it. Does it make any sense to have an element with index > length?
Do you think that this is a good solution? Or is it some kind of trial and error and not really understanding what is going on?
I would appreciate some advices. Thank you!
Annette -
Failure to save the element during dehydration
Hi all,
Build JDEVADF_11.1.1.2.0_GENERIC_091029.2229.5536
Oracle Enterprise Manager 11g Fusion Middleware Control [Version 11.1.1.2.0]
i am facing this below problem when trying to read a list. actually it a parent will get list from 2-3 process and before sending this list to another process i am looping through to set the input values for the last process. at that time i am getting this below error. kindly help me to fix this problem. thanks in advance.
<bpelFault><faultType> <message>0</message></faultType><remoteFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="summary"><summary>
Cannot save xml element. failure to save the element {http://xmlns.oracle.com/Process_Contracts_Build_XML}Header during dehydration
This element was not a root element and the scope had reference to this element. The scope should have references only to root element.
Contact Oracle Support Services. Provide the error message and the exception trace in the log files (with logging level set to debug mode).
</summary></part><part name="detail"><detail>javax.xml.ws.soap.SOAPFaultException: Cannot save xml element.
failure to save the element {http://xmlns.oracle.com/Process_Contracts_Build_XML}Header during dehydration
This element was not a root element and the scope had reference to this element.
The scope should have references only to root element. Contact Oracle Support Services.
Provide the error message and the exception trace in the log files (with logging level set to debug mode).
</detail></part><part name="code"><code>null</code></part></remoteFault></bpelFault>
Best Regards,
Kalyan
Edited by: ydkalyan on May 23, 2012 4:25 AM
Edited by: ydkalyan on May 23, 2012 4:26 AM
Edited by: ydkalyan on May 23, 2012 4:29 AM
Edited by: ydkalyan on May 23, 2012 4:30 AM
Edited by: ydkalyan on May 23, 2012 4:31 AMdoes your process have doXslTransform with multiple source documents? if yes then that patch should work. if not, please log an sr and please provide your current test case that can be used to reproduce the problem.
-
Is there any DB field which is save last number of records automatically?
HI
Is there any type of DB field which is save last number of records automatically when one record is inserted like MANDT?
MANDT is client number though.
Regards.thanks but I don't understand what you say.
is 'DD03L' field type for data element?
DD03L is another table.
I don't know how to put table inside table.
even if succeed how does it works for my question?
regards. -
Retrieve Last element from Collection
Hi,
I am a beginner in Java. Can somebody tell me how to retrieve last element from java.util.collection without Iterating?Hi,
I am a beginner in Java. Can somebody tell me
how to retrieve last element from
java.util.collection without Iterating?You realize of course that this is rather silly since not every Collection necessarily has a "last" element. For it to have the notion of a "last" element it would have be ordered and would be a List. -
How to get the last element of a structure in a textfield in DesignStudio
Hello,
how can I get the last element of a structure within a bex query?
Within the structure we are working with dates that dynamically are buiId (input date - offsets for several months).
I have to show the last value in a single textfield within DesignStudio.
Regards
FrankHi Frank,
in DS 1.3 you can use forEach function to get the last element of BEx structure (or n-th element in general using if condition)
var array = DS_CROSSTAB1.getMembers("DHGY5D6XEFO1K45SB00BXFH7A",10);
var lastMember="";
array.forEach(function(element, index) {
lastMember = element.text;
TEXT_1.setText("Last structure element: "+lastMember); -
How to select the last elements in a string
Hi Guys
I am using UART RS232 protocol and i need to calculate the check sum. My data came in decimal and in the end it must be doubles to manipulate it. So my problem is, for example, the sum of all elemants is in decimal 1742 and in hex is 6CE and i wont only the last two elemants, CE that corresponds to 206 that is the result of my checksum. Can anyone help me?
Thanks
Solved!
Go to Solution.
Attachments:
String last elements.vi 9 KBThanks Syrpimp
My data came from HMI in decimal like the example that i show above. Each cell is a value. You used an array, but i think that i can't use it because it must be done automatically and the data field have variable length.
The UART protocol frame has a start frame field that corresponds to two ‘{‘ characters and an end frame field that corresponds to two ‘}’. Additionally, besides the data field, that has variable length, it has a byte that corresponds to the command type and another that is the checksum. The following table illustrates the protocol.
Bytes considered in checksum
Command Data
Start Frame
Cmd
(hex)
Data0
Data1
Data2
Data3
Data4
Data5
Data6
Data…
CHK SUM
End Frame
1 Byte CHK SUM (sum of all data bytes truncated to 1 byte)
Fig. 1 UART communication protocol template
I receive data like this:
123
123
160
54
111
103
110
108
107
109
108
108
100
100
100
100
0
0
1
4
5
0
0
0
0
0
0
7
96
1
0
0
0
0
0
10
51
1
0
0
51
1
1
23
12
0
206
125
125
I'm trying explain my doubt the best way i can and i thank you all. -
Hello all
I am having a string like this:
55.000000; 10.000000; 0.100000; 1.000000; 1.000000; 0.100000; 0.000000; 0.000000; 1.000000; 1.000000; 22.000000; 0.100000; 6144.000000;
The length of the string is not always same. What i want is to have the last element. i.e in this case 6144
One way is to get the string length and using string subset to get the last element. But for this, the length must be always constant.
Is there any other way to get the last element independant of the string length
thanks
Nghtcwrlr
********************Kudos are alwayzz Welcome !! ******************
Solved!
Go to Solution.Since you have the extra semicolon at the end, I actually grabbed the second-to-last element of the array after the spreadsheet string to array.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines
Attachments:
Get last element.png 13 KB -
How to remove only the last element of spreadsheet string
I use path to string option to store image path into database and while retrieving the string is again converted into path but it gives out an error as the output of array to spreadsheet string gives out a tab at the end which is unable for the IMAQ read file to recognise.but when i use the path of the image directly into IMAQ readfile the image is opened . so how to remove the tab only at the end of output of the spreadsheet string(whose length can vary)? I have also attached my program with this.
Attachments:
retrieve_images_from_DB.vi 65 KB
file_path_to_db_(images).vi 40 KB
create_table_for_images.vi 45 KBindhu wrote:
> Thanks for your reply!
> But my problem is to remove only the last element(which is a tab or an
> alphabet) from a spreadsheet string of any length.
If you just want to remove the last character of a string just use the
String Size function reduce the result by one and wire it together with
the string to the Split String function.
Rolf Kalbermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions -
JComboBox shows "Java Applet Window" as last element
Hey all,
I am having a problem with using JComboBox. When I use JComboBox and show it in a JDialog (popup window), the last element of the drop down (JComboBox) is "Java Applet Window". This element is, however, not selectable. I want to get rid fo the "Java Applet Window" in my dropdown.
This problem only happens when my applet opens up a JDialog that has the JComboBox, but does not happen when I add the JComboBox directly to the applet.
I've read around in other forums that this has to do with security. I understand the need to show that a popup window (JDialog) is an applet window so the user doesn't mistake it as one of the native windows. But, the JComboBox is not a whole 'nother window, so why does it feel the needs to add that last line to designate it as a "Java Applet Window?"
Thanks.
Nina.My apologies, I did not clarify myself in my question. Sorry that I created misunderstandings of the problem - as evident in the response in the previous post from himanshug.
I am using JDK 1.3.1
I must use an applet, but all my components are standalone. They can be ran as a standalone application. But for deployment, we are using applets. It's easier to do applets so clients can access via browser than deploy a whole application installation on 50 machines halfway across the world.
And no, there is no element in my list that says "Java Applet Window". When running my application standalone, the "Java Applet Window" does not appear as the last element in my drop down.
The "Java Applet Window" also does NOT appear when I add the drop down directly to the applet. It only appears when the drop down is in a JDialog that gets launched by an applet.
My problem: How to get rid of the "Java Applet Window" as it seems something is adding this to my dropdown. And it's not my code that is adding it.
Thanks. I am also up'ing the duke dollars for a solution to this to 15. -
How to display last element in a dynamic 1d array
hi..
i want to display the value of last element in a 1d dynamic array.../ i mean ..if i stop the vi run, i need to display the last element in the array..how can i do this?
and is there any way to use a button to start the vi...instead of using the Run button on the vi front panel??
Solved!
Go to Solution.Index array!. Use array size to determine the size of your array, subtract 1, feed that in the index terminal of Index Array.
You have to start the VI running somehow. It could be set to run when opened. Assuming what you want is a means to type values into a front panel, hit a GO button that you created on the front panel, then have the real part of the VI execute. You could use an event structure. Or put a while loop at the beginning with a small wait statement in side that basically just polls the GO button. When that button is pressed, the true boolean stops the while loop and allows the program to proceed to the main body of your program. -
hey all-
i am trying to add a comma if this is last element in
structure:
<cfset stuff=structnew()>
<cfset stuff.first=1>
<cfset stuff.first_first=2>
<cfset stuff.first_first_first=3>
<cfset stuff.first_first_first_first=4>
<cfset stuff.first_first_first_first_first=5>
<cfdump var="#stuff#">
<cfoutput>
<cfloop collection="#stuff#" item="i">
'#stuff
#'<cfif StructCount(stuff) lt 6>,</cfif>
</cfloop>
</cfoutput>
but it is not workin. how do i get the last
element.As Adam said structures are unordered and there is no concept
of last.
But it looks like you are trying to output a list of elements
by looping
over the structure and do not want a comma after the last
element. Your
if logic is the problem here, it will always be true.
<cfoutput>
<cfloop collection="#stuff#" item="i">
'#stuff
#'<cfif StructCount(stuff) lt 6>,</cfif>
</cfloop>
</cfoutput>
StructCount(stuff) is always five. It the size of the
structure is not
going to change while you are looping over it. You need a
counter and
then compare that counter to the size of the structure to
know you have
reached the end of it.
<cfoutput>
<cfset counter = 0>
<cfloop collection="#stuff#" item="i">
<cfset counter = counter + 1>
'#stuff#'<cfif counter lt
StructCount(stuff)>,</cfif>
</cfloop>
</cfoutput>
This could be simplified with a list function.
<cfset stuffList = ''>
<cfloop collection="#stuff#" item="i">
<cfset stuffList = listAppend(stuffList,stuff
)>
</cfloop>
<cfoutput>#stuffList#</cfoutput> -
React on Array's last Element arrival
Hello NI developers!
My VI reads data from board and fills array. As data acquisition speed is slower than VI performance I want VI react and perform action exactly when array gets it's last element. I don't want to use Stacked Sequence Structure, because there NEXT frame executes only when it gets all the data from previous frame and if I manipulate large amounts of data (i.e. Megabytes) it will be hanging somewhere in memory. I want to catch that moment when array filled with last element. Any advices how can I reach that?
Thank you in advance.
Message Edited by ACiDuser on 06-26-2008 08:17 AMI want calculate transfer speed. CIN measures time that takes FOR Loop and sends it to LV. And I get this time with microsecond precision. I got an idea... Maybe I should use this Stacked Event Structure only for "Time" indicator.. and inside Check If it's not equal with 0 then - calculate speed!
Maybe you are looking for
-
My Illustrator CS6 will not launch
I was working with an AI file in Illustrator today. Everything was working fine and I made some edits and placed the file in my inDesign document. I saw another change I wanted to make so I right clicked on the file and selected Edit with Illustrato
-
I've had an account with T-Mobile for 7 years, and I'm trying to port the number to a Verizon prepaid phone. Three and a half days after activating the Verizon prepaid phone, I can make calls on the Verizon phone, but all incoming calls go to my T-M
-
Is what I want possible?
I started a website for my writer's group using iWeb and never expected it to take off like it has. It was meant to be a resource for my fellow writers in the group and a way for us to stay connected and up to date with one another and has turned int
-
there is a website need to run applet, but must disble sun java vm. when i disble java, i was told "enable java first". when i enable java i was told "disable sun java vm first". what should do. i am using windows xp and jre1.4.1
-
Hey Everyone, This must be easy to solve, but my searches have yet to reveal the answer. I just created a simple chart based on the average value from a table. Here is my source query: SELECT AVG(TIME_VAL) VALUE, 5 MAX, MIN(TIME_VAL) LOW, MAX(TIME_VA