有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在jdialog窗体上显示图像时发生java错误

我有一个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是模态的。 有什么想法吗


共 (3) 个答案

  1. # 1 楼答案

    我终于解决了自己设置图标大小的问题。问题是我在构造函数完成之前就得到了jLabel的大小

    问题是:

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

    我就是这样解决的:

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

    我认为有更好的方法来解决这个问题,所以我会继续尝试

    多谢各位

  2. # 2 楼答案

    错误消息会准确地告诉您出了什么问题:

    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布局和我们没有的图像,阻止我们编译和运行你的代码

  3. # 3 楼答案

    系统找不到您的图像,因此在cargarImagen尝试调整该空图像的大小时,会出现一个空图像图标,然后出现一个IllegalArgumentException

    尝试此操作以检查请求的映像是否存在:

    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;
        }
    }