简体   繁体   English

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

[英]Error showing image on jdialog form

I have a JDialog called from a JFrame. 我有一个从JFrame调用的JDialog。 This Jdialog load some data passed from the jframe.I can load all data ok except an image. 这个Jdialog加载了一些从jframe传递的数据。我可以加载除图像之外的所有数据。 I´m passign this image in a String in which I have the path, and load it using a method (cargarImagen()). 我将这个图像传递给我有路径的字符串,并使用方法(cargarImagen())加载它。

This is the code of the JDialog: 这是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);

}

And this is the error code: 这是错误代码:

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)

UPDATE: 更新:

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();

I think that the problem is that I am calling cargarDatos(), which load the data (included the image), before the setvisible(true). 我认为问题在于我调用cargarDatos(),它在setvisible(true)之前加载数据(包括图像)。 But I can´t put it after because my jdialog is modal. 但我不能把它放在后面,因为我的jdialog是模态的。 Any idea?? 任何想法??

The error message is telling you exactly what is wrong: 错误消息告诉您确切的错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (0) and height (0) must be non-zero 线程“AWT-EventQueue-0”中的异常java.lang.IllegalArgumentException:Width(0)和height(0)必须为非零

I'm guessing that it's this line that's tripping the exception: 我猜这是绊倒异常的这条线:

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

Understand that your JLabel has width and height of 0 and likely has not been rendered at the time that cargarImagen(...) method is first called. 了解您的JLabel的宽度和高度为0,并且可能在首次调用cargarImagen(...)方法时尚未呈现 I would avoid basing the size of the image on the label's current width or height at creation time, and also would avoid setting sizes as much as possible. 我会避免在创建时将图像的大小基于标签的当前宽度或高度,并且还会尽可能避免设置尺寸。 If you need more help, create and post a valid minimal example program , a much smaller piece of code that is a complete program that only has necessary code to demonstrate your problem, and that we can copy, paste, compile and run without modification. 如果您需要更多帮助,请创建并发布一个有效的最小示例程序 ,一个更小的代码片段,它是一个完整的程序,只有必要的代码来演示您的问题,并且我们可以复制,粘贴,编译和运行而无需修改。


But I can´t put it after because my jdialog is modal. 但我不能把它放在后面,因为我的jdialog是模态的。 Any idea?? 任何想法??

Yes, again, don't base the size of the icons on the size of the JLabel. 是的,再次,不要将图标的大小基于JLabel的大小。 Again, please consider posting code that we can relate to, that we can actually run, a minimal code example that demonstrates your problem, an SSCCE . 再次,请考虑发布我们可以关联的代码,我们可以实际运行的代码,一个演示您的问题的最小代码示例,一个SSCCE This will allow us to run your code and modify it and perhaps even correct it. 这将允许我们运行您的代码并对其进行修改,甚至可能更正它。 Please read the link before replying as it supplies many important details on the SSCCE requirements. 请在回复前阅读链接,因为它提供了有关SSCCE要求的许多重要细节。 You've posted way too much code, most of it completely unrelated to the problem at hand, and much of it, including non-core Java layouts, and images we don't have, that prevent us from compiling and running your code. 您发布的代码太多了,其中大部分代码与手头的问题完全无关,其中大部分代码(包括非核心Java布局)和我们没有的图像都阻止我们编译和运行代码。

Your image can't be found by the system, and so you get an empty ImageIcon and then a IllegalArgumentException when trying to resize that empty image at cargarImagen . 系统无法找到您的图像,因此当您尝试在cargarImagen上调整该空图像的大小时,您会得到一个空的ImageIcon,然后是一个IllegalArgumentException。

Try this to check if the requested image exists: 尝试此操作以检查所请求的图像是否存在:

public ImageIcon checkImagePath(String path) {
    URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

I finally solved the problem setting the size of the icon by myself. 我终于解决了自己设置图标大小的问题。 The problem was I was getting the size of the jLabel before the constructor finish. 问题是我在构造函数完成之前得到了jLabel的大小。

Here was the problem: 这是问题所在:

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

And that´s how I solved it: 这就是我如何解决它:

 new ImageIcon(ii.getImage().getScaledInstance(150,200, Image.SCALE_DEFAULT));

I think there is a better way to solve this, so I will keep on trying. 我认为有更好的方法可以解决这个问题,所以我会继续努力。

Thank you very much. 非常感谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM