0

I have a List (List<MyBean>). Then I used it for fill a 2D array. I used following steps to do it.

MyBean.java

public class MyBean{
private int id;
private String name;
private String address;

/**
 * @return the id
 */
public int getId()
{
    return id;
}

/**
 * @param id the id to set
 */
public void setId(int id)
{
    this.id = id;
}

/**
 * @return the name
 */
public String getName()
{
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name)
{
    this.name = name;
}

/**
 * @return the address
 */
public String getAddress()
{
    return address;
}

/**
 * @param address the address to set
 */
public void setAddress(String address)
{
    this.address = address;
}
}    

public void myMethod(List<MyBean> list){
    List<Object> objects = new ArrayList<>();
    for (Object object : list){
          objects.add(object != null ? object : null);
    }

    Object rowData1[][] = new Object[objects.size()][];
    for (int i = 0; i < objects.size(); i++){
          List<Object> row = (ArrayList<Object>)(Object)objects.get(i);
          rowData1[i] = row.toArray(new Object[row.size()]);
    }

    Object columnNames1[] ={"HEADER 1", "HEADER 2", "HEADER 3"};
} 

When I run execute this code I got following exception .

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
MyBean cannot be cast to java.util.ArrayList

The exception is on this line

List<Object> row = (ArrayList<Object>)(Object)objects.get(i);

I use this 2D array for following purpose.

JTable table1 = new TableWithRowHeader(rowData1, columnNames1);
table1.getColumnModel().getColumn(0).setPreferredWidth(120);

JScrollPane scrollPane1 = new JScrollPane(table1);
scrollPane1.setColumnHeaderView(null);

JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
JButton button = new JButton("Add Button");
button.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent ae){
      JDialog dialog = new JDialog();
      dialog.setTitle("terance");
      dialog.setSize(600, 500);
      dialog.setLocationRelativeTo(null);
      dialog.setVisible(true);
}
});

jPanel.removeAll();
jPanel.add(button, BorderLayout.EAST);
jPanel.revalidate();

JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(jPanel, BorderLayout.NORTH);
frame.add(scrollPane1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Here is an example sketch for final result .

enter image description here

How could I handle the exception ?

Have any ideas ?

Thank you .

Terance Wijesuriya
  • 1,928
  • 9
  • 31
  • 61
  • Why are you double casting? `(ArrayList)(Object)objects.get(i);` – OneCricketeer Feb 17 '16 at 05:25
  • First time to a object , then for object list . Am I wrong ? – Terance Wijesuriya Feb 17 '16 at 05:27
  • All Java objects are of the class `Object`. Casting to it is pointless and casting twice makes no sense because the most-left cast takes precedence – OneCricketeer Feb 17 '16 at 05:28
  • I can't figure out what you're trying to do. Your input is a list of `MyBean`s, and you're trying to convert each one to an `ArrayList`. A `MyBean` is not an array or a list. So how can that work? And you can't fool Java by casting it to an `Object` first. It's still a `MyBean`. Is there some reason you think that `MyBean` represents a list of something? – ajb Feb 17 '16 at 05:29
  • What should be correct ? – Terance Wijesuriya Feb 17 '16 at 05:29
  • 3
    I don't know, because I have no idea what you're trying to accomplish. Maybe you should explain in more detail. Give an example of what `list` looks like, and then tell us what you want the 2D array to look like. – ajb Feb 17 '16 at 05:30
  • MyBean is an object . list has several MyBean objects . – Terance Wijesuriya Feb 17 '16 at 05:31
  • *MyBean is an object* ...Exactly, it is not a list, so you cannot cast it to one, so that is your error – OneCricketeer Feb 17 '16 at 05:32
  • 1
    Can you add your `MyBean` code into your question? I also get lost in why are you transforming a perfect typed object `List` into plain objects. There is no point to it. – Jorge Campos Feb 17 '16 at 05:33
  • The ternary is also superfluous at `objects.add(object != null ? object : null)`. Just do `objects.add(object)`, it does the same thing – OneCricketeer Feb 17 '16 at 05:34
  • See the updated code. And I use this 2D array to fill a JTable. – Terance Wijesuriya Feb 17 '16 at 05:38
  • You have 5 headers, but three fields. What do the other two columns contain? – OneCricketeer Feb 17 '16 at 05:39
  • @cricket_007 : Please forget HEADER 4 and Header 5. It is a big mistake. – Terance Wijesuriya Feb 17 '16 at 05:41
  • 1
    You still have not provided enough information. I asked for an example of what you want the 2D array to look like, and all you're giving us are vague statements that don't explain *what you want in your 2D array*. – ajb Feb 17 '16 at 05:41
  • Please see http://stackoverflow.com/questions/20526917/load-arraylist-data-into-jtable – OneCricketeer Feb 17 '16 at 05:45
  • @cricket_007:- It is not like a normal table . I use this question to do this . Please see http://stackoverflow.com/questions/26248084/how-to-display-row-header-on-jtable-instead-of-column-header/26248635#26248635 – Terance Wijesuriya Feb 17 '16 at 05:50
  • What do you mean? The link I gave tells you how to convert an arraylist into a JTable object, which is what you were looking for. The link you provided just has a bunch of extra stuff – OneCricketeer Feb 17 '16 at 06:18
  • @cricket_007 :- Yes , exactly . But my purpose include in it . Could you see a 2D array in the beginning of the code ? I aimed it for my purpose . – Terance Wijesuriya Feb 17 '16 at 06:41

2 Answers2

3

Since you still have not told what you want the 2D array to look like, this is what I interpreted what you wanted.

table sample

Here I load a List<MyBean> of sample data

java.util.List<MyBean> list = new ArrayList<MyBean>();
for (int i = 0; i < 3; i++) {
    MyBean b = new MyBean();
    b.setId(i);
    b.setName("Name " + i);
    b.setAddress("Address " + i);
    list.add(b);
}

Here I load the Object[][] with that List<MyBean>. No casting required.

Object[][] data = new Object[list.size()][];
for (int i = 0; i < list.size(); i++) {
    MyBean b = list.get(i);
    Object[] row = new Object[] { b.getId(), b.getName(), b.getAddress() };
    data[i] = row;
}

Object columnNames1[] = {"HEADER 1", "HEADER 2", "HEADER 3"};

JTable table1 = new TableWithRowHeader(data, columnNames1);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Dear , can you do some changes for your code for me ? Because you are so close to expected answer – Terance Wijesuriya Feb 17 '16 at 07:18
  • Umm, no changes need to be made. You just need to know where to put those 2 blocks of code. That is your task – OneCricketeer Feb 17 '16 at 07:23
  • Actually , I want following purpose . If name is `Header 2` , the whole raw should include with names . – Terance Wijesuriya Feb 17 '16 at 07:33
  • See the updated post . – Terance Wijesuriya Feb 17 '16 at 07:46
  • 1
    To get your picture, you just need to fill in the arraylist differently (and add more fields to `MyBean` if you want 5 columns). I have already shown you how to fill the table. Just think about each "row" in your table representing a single `MyBean`. Then each `Object[] row` in the code is the data for that `MyBean`. – OneCricketeer Feb 17 '16 at 08:20
  • In my idea , each "column" representing a single bean not a row that's what I showed in my picture . You didn't clearly get idea. Now I give you the idea . Tell me your opinion now . – Terance Wijesuriya Feb 18 '16 at 09:46
  • 1
    I tried adding more columns, and the fifth column doesn't appear. I tried less than 3 columns and the program crashes. My opinion is that I don't feel like fixing this code that you took from another question that clearly stated that it might not work – OneCricketeer Feb 18 '16 at 12:36
1
  • In your myMethod you are clearly passing a list of MyBean objects.

  • From this list you are copying every MyBean instance to a new List called objects

  • Then you are looping through objects and doing this: List<Object> row = (ArrayList<Object>)(Object)objects.get(i);

  • But (Object)objects.get(i); here in this code will always return an Object of MyBean and not a list . This you can't typecast to an ArrayList. And thus the error!

You need to modify the code around rowData1 and objects list as per your requirement.

Ravi Ranjan
  • 740
  • 2
  • 10
  • 31
  • Ok . I want to read this `list` and set values to this 2D array using this `list`. How could I do it ? – Terance Wijesuriya Feb 17 '16 at 06:04
  • For a 2D array you should have rows and columns, in this code you are passing just one list. What should be present in this 2D array as row and column? Or is it like you want to put all the MyBean instances in a 2D array? – Ravi Ranjan Feb 17 '16 at 06:09
  • I want to put all MyBean instances in a 2D array. – Terance Wijesuriya Feb 17 '16 at 06:12
  • In that case, how should be the representation in the 2D array, like how many rows and columns. e.g. if the `list` contains 6 instances of `MyBean`, say MB1, MB2, MB3, MB4, MB5, MB6. Then how should these needs to be represented, can you give some illustartion? – Ravi Ranjan Feb 17 '16 at 06:24
  • 2
    @Barrier We know you want to set values in a 2D array. We know you want to use it for a JTable. **We do not know how you want to organize your input into a 2-dimensional array, and you have repeatedly refused to tell us.** What will it take to get you to answer our question????????????? – ajb Feb 17 '16 at 06:30
  • @ajb : - First look at this clearly . http://stackoverflow.com/questions/26248084/how-to-display-row-header-on-jtable-instead-of-column-header/26248635#26248635 . Then try to feed some data into this table using my concept . – Terance Wijesuriya Feb 17 '16 at 06:43
  • 1
    @Barrier Oh, I could feed _some_ data into it. I could just make up some data to feed into it. But I think you want to use data from your list. And you **STILL** are not telling us how. What part of this do you not understand? Let me make it more specific. Your `list` has the elements `MyBean1`, `MyBean2`, `MyBean3`, `MyBean4`, `MyBean5`. You want a 2D array. What, **specifically**, do you want your 2D array to be? And if you say "I want data from the list" or "I want to use it for a JTable", I'm just going to give up. **BE SPECIFIC.** – ajb Feb 17 '16 at 06:48
  • @ajb :- Without this 2D array how could I set columns in vertical on the table ? I think you didn't do what I ask for . – Terance Wijesuriya Feb 17 '16 at 07:13