I am a newbie to Java and I have a gui class which has a GUI component and it takes the input from the text field and should pass it to another class. The action listener of the button is below.
public void actionPerformed(ActionEvent action) {
arraylist.add(textField_1.getText());
arraylist.add(textField_2.getText());
arraylist.add(textField_3.getText());
arraylist.add(textField_4.getText());
}
since it is a void method I cannot return the array list so that Ii cannot construct a getter.
public ArrayList<String> getList(){
return this.arraylist;
}
Could anyone please tell me how to access this arraylist from the another class without passing it through the constructor? I am sorry if i asked anything wrong. Thanks in advance.
This is one of the many possible approaches.
Just define another class and call the setter from your actionPerformed(..) method.
public class YourOtherClass {
private static ArrayList<String> arraylist;
public void setList(arrayList) {
this.arraylist = arraylist;
}
public ArrayList<String> getList() {
return this.arraylist;
}
}
Now you can simply set this arraylist as:
public void actionPerformed(ActionEvent action) {
arraylist.add(textField_1.getText());
arraylist.add(textField_2.getText());
arraylist.add(textField_3.getText());
arraylist.add(textField_4.getText());
YourOtherClass.setList(arraylist);
}
Now when you want to access the contents of this list, simply use:
...
//any other method
ArrayList<String> arraylist = YourOtherClass.getList();
System.out.println(arraylist.get(0)); //or whatever
...
You can make that arraylist as Static and access it.
To access that particular arraylist use the below syntax
classNameThatContainArraylist.yourArrayList
be careful while using static.
If you want to use to set and get data then there are many approaches and two of them are follow
public class SetDataInArrayList {
//Aproach one by using object
private List<ActionEvent> list;
public SetDataInArrayList() {
list = new ArrayList();
}
public void setDataInList(ActionEvent e) {
list.add(e);
}
public List<ActionEvent> getList() {
return list;
}
//Approach two by using static reference
private static List<ActionEvent> newList;
static {
newList = new ArrayList<>();
}
public static void add(ActionEvent e) {
newList.add(e);
}
public static List<ActionEvent> returnList() {
return newList;
}
if you use either of approach you will need reference variable in both of cases to fetch data
If I understood, you want to do it:
public class A {
private ArrayList<String> arrayList;
public ArrayList<String> getArrayList() {
return this.arrayList;
}
}
public class B {
private A a = new A();
public void actionPerformed(ActionEvent action) {
a.getArrayList().add(textField_1.getText());
a.getArrayList().add(textField_2.getText());
a.getArrayList().add(textField_3.getText());
a.getArrayList().add(textField_4.getText());
}
}
Related
I'm just looking some another efficient way to pass an object parameter to method.
So I have some method like this:
private void dashboardMenu() {
Dashboard dashboard = new Dashboard();
body.removeAll();
body.add(dashboard);
dashboard.setSize(body.getWidth(), body.getHeight());
dashboard.setVisible(true);
}
private void dataMenu() {
Data data = new Data();
body.removeAll();
body.add(data);
data.setSize(body.getWidth(), body.getHeight());
data.setVisible(true);
}
And I want an efficient method to call between this two method with object parameter (dashboard = new Dashboard(), and data = new Data()).
What I think it should be like this for example:
private void dasboardMenu() {
navigateMenu(Type object);
}
private void dataMenu() {
navigateMenu(Type object);
}
private void navigateMenu(Type object) {
object menu = new object();
body.removeAll();
body.add(menu);
menu.setSize(body.getWidth(), body.getHeight());
menu.setVisible(true);
}
Is it possible to do that?
Please give me an example. I don't even know what keyword should I do.
How about this (assuming your Dashboard and Data are Swing Components)?
private void dashboardMenu() {
navigateMenu(new Dashboard());
}
private void dataMenu() {
navigateMenu(new Data());
}
private void navigateMenu(JComponent c) {
body.removeAll();
body.add(c);
c.setSize(body.getWidth(), body.getHeight());
c.setVisible(true);
}
I was wondering how to reference an ArrayList a different method than it was declared in.
For example I am writing a program that allows me to create a playlist of songs, so in one method I have createAPlaylist and then another method I have shuffle().
In my playlist method I have created an ArrayList but I am having trouble using this arrayList in my shuffle method. There is some code below for context:
public static void createAPlaylist() {
try {
System.out.println("We have the following tracks:");
ArrayList<String> songs = new ArrayList<String>();
String firstSong = jukebox.allTracks.get(0).getTitle();
songs.add(firstSong);
for (int index = 0; index < count; index++) {
System.out.println(SPACES + (index + 1) + ". " + jukebox.allTracks.get(index).getTitle());
}
System.out.println("Select a track to add to the playlist: ");
int songNumber = input.nextInt();
String songSelected = songs.get(songNumber);
songs.add(songSelected);
input.nextLine();
} catch (Exception e) {
System.out.println("\nplease select a valid song number.");
}
}
This is what method parameters are for:
public static void createAPlaylist() {
ArrayList<String> songs = new ArrayList<>();
shuffle(songs);
}
public static void shuffle(ArrayList<String> songs) {
// Do stuff with your ArrayList here
}
You can the arraylist from the createAPlaylist method and pass that to shuffle method:
Like:
public static List<String> createAPlaylist() {
...
...
...
return songs;
}
/// and then in shuffle method receive that as parameter :
public static void shuffle(List<String> songs){
// access that songs list by
}
Or you could:
Instead of method variable declare that arraylist as class variable..
Like:
public class ClassName{
public static ArrayList<String> songs = new ArrayList<String>();
public static void createAPlaylist() {
...
...
...
// reset the songs.
songs = new ArrayList<String>();
...
}
/// and then in another method:
public static void suffle(){
// access that songs list by
List<String> createdSongs = ClassName.songs;
}
In Java, variables are only available within the context they are created - so if you create an ArrayList inside a method, you cannot access it outside of that method unless you store it in the method’s class, or you return the variable from the method it’s made it.
You can either declare the ArrayList outside of the method, as a class field, like so:
public class Foo {
private static ArrayList<String> arrayList = new ArrayList<String>();
public static void createAPlaylist() {
arrayList.add();
etc...
}
}
Or you could return the ArrayList from the method like so:
public class Foo {
public static void main(String[] args) {
ArrayList<String> arrayList = createAPlaylist();
}
public static ArrayList<String> createAPlaylist() {
ArrayList<String> songs = new ArrayList<String>();
// Your code here
// Note that you have to return the list from
// inside the catch block!
// I’d recommend creating the ‘songs’ ArrayList
// outside of the ‘try’ block, so that you can
// have a fallback if something fails in the ‘try’
return songs;
}
}
I don’t know if you intend to have this all static. I’d think it will work better as non static, but that’s a matter for another question, so I’ve left it as-is in the examples.
Sorry if this isn’t formatted perfectly - I’m on a mobile device and don’t have my IDE.
I have created ArrayList and make setter and getter for it.
In the other class i want to add objects in this array. But my code doesn't works. i think i need to add in method setter for array some other code..
public class DataVar {
private ArrayList<String> arrayLinks = new ArrayList<>();
public ArrayList<String> getArrayLinks() {
return arrayLinks;
}
public void setArrayLinks(ArrayList<String> arrayLinks) {
this.arrayLinks = arrayLinks;
}
}
//Here is another class
public class LinksAd {
public void getAllLinksAd() {
DataVar dataVar = new DataVar();
String link = "href";
dataVar.setArrayLinks(link) }}
Looking at your code you are trying to add a String type, where your code specifies that you are expecting an ArrayList. Assuming you just want to add a string to your arraylist the following will work:
public void setArrayLinks(String arrayLinks) {
this.arrayLinks.add(arrayLinks);
}
You can implement generic setter method.
This is DataVar class:
public class DataVar {
private List<String> itemList=new ArrayList<String>();
public List<String> getItemlist() {
return itemList;
}
public void setItemList(Object list) {
if (list.getClass().equals(String.class)) {
itemList.add((String)list);
}
else if (list.getClass().equals(ArrayList.class)) {
itemList = (ArrayList<String>)list;
}
else {
throw new Exception("Rejected type- You can set String or ArrayList");
}
}
}
And this is calling setter method example:
Main class:
public static void main(String[] args) {
List<String> exampleList = new ArrayList<String>();
exampleList.add("This example");
exampleList.add("belongs to");
String owner = "http://www.javawebservice.com";
DataVar dataVar = new DataVar();
dataVar.setItemList(exampleList);
dataVar.setItemList(owner);
for(String str:dataVar.getItemlist()){
System.out.println(str);
}
}
Output:
This example
belongs to
http://www.javawebservice.com
So, you can set ArrayList, also you can set String.
You could do a mehtod to add an Item like this:
public void addStringToList(String s)
{
arrayLinks.add(s);
}
In LinksAd you have to wirte:
dataVar.addStringToList(link);
From reading tutorials and practicing Java, I have come across a problem. I have created a String ArrayList, added string to it. However I want one method which allows me to add more string to this arrayList and another method which allows me to display this arrayList. below is my attempt to solve this problem. My code only prints an empty Array List
class apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static void addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
}
static ArrayList GetArrayList() {
ArrayList<String> destinationArray = new ArrayList<String>();
return destinationArray;
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Didn't you forget adding addString() to getArrayList()?
Your variable destinationArray is declared in a method, it meens that it only exists inside this method outside addString() the object does not exist anymore and you can't access it in other methods. To do it you have to declare it as a class variable like that :
class apples{
ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args)
When your program is executed, in fact it executes the main method, as a result if you want to execute your method addString() you will have to call it in the main function. It will look like that :
public static void main(String[] args)
{
this.addString();
this.viewArrayList(); //prints a empty arraylist
}
Create a Object of a ArrayList and pass reference to different methods. Example create a ArrayList Object in main class and pass it to addString & display method.
public static void main(String[] args){
List<String> destinationArray = new ArrayList<String>();
viewArrayList(destinationArray);
displayArrayList(destinationArray);//prints a empty arraylist
}
public static void addString(List destinationArray ){
destinationArray.add("example1");
destinationArray.add("example2");
}
...
I would do something like this:
class apples
{
private ArrayList<String> array = new ArrayList<String>();
public void addString(String addString)
{
this.array.add(addString);
}
public ArrayList<String> GetArrayList()
{
return array;
}
}
One problem is that you use a different array list for each method. Every time you use the keyword new you are creating a new (and empty) list.
At the top of your class create the ArrayList once...
private ArrayList<String> myList = new ArrayList<String>();
then refer to myList in all your other methods without assigning it a new value.
public ArrayList<String> getArrayList() {
return myList;
}
public void addSomeStrings() {
myList.add("Some String");
myList.add("Some Other String");
}
and don't be afraid to walk through a Java tutorial. This is a fundamental concept and you may get pretty frustrated if you don't shore up your foundation.
Compile and run following program.
import java.util.ArrayList;
class Apples {
static ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args) {
System.out.print("First time");
viewArrayList();
addString("Example1");
addString("Example2");
addString("Example3");
System.out.print("Second time");
viewArrayList();
addString("Example4");
addString("Example5");
System.out.print("Third time");
viewArrayList();
}
public static void addString(String example) {
destinationArray.add(example);
}
static ArrayList getArrayList() {
return destinationArray;
}
public static void viewArrayList() {
System.out.println(getArrayList());
}
}
The scope of the array object is the problem here. You are adding string to 1 array and trying to print another array. Remove the static block and the array declaration in addString(). Declare the array next to the class definition like this,
class apples {
ArrayList destinationArray = new ArrayList();
.. ....
It should work.
Code:
public class Apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static ArrayList<String> addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
return destinationArray;
}
public static ArrayList<String> GetArrayList() {
return addString();
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Output:
[example1, example2]
I am having problems understanding how private and public variables work.
I am trying to fill the myStorage.outString variable from myThread.
But it seems I cannot see the setInString method from myThread.
Here is my example:
public class CT63_Console extends MIDlet {
public Storage myStorage;
public void startApp() {
this.myStorage = new Storage();
}
}
public class storage{
private String[] outString;
public Storage(){
AClass myThread = new AClass();
myThread.start();
}
public void setInString(String sendString){
this.outString = sendString; //push seems not to be supported by MIDP
}
}
public class AClass{
public void run(){
myFunction("write this into Storage var outString");
}
private myFunction(myString){
myStorage.setInString(myString);
}
}
What do I have to do to set the variable and why am I wrong?
You are trying to access myStorage without having a reference to it.
You could pass this reference when you create the AClass instance.
Also, you are trying to assign a String to an array of Strings which can't be done.
public class Storage{
private String outString;
public Storage(){
AClass myThread = new AClass(this);
myThread.start();
}
public void setInString(String sendString){
this.outString = sendString; //push seems not to be supported by MIDP
}
}
public class AClass {
Storage myStorage;
public AClass(Storage s) {
this.myStorage = s;
}
public void run(){
myFunction("write this into Storage var outString");
}
private myFunction(String myString) {
myStorage.setInString(myString);
}
}
this.outString = sendString;
outString is an array of strings (String[]). You cannot assign a single string to an array of strings. So either you need to change the type of that variable to a single string (just String), or you need to specify an index where you assign that string to. Note that in the latter case you need to initialize the array first.