问题
I am trying to receive mails from my email account. But i am not able to store it in jtable
. I want to do this because when one row is selected the contents will be displayed in jTextArea
. This is my code snippet.
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);
}
}
I am getting error in this line
jTable2.add(msg);
How am I supposed to do it..
回答1:
add is used to add components to a container rather than data to the JTable
. You could create a custom AbstractTableModel
specifically for storing Message
references
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);
}
}
来源:https://stackoverflow.com/questions/22591836/receiving-emails-and-storing-it-in-jtable