接收电子邮件并将其存储在jTable中

时间:2014-03-23 13:57:48

标签: java javamail netbeans-7

我正在尝试从我的电子邮件帐户接收邮件。但我无法将其存储在jtable中。我想这样做是因为当选择一行时,内容将显示在jTextArea中。这是我的代码段。

public void connect() {
    final String pass = set.pass;
    final String user = set.uname;
    try {

        Properties props = new Properties();

        props.put("mail.imap.host", "imap.gmail.com");

        props.put("mail.imap.socketFactory", 995);

        props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        props.put("mail.imap.port", 995);

        Session session = Session.getDefaultInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, pass);

                }
            });


        Store store = session.getStore("imap");

        store.connect("imap.gmail.com", "mymail@gmail.com", "mypaswword");

        Folder folder = store.getFolder("INBOX");

        folder.open(Folder.READ_ONLY);

        Message[] msg = folder.getMessages();

        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(msg, profile);
        jTable2.add(msg);


        folder.close(true);
        store.close();

    } catch (Exception e) {
        System.out.println(e);
    }
}

我在这一行收到错误

jTable2.add(msg);

我该怎么做..

1 个答案:

答案 0 :(得分:1)

add用于向容器添加组件,而不是向JTable添加数据。您可以专门为存储AbstractTableModel引用

创建自定义Message
public class MessageTableModel extends AbstractTableModel {

    private List<Message> messages;

    public MessageTableModel(List<Message> messages) {

        this.messages = new ArrayList<Message>(messages);
    }

    @Override
    public int getRowCount() {
        return messages.size();
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {

        Object value = "??";
        Message message = messages.get(rowIndex);
        switch (columnIndex) {
            case 0:
                StringBuilder builder = new StringBuilder();

                for (Address a: message.getFrom()) {
                    builder.append(a);
                    builder.append(",");
                }
                value = builder.toString();
                break;

            case 1:
                value = message.getSubject();
                break;
        }

        return value;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return String.class;
    }

    /* Override this if you want the values to be editable...
    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        //....
    }
    */

    /**
     * This will return the Message at the specified row...
     * @param row
     * @return 
     */
    public Message getMessageAt(int row) {
        return messages.get(row);
    }
}