java - 在 jdialog 表单上显示图像时出错

标签 java swing jlabel

我有一个从 JFrame 调用的 JDialog。此 Jdialog 加载一些从 jframe 传递的数据。我可以加载除图像之外的所有数据。我将此图像传递到一个我有路径的字符串中,并使用方法 (cargarImagen()) 加载它。

这是 JDialog 的代码:

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 txFecha;
private JLabel     lblImagen;
private JTextField txFoto;
/**
 * 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.GROWING_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);
        }
        {
            lblImagen = new JLabel("");
            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);
        }
        {
            txFoto = new JTextField();
            txFoto.setEditable(true);
            panel.add(txFoto, "14, 14, fill, top");
            txFoto.setColumns(10);
        }
        {
            JButton btnCambiar = new JButton("Cambiar imagen");
            btnCambiar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    String path = buscarImagen();
                    cargarImagen(path);

                }
            });
            panel.add(btnCambiar, "14, 12");
        }

    }
    {
        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()));
    txFoto.setText(cs.getFoto());

    //Mostramos la imagen
    cargarImagen(txFoto.getText());

}

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

    return ff;
}

@SuppressWarnings("static-access")
public String buscarImagen(){

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

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

        path = jfc.getSelectedFile().getAbsolutePath();         


    }return path;
}

public void cargarImagen(String path){

    //txFoto.setText(path);
    ImageIcon ii = new ImageIcon(path);
    Icon icono = new ImageIcon(ii.getImage().getScaledInstance(lblImagen.getWidth(), lblImagen.getHeight(), Image.SCALE_DEFAULT));
    lblImagen.setIcon(icono);

}

这是错误代码:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (0) and height (0) must be non-zero
at java.awt.image.ReplicateScaleFilter.<init>(Unknown Source)
at java.awt.Image.getScaledInstance(Unknown Source)
at com.pcastelbon.interfaces.ContactoMantenimiento.cargarImagen(ContactoMantenimiento.java:384)
at com.pcastelbon.interfaces.ContactoMantenimiento.cargarDatos(ContactoMantenimiento.java:350)

更新:

ContactoMantenimiento cmantenimiento = new ContactoMantenimiento();
                       c.setFechaNacimiento(cmantenimiento.parseFecha(txFecha.getText()));          
                cmantenimiento.setTitle("Modificar [ "+c.getNombre()+" "+c.getApellido1()+" ]");
                cmantenimiento.setContacto(c);
                cmantenimiento.cargarDatos(c);
                cmantenimiento.setVisible(true);                    


                //Actualizar tabla
                cargarTabla();

我认为问题在于我调用了 cargarDatos(),它在 setvisible(true) 之前加载数据(包括图像)。但我不能把它放在后面,因为我的 jdialog 是模态的。 有什么想法吗??

最佳答案

错误信息告诉你到底出了什么问题:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (0) and height (0) must be non-zero

我猜是这一行触发了异常:

new ImageIcon(ii.getImage().getScaledInstance(lblImagen.getWidth(), 
       lblImagen.getHeight(), Image.SCALE_DEFAULT));

了解您的 JLabel 的宽度和高度为 0,并且在首次调用 cargarImagen(...) 方法时可能尚未呈现。我会避免在创建时将图像的大小基于标签的当前宽度或高度,并且还会尽可能避免设置大小。如果您需要更多帮助,请创建并发布有效的 minimal example program ,一小段代码是一个完整的程序,只有必要的代码来演示您的问题,我们可以不加修改地复制、粘贴、编译和运行。


But I can´t put it after because my jdialog is modal. Any idea??

是的,再次重申,不要根据 JLabel 的大小来确定图标的大小。同样,请考虑发布我们可以关联的代码,我们可以实际运行的代码,一个演示您的问题的最小代码示例,SSCCE .这将使我们能够运行您的代码并修改它,甚至可能更正它。请在回复之前阅读链接,因为它提供了许多关于 SSCCE 要求的重要细节。您发布了太多代码,其中大部分与手头的问题完全无关,而且其中大部分(包括非核心 Java 布局和我们没有的图像)阻止我们编译和运行您的代码。

关于java - 在 jdialog 表单上显示图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34442616/

相关文章:

java - 我想将 JList 选定的项目附加到 Jtextfield

java - 如何让JPanel填满整个JFrame?

java - 更改窗口大小和 JLabel 的奇怪行为时如何更改字符串长度(以像素为单位计算其宽度)

java - Java 网格布局

java - SomeObject是一个接口(interface),JAXB不能处理接口(interface)

java - 替换 IBM MQ 消息有效负载并使用 Java 中的相同消息进行回复(不带 JMS)

java - 完成xslt新手。如何在xslt 1.0版中合并这2个xml源。应用分组和排序?

java - JPanel从其原始位置向外动态生成

java - 持久化中的默认表前缀

java - 在java中删除选定的图像