Olá
Tenho esta classe no meu programa e quando mas não me está a aparecer a janela de escolha de ficheiro.
public class JFilePicker extends JPanel {
private final String textFieldLabel;
private final String buttonLabel;
private final JLabel label;
private final JTextField textField;
private final JButton button;
private final JFileChooser fileChooser;
private int mode;
public static final int MODE_OPEN = 1;
public static final int MODE_SAVE = 2;
public JFilePicker(String textFieldLabel, String buttonLabel) {
this.textFieldLabel = textFieldLabel;
this.buttonLabel = buttonLabel;
fileChooser = new JFileChooser();
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
label = new JLabel(textFieldLabel);
textField = new JTextField(30);
button = new JButton(buttonLabel);
button.addActionListener((ActionEvent evt) -> {
buttonActionPerformed(evt);
});
add(label);
add(textField);
add(button);
}
private void buttonActionPerformed(ActionEvent evt) {
if (mode == MODE_OPEN) {
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
} else if (mode == MODE_SAVE) {
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}
public void addFileTypeFilter(String extension, String description) {
FileTypeFilter filter = new FileTypeFilter(extension, description);
fileChooser.addChoosableFileFilter(filter);
}
public void setMode(int mode) {
this.mode = mode;
}
public String getSelectedFilePath() {
return textField.getText();
}
public JFileChooser getFileChooser() {
return this.fileChooser;
}
}
E o Jframe é este
public class EmailSenderForm extends javax.swing.JFrame {
private final ConfigUtility configUtil = new ConfigUtility();
private final JFilePicker filePicker = new JFilePicker("Anexo", "Anexar...");
public EmailSenderForm() throws IOException {
initComponents();
setLocationRelativeTo(null);
String imagePath = "/img/email_32_32.png";
InputStream imgStream = Entrada.class.getResourceAsStream(imagePath);
BufferedImage myImg = ImageIO.read(imgStream);
setIconImage(myImg);
}
private boolean validarCampos() {
if (fieldTo.getText().equals("")) {
JOptionPane.showMessageDialog(this,
"Introduza o destinatário!",
"Error", JOptionPane.ERROR_MESSAGE);
fieldTo.requestFocus();
return false;
}
if (fieldSubject.getText().equals("")) {
JOptionPane.showMessageDialog(this,
"Introduza o assunto deste email!",
"Error", JOptionPane.ERROR_MESSAGE);
fieldSubject.requestFocus();
return false;
}
if (textAreaMessage.getText().equals("")) {
JOptionPane.showMessageDialog(this,
"Introduza a sua mensagem!",
"Error", JOptionPane.ERROR_MESSAGE);
textAreaMessage.requestFocus();
return false;
}
return true;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
labelPara = new javax.swing.JLabel();
labelAssunto = new javax.swing.JLabel();
labelAnexo = new javax.swing.JLabel();
fieldTo = new javax.swing.JTextField();
fieldSubject = new javax.swing.JTextField();
fieldAnexo = new javax.swing.JTextField();
sendEmail = new javax.swing.JButton();
pesquisarBt = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
textAreaMessage = new javax.swing.JTextArea();
jMenuBar1 = new javax.swing.JMenuBar();
menuPrincipal = new javax.swing.JMenu();
menuItemTools = new javax.swing.JMenuItem();
menuItemExit = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Envio de Email");
setPreferredSize(new java.awt.Dimension(500, 350));
labelPara.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
labelPara.setText("Para:");
labelAssunto.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
labelAssunto.setText("Assunto:");
labelAnexo.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
labelAnexo.setText("Anexo:");
sendEmail.setIcon(new javax.swing.ImageIcon("C:\\Users\\gilca\\Documents\\NetBeansProjects\\gmc.esmaior\\src\\main\\resources\\img\\email_32_32.png")); // NOI18N
sendEmail.setToolTipText("Enviar");
sendEmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendEmailActionPerformed(evt);
}
});
pesquisarBt.setIcon(new javax.swing.ImageIcon("C:\\Users\\gilca\\Documents\\NetBeansProjects\\gmc.esmaior\\src\\main\\resources\\img\\attach_32_32.png")); // NOI18N
pesquisarBt.setToolTipText("Anexo");
pesquisarBt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pesquisarBtActionPerformed(evt);
}
});
textAreaMessage.setColumns(20);
textAreaMessage.setRows(5);
jScrollPane1.setViewportView(textAreaMessage);
menuPrincipal.setText("Ferramentas");
menuItemTools.setText("Definições Conta");
menuPrincipal.add(menuItemTools);
menuItemExit.setText("Sair");
menuPrincipal.add(menuItemExit);
jMenuBar1.add(menuPrincipal);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelPara)
.addComponent(labelAssunto)
.addComponent(labelAnexo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(fieldTo, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(fieldAnexo)
.addComponent(fieldSubject, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sendEmail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(pesquisarBt, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelPara)
.addComponent(fieldTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelAssunto)
.addComponent(fieldSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(sendEmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelAnexo)
.addComponent(fieldAnexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(pesquisarBt)))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void sendEmailActionPerformed(java.awt.event.ActionEvent evt) {
File[] attachFiles = null;
if (!validarCampos()) {
return;
}
String toAddress = fieldTo.getText();
String subject = fieldSubject.getText();
String message = textAreaMessage.getText();
if (!filePicker.getSelectedFilePath().equals("")) {
File selectedFile = new File(filePicker.getSelectedFilePath());
attachFiles = new File[]{selectedFile};
}
try {
Properties smtpProperties = configUtil.loadProperties();
EmailUtility.sendEmail(smtpProperties, toAddress, subject, message, attachFiles);
JOptionPane.showMessageDialog(this, "O e-mail foi enviado com suesso!");
} catch (IOException | MessagingException | HeadlessException ex) {
JOptionPane.showMessageDialog(this, "Erro no envio deste email, tente mais tarde: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void pesquisarBtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(EmailSenderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EmailSenderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EmailSenderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EmailSenderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
try {
new EmailSenderForm().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(EmailSenderForm.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField fieldAnexo;
private javax.swing.JTextField fieldSubject;
private javax.swing.JTextField fieldTo;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelAnexo;
private javax.swing.JLabel labelAssunto;
private javax.swing.JLabel labelPara;
private javax.swing.JMenuItem menuItemExit;
private javax.swing.JMenuItem menuItemTools;
private javax.swing.JMenu menuPrincipal;
private javax.swing.JButton pesquisarBt;
private javax.swing.JButton sendEmail;
private javax.swing.JTextArea textAreaMessage;
// End of variables declaration
}
Não me aparece o botão “Anexar” e se defino o “pesquisarBt” não me anexa o ficheiro no email
Alguma dica??