为什么JFrame背景图像不起作用?

时间:2015-10-20 16:09:10

标签: java swing jframe

我正在尝试显示背景图像,但它无法正常工作,我已经尝试了多次回复此错误的事情。每次它说复制字段我都不知道这意味着我是java的初学者

这是错误

Exception in thread "main" java.lang.ClassFormatError: Duplicate field        name&signature in class file search/text/file/SearchTextFile$1
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at search.text.file.SearchTextFile.<init>(SearchTextFile.java:46)
at search.text.file.SearchTextFile.main(SearchTextFile.java:42)
Java Result: 1

此尝试阻止导致背景错误:

    try {            
    BufferedImage img = ImageIO.read(new File("bible.jpg"));
    } catch(IOException e ) {

    }

谢谢

Java代码:            package search.text.file;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SearchTextFile {

public static void main(String[] args) {
    new SearchTextFile();
}

public SearchTextFile() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }


            JFrame frame = new JFrame("Bible Search");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new TestPane());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
try {            
BufferedImage img = ImageIO.read(new File("bible.jpg"));
} catch(IOException e ) {
}
});


}

public class TestPane extends JPanel {

    private JTextField findText;
    private JButton search;
    private DefaultListModel<String> model;
    private JList list;

    private String searchPhrase;

    public TestPane() {
        setLayout(new BorderLayout());
        JPanel searchPane = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(2, 2, 2, 2);
        searchPane.add(new JLabel("Find: "), gbc);
        gbc.gridx++;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1;
        findText = new JTextField(20);
        searchPane.add(findText, gbc);

        gbc.gridx++;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        search = new JButton("Search");
        searchPane.add(search, gbc);

        add(searchPane, BorderLayout.NORTH);

        model = new DefaultListModel<>();
        list = new JList(model);
        list.setCellRenderer(new HighlightListCellRenderer());
        add(new JScrollPane(list));

        ActionHandler handler = new ActionHandler();

        search.addActionListener(handler);
        findText.addActionListener(handler);

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("bible.txt")))) {

            String text = null;
            while ((text = reader.readLine()) != null) {
                model.addElement(text);
            }

        } catch (IOException exp) {

            exp.printStackTrace();

        }
    }

    public class ActionHandler implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            searchPhrase = findText.getText();
            if (searchPhrase != null && searchPhrase.trim().length() == 0) {
                searchPhrase = null;
            }
            list.repaint();
//              model.removeAllElements();
////                    BufferedReader reader = null;
//
//              String searchText = findText.getText();
//              try (BufferedReader reader = new BufferedReader(new     FileReader(new File("bible.txt")))) {
//
//                  String text = null;
//                  while ((text = reader.readLine()) != null) {
//
//                      if (text.contains(searchText)) {
//
//                          model.addElement(text);
//
//                      }
//
//                  }
//
//              } catch (IOException exp) {
//
//                  exp.printStackTrace();
//                  JOptionPane.showMessageDialog(TestPane.this, "Something Went     Wrong", "Error", JOptionPane.ERROR_MESSAGE);
//
//              }
        }
    }

    public class HighlightListCellRenderer extends DefaultListCellRenderer {

        public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if (value instanceof String && searchPhrase != null) {
                String text = (String) value;
                if (text.contains(searchPhrase)) {
                    text = text.replace(" ", "&nbsp;");
                    value = "<html>" + text.replace(searchPhrase, "<span STYLE='background-color: #ffff00'>" + searchPhrase + "</span>") + "</html>";
                }
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
        }

    }
}
}

2 个答案:

答案 0 :(得分:3)

你的尝试阻止:

try {            
BufferedImage img = ImageIO.read(new File("bible.jpg"));
} catch(IOException e ) {
}
});

不在任何方法或构造函数之外,这是不允许的。我建议你

  1. 将其移至构造函数或方法中。
  2. 请勿忽略您正在执行的例外情况,因为这是非常危险的编码。至少打印出异常的堆栈跟踪。
  3. 另外,为什么你在阅读图像但却什么都不做呢?

    e.g。

    public class SearchTextFile2 {
    
        private static void createAndShowGui() {
            BufferedImage img = null;
            try {
                // better to get as a resource and not as a File
                img = ImageIO.read(new File("bible.jpg"));
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            JFrame frame = new JFrame("SearchTextFile2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new TestPane(img)); // pass image into TestPane
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    
        // make TestPane a static inner class
        // have TestPane display image within its paintComponent method
        public static class TestPane extends JPanel {
            private JTextField findText;
            private JButton search;
            private DefaultListModel<String> model;
            private JList list;
            private BufferedImage img;
            private String searchPhrase;
    
            public TestPane(BufferedImage img) {
                setLayout(new BorderLayout());
                this.img = img;
                // etc.....
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (img != null) {
                    g.drawImage(img, 0, 0, this);
                }
            }
            // .....
    

答案 1 :(得分:2)

看起来你放在一个文件中的所有类可能会在你的情况下被搞乱 请检查java文档是否有错误

  

Java虚拟机尝试读取类文件并确定它   文件格式错误或无法解释为类   文件

http://docs.oracle.com/javase/7/docs/api/java/lang/ClassFormatError.html