Java:如果声明了'值'一个ImageIcon

时间:2016-11-10 14:47:16

标签: java image netbeans imageicon

我有一个带有文本字段,标签(用于图像)和按钮的小程序。当我按下按钮时,它显示标准图像。

但是,如果文本字段的输入等于某个字符串,我想更改图片," car"例如。

当我使用它时,我得到了我已经定义的错误'照片'作为变量:

if ("car".equals(input)) {
    ImageIcon foto =  ImageIcon("C:......png");

这是代码中最重要的部分:

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String input = textfield.getText();
    ImageIcon foto = new ImageIcon("C:.......png");
    label.setIcon(foto);

这是完整的代码:

主要课程:

package test4;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class Test4 extends JFrame
{       

    public static void main(String[] args) {
        test5 frame = new test5();
        frame.setVisible(true);
    }

}

"摆动"类:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test4;

import javax.swing.ImageIcon;

/**
 *
 * @author
 */
public class test5 extends javax.swing.JFrame {

    /**
     * Creates new form test5
     */
    public test5() {
        initComponents();
    }

    /**
     * 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() {

        textfield = new javax.swing.JTextField();
        label = new javax.swing.JLabel();
        button = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        button.setText("Show");
        button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(121, 121, 121)
                        .addComponent(textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(100, 100, 100)
                        .addComponent(label, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(147, 147, 147)
                        .addComponent(button)))
                .addContainerGap(124, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(label, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(button)
                .addContainerGap(63, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                       
        String input = textfield.getText();
        ImageIcon foto = new ImageIcon("C:\\Users\\Jordii\\Pictures\\music.png");
        label.setIcon(foto);

    }                                      

    /**
     * @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(test5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(test5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(test5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(test5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new test5().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton button;
    private javax.swing.JLabel label;
    private javax.swing.JTextField textfield;
    // End of variables declaration                   
}

所以我的问题是:是否有其他方式根据文本字段的输入显示图片?

例如:如果输入是&#39; car&#39;,则显示汽车的图片。如果输入是&#39; house&#39;,则显示房屋的图片。否则,显示一辆自行车的照片。

1 个答案:

答案 0 :(得分:0)

看,你的代码不是很漂亮。因此,要在代码中进行操作,您需要获取它的功能。

除此之外,回答你的问题:

如果您收到错误说...已经定义,那么......已经定义了。 就这么简单。 此示例将向您展示其工作原理:

package test.project.main;

public class Main {

    public static void main(String[] args) {
        int a = 10;
        String a = "10";
    }
}

如果您尝试运行上面的代码,编译器会发出警告并说您已经定义了名为a的变量。如果仍继续运行代码,则会抛出运行时异常:

  

线程中的异常&#34; main&#34; java.lang.Error:未解决的编译问题:       重复的局部变量a at test.project.main.Main.main(Main.java:7)

现在回到您的foto示例。

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String input = textfield.getText();

    ImageIcon foto = new ImageIcon("C:.....png");
    if ("car".equals(input))
        ImageIcon foto = new ImageIcon("C:......png");

    label.setIcon(foto);
}

在这里你可以看到已经定义了foto,编译器会警告你这件事。如果您运行代码并且if语句为真(因为输入等于&#39; car&#39;)那么您将获得运行时异常,请注意:如果您有编译器错误,您可能会在运行时收到 Unresolved compilation 错误消息。

您可以通过避免在同一方法e.a中使用重复名称来解决此问题。 fotofoto1等 更好的方法是创建一个变量foto,并在运行时设置它。下面的例子将解释这是如何工作的:

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String input = textfield.getText();

    ImageIcon foto;
    if ("car".equals(input))
        foto = new ImageIcon("C:......png");
    else if ("plane".equals(input))
        foto = new ImageIcon("C:......png");
    else if ("bike".equals(input))
        foto = new ImageIcon("C:......png");
    else
        foto = new ImageIcon("C:......png");

    label.setIcon(foto);
}