如何从arraylist填充jframe表? [英] How to fill a jframe table from an arraylist?
问题描述
我有一个使用Java GUI创建的jtable,需要从arraylist进行填充.我不熟悉Java,也不知道如何填充jTable.我不知道是否需要使用TableModel或仅使用JTable table = new JTable(data,columnNames).这是我的代码:
I have a jtable that I created using java GUI and I need to fill from an arraylist. I'm not familiar with java and I have no idea how to fill a jTable. I don't know if I need to use TableModel or just JTable table = new JTable(data, columnNames). This is my code:
public void filltable(){
ArrayList A=new ArrayList();
jframe4 j=new jframe4();
String m=j.getloggedemail();
// A=s.getEmails(m);
//this is an example of my arraylist
A.add("sender@gmail.com");
A.add("my subject");
A.add("hiiii");
try {
String[] columnNames = {"Sender",
"Subject",
"Body",
};
//here I need to fill my table
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
这是我需要填写的jTable1声明:
This is the declaration of jTable1 that I need to fill:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"Sender", "Subject", "Body"
}
));
jScrollPane1.setViewportView(jTable1);
推荐答案
我不知道我是否需要使用TableModel或仅使用JTable table = new JTable(data,columnNames)
I don't know if I need to use TableModel or just JTable table = new JTable(data, columnNames)
根据您的需要,您可以选择其中一种.我将演示如何使用后者.如果要使用自己的TableModel
,请参阅@Andrew Thompson评论中的链接.
Depends on your needs, you can do either. I will demonstrate how to use the latter. If you want to use your own TableModel
, see the link in @Andrew Thompson's comment.
public class Example extends JFrame {
Example() {
String[] colNames = new String[] {"Sender", "Subject", "Body"};
List<String> list = new ArrayList<>();
list.add("sender@gmail.com");
list.add("my subject");
list.add("hiiii");
list.add("sender2@gmail.com");
list.add("my subject2");
list.add("hiiii2");
String[][] rowData = new String[list.size() / colNames.length][colNames.length];
for (int i = 0; i < rowData.length; i++) {
for (int j = 0; j < rowData[i].length; j++) {
rowData[i][j] = list.get(i * colNames.length + j);
}
}
JTable table = new JTable(rowData, colNames);
add(new JScrollPane(table));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
请注意,如果列表中连续不包含3个元素,则不会显示整行.
Just note that if the list does not contain 3 elements in a row, the whole row will not be displayed.
这篇关于如何从arraylist填充jframe表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!