user3198552
user3198552

Reputation: 21

ArrayList to different class

I am new to Java and I am trying to send the value of an ArrayList to another class in which I will display the value in a Text Field. So far I have

public class A {
  public static void main(String[] args) {
    String[] color= {"red", "blue"};
    List<String> list = new ArrayList<String>();

    for ( String x : joke )
      list.add(x);
    }
 }

And I have the second class

public class B extends JFrame{
  A a = new A();
  private JButton but;
  private JTextField txt;

  public B(){
    ...GUI declarations(layout, etc)
    but = new JButton("Button);
    txt = new JTextField(30);
    add(but);
    add(txt);
    ColorHandler color = new Color
    color.addActionListener(but);
  }

  private class ColorHandler implements ActionListener{

    public void actionPerformed(ActionEvent event){
       for(int i=0;i<list.size();i++){
         txt.append(list.get(i).toString());
       }
     }
  }

I hope you understand my code.

Upvotes: 0

Views: 123

Answers (2)

omgBob
omgBob

Reputation: 527

What you want to do is change your main method at the end by adding the following line:

new B(list);

and change the constructor of B to:

public B(ArrayList<String> list)

Then you'll have the values from your list in B as the variable named "list".

Moreover you should kick the following line from B since the Class containing the main method is your starting point, not vice versa.

A a = new A();

Upvotes: 1

stefana
stefana

Reputation: 2626

Create a B class with the list as parameter.

public class A {
    public static void main(String[] args) {
    String[] color= {"red", "blue"};
    List<String> list = new ArrayList<String>();

    for ( String x : joke )
        list.add(x);
    }

    B class = new B(list);
}

Constructor with list parameter in class B

public B(List list){
    ...GUI declarations(layout, etc)
    but = new JButton("Button);
    txt = new JTextField(30);
    add(but);
    add(txt);
    ColorHandler color = new Color
    color.addActionListener(but);

    ArrayList array = list;
}

Upvotes: 0

Related Questions