Use JTextField to List items - java

I'm not too familiar with Java GUI programming, and I wanted to do something where I have a loop that spits out a list of stuff and have the JTextField render it in the order it comes out.
I just do not know how the second parameter of the JTextField insert() function works. Right now when I do something like:
for(int i = 0; i < list.size(); i++){
textArea.insert(list.get(i), 0);
}
It does what I want, except it lists everything in backwards order that I put it in. I want it to display everything the other way around.
Thank you for any advice.

All you need to define a temporary string, result and for every item in the list add the string representation to that variable. When you have looped through everything, all you need to do is textArea.setText(result).
String result = "";
for(int i = 0; i < list.size(); i++)
{
result += list.get(i).toString();
}
textArea.setText(result);

Related

Java - how to avoid this repetitive code

I am currently writing a Java program that displays values into an AreaChart and to do so I have an ArrayList with the name dataList from the generic type AreaChartPair.
Each AreaChartPair contains a X-Axis(String) value and a Y-Axis(Integer) value.
The X-Axis are dates and the Y-Axis is a counter and because all the data gets read from a file, the dates will be in a unsorted order. to sort them I use this function:
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
Which is not completely solving my issue, since it will only compare the first few alphanumeric characters (i.e 02.09.2030 would come after 01.01.2000, because 02 comes after 01)
To solve this problem I simply reversed the date from dd.mm.yyyy to yyyy.mm.dd, sorted the list with the function above and afterwards reversed the string back to dd.mm.yyyy
My Question now is how I can simplify this block of code, since it is repetitive:
//replaces the current data with the reversed string
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue()));
}
//sorts the data
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
//reverses the string back to normal, so it can be displayed
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue()));
}
Any suggestions?
A shorter way to perform the sorting is to do the reversing on the fly. The string could also be parsed to a real date object, to make it cleaner, but that requires catch blocks and dateformatter objects, so I won't write that code here.
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue,
(a, b) -> {
return model.reverseDate(a).compareTo(model.reverseDate(b));
}));
Perhaps make a method out of it:
AreaChartPair areaChartPair = new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue());
public DataListType dataListSorter(DataListType datalist, AreaChartPair areaChartPair) {
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, areaChartPair);
}
return dataList;
}
dataList = dataListSorter(dataList);
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
dataList = dataListSorter(dataList);
Still repetitive, though. Probably most useful to do it this way if you're going to do this over and over again throughout your application.

Copying i value from arraylist to array

So I am making a program that needs to be overwrite value i from ArrayList to value i in array. For the life of me I cannot figure out what I should do. I've tried looking for similar problems here, but can't seem to find them. Obviously, my loop is very wrong as it is, as it is just overwriting the entire loop, but I can't figure it out. Any kind-hearted person want to help me?
BTW, I am using Java with Processing
Dot[] dots = new Dot[16];
ArrayList<Dot> extraDots = new ArrayList<Dot>();
Fill them with values and later ...
for (int i = 0; i < dots.length; ++i) {
if (dots[i].timeRemain == 0 && !dotTouch)
{
//arrayCopy(extraDots, i, dots, i, 1);
//this is basically what I want, but from an arraylist to the array
dots = extraDots.toArray(new Dot[i]); //So, so wrong, I know
dotTouch = true;
}
dotTouch = false;
You mean
dots[i] = extraDots.get(i);
???
i didn't get your problem..
simply you can do like below to copy from arraylist to array
why you are using dots[i].timeRemain and dotTouch. can you clarify??
for (int i = 0; i < dots.length; ++i) {
dots[i] = extraDots.get(i);
}

Using Strings to Call Methods in Java

This is one of the first programs I am writing by myself. I want to make a physics calculator where many objects can interact with each other and give the user an option to add more objects. My idea is to have a for loop that runs through each object pulling on each other like this.
for(int n=1; n<=totalObjs; n++){
objName = "object"+n;
for(int i=1; i<n; i++){
obj2Name = "object"+i
objName.getMass();
//getting mass and position from both
//calculations here}
for(int x=n+1; x<=totalObjs; x++){
//same stuff as in the previous for loop}
}
I know there are probably huge syntax errors or logical errors in that but I'd like to sort through those on my own. Is there some way i could reference objects with the strings?
Is there some way i could reference objects with the strings?
Yes, via a Map<String, SomeType> such as a HashMap<String, SomeType>.
Think of this as being similar to an array or ArrayList, but instead of using number indices, you'd be using String indices.
Now looking at your code however, you might be better off using a simple ArrayList or array, since you appear to be trying to use numeric indices.
e.g.,
// assume a class called GravMass which has Mass, position, and momentum
List<GravMass> gravMassList = new ArrayList<GravMass>();
// fill your list
for(int i = 0; i < gravMassList.size() - 1; i++) {
GravMass gravMass1 = gravMassList.get(i);
int mass1 = gravMass1.getMass();
for(int j = i + 1; j < gravMassList.size(); j++){
GravMass gravMass2 = gravMassList.get(j);
int mass2 = gravMass2.getMass();
//getting mass and position from both
//calculations here}
}
}

Java Can Variables Be Used in Variable Names

I have this little script repeated below in my code a few times. I know that I could run a function to do this easily, but can I use a variable as a variable name like in PHP.
if (4val != null && 4val.length() > 0){
Button 4 = new Button(this);
4.setText(4val);
4.setTextSize(20);
}
I want to be able to do something like
i=1;
while{i > 10}{
$$i = value;
//do stuff with $$i
i++;
}
Is this possible in Java?
No. But you can stick the buttons in an array, and then iterate through.
Button[] buttons = new Button[10];
// instantiate all the buttons
for (int i = 0; i < buttons.length; i++) {
// update the button
}
use Map instead
map.put("key","val");
map.get("key");
Well you can also use array, List , but if you use HashMap you retrieval process would be almost o(1)

Checking if ArrayList element exists or not

I'll try to explain this as best I can. I have an ArrayList of String's. I am trying to implement server-side paging for a webapp. I am restricted to the number of items per page (6 in this case) which are read from this ArrayList. The ArrayList is, lets say, the entire catalog, and each page will take a section of it to populate the page. I can get this working just fine when there are enough elements to fill the particular page, its when we hit the end of the ArrayList where there will be less than 6 items remaining for that pages segment. How can I check if the ArrayList is on its last element, or if the next one doesn't exist? I have the following code (in pseudo-ish code):
int enterArrayListAtElement = (numberOfItemsPerPage * (requestedPageNumber - 1));
for (int i = 0; i < numberOfItemsPerPage; i++) {
if (!completeCatalog.get(enterArrayListAtElement + i).isEmpty() {
completeCatalog.get(enterArrayListAtElement + i);
}
}
The if in the code is the problem. Any suggestions will be greatly appreciated.
Thanks.
It sounds like you want:
if (enterArrayListAtElement + i < completeCatalog.size())
That will stop you from trying to fetch values beyond the end of the list.
If that's the case, you may want to change the bounds of the for loop to something like:
int actualCount = Math.min(numberOfItemsPerPage,
completeCatalog.size() - enterArrayListAtElement);
for (int i = 0; i < actualCount; i++) {
// Stuff
}
(You may find this somewhat easier to format if you use shorter names, e.g. firstIndex instead of enterArrayListAtElement and pageSize instead of numberOfItemsPerPage.)
Can't you just get
completeCatalog.size()
and compare it to i? i.e to answer the question "is there an ith element" you say
if (i<completeCatalog.size())
You just need to add a second expression to look whether the end of the list was reached already:
int enterArrayListAtElement = (numberOfItemsPerPage * (requestedPageNumber - 1));
for (int i = 0; i < numberOfItemsPerPage; i++) {
if (enterArrayListAtElement + i < completeCatalog.size() && !completeCatalog.get(enterArrayListAtElement + i).isEmpty() {
completeCatalog.get(enterArrayListAtElement + i);
}
}
An ArrayList has the method of size(), which returns the number of elements within the List.
Therefore, you can use this within the if statement to check you've not went too far.
For example,
if(enterArrayListAtElement + i < completeCatalog.size()) {
...
}

Categories