访问 jLabel 时出错

Error accessing jLabel

我正在使用 WindowBuilder 在 Eclipse 中编写一个简单的程序。

我编码了 2 个 windows、一个 JFrame 和一个 JDialogJdialog 包含一些 Jlabel,我想在其中一个中显示图像。我读过它可以创建一个 ImageIcon 并使用 setIcon() 将其设置为标签。问题是我无法从任何地方访问标签。

在方法cargarImagen()的最后一行

代码如下:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.pcastelbon.dao.ContactoJDBCImpl;
import com.pcastelbon.entity.Contacto;
import com.jgoodies.forms.layout.FormSpecs;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;

public class ContactoMantenimiento extends JDialog {

/**
 * 
 */
private static final long serialVersionUID = 6291928431785031824L;
ContactoJDBCImpl cc= new ContactoJDBCImpl();
private Contacto c;
private final JPanel contentPanel = new JPanel();
private JTextField txId;
private JTextField txNombre;
private JTextField txApellido1;
private JTextField txApellido2;
private JTextField txTelefono;
private JTextField txDireccion;
private JTextField txCp;
private JTextField txCiudad;
private JTextField txEmail;
private JTextField txFoto;
private JTextField txFecha;

/**
 * Launch the application.
 */
/**public static void main(String[] args) {
    try {
        ContactoMantenimiento dialog = new ContactoMantenimiento();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}**/

/**
 * Create the dialog.
 */
public ContactoMantenimiento() {
    setModal(true);

    setBounds(100, 100, 588, 300);
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    contentPanel.setLayout(new BorderLayout(0, 0));
    {
        JPanel panel = new JPanel();
        contentPanel.add(panel, BorderLayout.CENTER);
        panel.setLayout(new FormLayout(new ColumnSpec[] {
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                ColumnSpec.decode("default:grow"),
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                ColumnSpec.decode("default:grow"),
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.BUTTON_COLSPEC,
                FormSpecs.RELATED_GAP_COLSPEC,
                FormSpecs.DEFAULT_COLSPEC,},
            new RowSpec[] {
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                RowSpec.decode("6dlu"),
                FormSpecs.DEFAULT_ROWSPEC,
                FormSpecs.RELATED_GAP_ROWSPEC,
                FormSpecs.DEFAULT_ROWSPEC,}));
        {
            JLabel lblId = new JLabel("Id");
            panel.add(lblId, "4, 4, right, default");
        }
        {
            txId = new JTextField();
            txId.setEditable(false);
            panel.add(txId, "6, 4, fill, default");
            txId.setColumns(10);
        }
        {
            JLabel lblDireccin = new JLabel("Dirección");
            panel.add(lblDireccin, "8, 4, right, default");
        }
        {
            txDireccion = new JTextField();
            panel.add(txDireccion, "10, 4, fill, default");
            txDireccion.setColumns(10);
        }
        {
            JLabel lblImagen = new JLabel("New label");
            panel.add(lblImagen, "14, 4, 1, 7");
        }
        {
            JLabel lblNombre = new JLabel("Nombre");
            panel.add(lblNombre, "4, 6, right, default");
        }
        {
            txNombre = new JTextField();
            panel.add(txNombre, "6, 6, fill, default");
            txNombre.setColumns(10);
        }
        {
            JLabel lblCdigoPostal = new JLabel("Código postal");
            panel.add(lblCdigoPostal, "8, 6, right, default");
        }
        {
            txCp = new JTextField();
            panel.add(txCp, "10, 6, fill, default");
            txCp.setColumns(10);
        }
        {
            JLabel lblPrimerApellido = new JLabel("Primer apellido");
            panel.add(lblPrimerApellido, "4, 8, right, default");
        }
        {
            txApellido1 = new JTextField();
            panel.add(txApellido1, "6, 8, fill, default");
            txApellido1.setColumns(10);
        }
        {
            JLabel lblCiudad = new JLabel("Ciudad");
            panel.add(lblCiudad, "8, 8, right, default");
        }
        {
            txCiudad = new JTextField();
            panel.add(txCiudad, "10, 8, fill, default");
            txCiudad.setColumns(10);
        }
        {
            JLabel lblSegundoApellido = new JLabel("Segundo apellido");
            panel.add(lblSegundoApellido, "4, 10, right, default");
        }
        {
            txApellido2 = new JTextField();
            panel.add(txApellido2, "6, 10, fill, default");
            txApellido2.setColumns(10);
        }
        {
            JLabel lblTelfono = new JLabel("Teléfono");
            panel.add(lblTelfono, "8, 10, right, default");
        }
        {
            txTelefono = new JTextField();
            panel.add(txTelefono, "10, 10, fill, default");
            txTelefono.setColumns(10);
        }
        {
            JLabel lblFechaNacimiento = new JLabel("Fecha nacimiento");
            panel.add(lblFechaNacimiento, "4, 12, right, default");
        }
        {
            txFecha = new JTextField();
            panel.add(txFecha, "6, 12, fill, top");
            txFecha.setColumns(10);
        }
        {
            JLabel lblEmail = new JLabel("Email");
            panel.add(lblEmail, "8, 12, right, default");

        }
        {
            txEmail = new JTextField();
            panel.add(txEmail, "10, 12, fill, default");
            txEmail.setColumns(10);
        }
        {
            JButton btnCambiar = new JButton("Cambiar imagen");
            btnCambiar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    cargarImagen();

                }
            });
            panel.add(btnCambiar, "14, 12");
        }
        {
            txFoto = new JTextField();
            panel.add(txFoto, "14, 14, fill, default");
            txFoto.setColumns(10);
        }
    }
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton btAceptar = new JButton("Aceptar");
            btAceptar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {

                    Boolean correcto = false;
                    String id= txId.getText();
                    Contacto c = new Contacto();
                    Date fecha=null;
                    fecha = parseFecha (txFecha.getText());

                    if (txId.getText().length()>0){
                        c.setIdContacto(Integer.parseInt(txId.getText()));
                    }
                    c.setNombre(txNombre.getText());
                    c.setApellido1(txApellido1.getText());
                    c.setApellido2(txApellido2.getText());
                    c.setDireccion(txDireccion.getText());
                    c.setCp(txCp.getText());
                    c.setCiudad(txCiudad.getText());
                    c.setEmail(txEmail.getText());                                      
                    c.setFechaNacimiento(fecha);
                    c.setTelefono(txTelefono.getText());
                    c.setFoto(txFoto.getText());

                    if(id.equalsIgnoreCase("")){

                        correcto = cc.insertarContacto(c);

                    }else{

                        correcto = cc.actualizarContacto(c);

                    }
                    if (!correcto){

                        JOptionPane.showMessageDialog(getParent(), "Error al actualizar la base de datos" );

                    }else{

                        JOptionPane.showMessageDialog(getParent(), "Base de datos actualizada" );
                    }
                    dispose();

                }
            });
            btAceptar.setActionCommand("OK");
            buttonPane.add(btAceptar);
            getRootPane().setDefaultButton(btAceptar);
        }
        {
            JButton btCancelar = new JButton("Cancelar");
            btCancelar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            });
            btCancelar.setActionCommand("Cancel");
            buttonPane.add(btCancelar);
        }
    }

}

public Contacto getContacto(){

    return this.c;

}

public void setContacto (Contacto c){

    this.c= c;

}
/*
 * 
 * Método que convierte un string en una fecha con el formato requerido
 */
public Date parseFecha(String fecha){

    Date fechaDate = null;
    SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");

    try {
        fechaDate = formato.parse(fecha);

    } 
    catch (ParseException ex) 
    {
        System.out.println(ex);
    }
    return fechaDate;
}
/**
 * Método que carga los datos al inicio
 */
public  void cargarDatos(Contacto cs){

    //Rellenamos los datos del formulario

    txId.setText(Integer.toString(cs.getIdContacto()));
    txNombre.setText(cs.getNombre());
    txApellido1.setText(cs.getApellido1());
    txApellido2.setText(cs.getApellido2());
    txTelefono.setText(cs.getTelefono());
    txDireccion.setText(cs.getDireccion());
    txCp.setText(cs.getCp());
    txCiudad.setText(cs.getCiudad());
    txEmail.setText(cs.getEmail());
    txFecha.setText(formatearFecha(cs.getFechaNacimiento()));

}

String formatearFecha (Date fecha){
    String ff;
    SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
    ff=sdf.format(fecha);

    return ff;
}

public void cargarImagen(){

    JFileChooser jfc = new JFileChooser();
    FileNameExtensionFilter filtroImagen=new FileNameExtensionFilter("JPG, PNG & GIF","jpg","png","gif");
    jfc.setFileFilter(filtroImagen);
    int opcion = jfc.showOpenDialog(getParent());

    //Si pulsamos en aceptar
    if (opcion==jfc.APPROVE_OPTION){

        File imagen = jfc.getSelectedFile();
        String path = imagen.getAbsolutePath();
        txFoto.setText(path);
        ImageIcon ii = new ImageIcon(path);

        lblImagen.setIcon(ii);

    }
}

我可以访问任何 JTextField,但不能访问 Jlabel。另一方面 Jframe 我可以毫无问题地访问 JLabels

您应该将标签 'lblImagen' 设为 class 的一个字段(就像各种文本字段一样)。

目前它只能在您创建它的地方使用。