如何使用本地存储的原始路径设置JFrame的图标

时间:2014-07-17 16:58:45

标签: java image swing jframe calculator

我需要一些帮助,将JFrame的标题栏图标设置为我计算机中的图像。

我意识到计算器不完整。我仍然需要添加操作,但我只是想先这样做。

如果你能专注于实际问题,那就太惊人了。请不要提出类似设置特定CLASSPATH的建议。我想使用相对位置和排序从我的计算机中获取图片而不使用。我之前尝试过使用相对位置,但是失败了。

此程序正在 BlueJ 上完成,原因仅限于个人偏好。

图像尝试的代码在Calculator方法下......

文件路径为" C:/Users/Charlie/Downloads/smiley.png "

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.BorderFactory.*;
import java.lang.*;

public class Calculator{
    JFrame f = new JFrame("Calculator");
    private String word = "";
    JTextField tf = new JTextField("0");
    public static void main(){
        Calculator Run = new Calculator();
    }
    public Calculator(){
        //URL url = new URL("file:/C:/Users/Charlie/Downloads/smiley.png");
        try{
            javax.swing.UIManager.setLookAndFeel(new
                com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
        }catch(Exception e){}
        ImageIcon img = new ImageIcon("file:/C:/Users/Charlie/Downloads/smiley.png");
        f.setIconImage(img.getImage());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);

        JButton one, two, three, four, five, six, seven, eight, nine, zero, back, ce;
        one = new JButton("1");
        two = new JButton("2");
        three = new JButton("3");
        four = new JButton("4");
        five = new JButton("5");
        six = new JButton("6");
        seven = new JButton("7");
        eight = new JButton("8");
        nine = new JButton("9");
        zero = new JButton("0");
        back = new JButton("<-");
        ce = new JButton("CE");
        one.setPreferredSize(new Dimension(50, 40));
        two.setPreferredSize(new Dimension(50, 40));
        three.setPreferredSize(new Dimension(50, 40));
        four.setPreferredSize(new Dimension(50, 40));
        five.setPreferredSize(new Dimension(50, 40));
        six.setPreferredSize(new Dimension(50, 40));
        seven.setPreferredSize(new Dimension(50, 40));
        eight.setPreferredSize(new Dimension(50, 40));
        nine.setPreferredSize(new Dimension(50, 40));
        zero.setPreferredSize(new Dimension(50, 40));
        back.setPreferredSize(new Dimension(50, 40));
        ce.setPreferredSize(new Dimension(50, 40));
        one.setActionCommand("1");
        two.setActionCommand("2");
        three.setActionCommand("3");
        four.setActionCommand("4");
        five.setActionCommand("5");
        six.setActionCommand("6");
        seven.setActionCommand("7");
        eight.setActionCommand("8");
        nine.setActionCommand("9");
        zero.setActionCommand("0");
        back.setActionCommand("back");
        ce.setActionCommand("ce");
        one.addActionListener(al);
        two.addActionListener(al);
        three.addActionListener(al);
        four.addActionListener(al);
        five.addActionListener(al);
        six.addActionListener(al);
        seven.addActionListener(al);
        eight.addActionListener(al);
        nine.addActionListener(al);
        zero.addActionListener(al);
        back.addActionListener(al);
        ce.addActionListener(al);
        one.addKeyListener(kl);
        two.addKeyListener(kl);
        three.addKeyListener(kl);
        four.addKeyListener(kl);
        five.addKeyListener(kl);
        six.addKeyListener(kl);
        seven.addKeyListener(kl);
        eight.addKeyListener(kl);
        nine.addKeyListener(kl);
        zero.addKeyListener(kl);
        back.addKeyListener(kl);
        ce.addKeyListener(kl);
        f.addKeyListener(kl);

        tf.setPreferredSize(new Dimension(130, 25));
        tf.setEditable(false);
        tf.setHorizontalAlignment(JTextField.RIGHT);

        TitledBorder t0, t1, t2;
        t0 = BorderFactory.createTitledBorder(" Input ");
            t1 = BorderFactory.createTitledBorder(" Operations ");
        t2 = BorderFactory.createTitledBorder(" Output ");

        JPanel p0, p1, p2, p3, p4, p5, p6;
        p0 = new JPanel();
        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        p4 = new JPanel();
        p5 = new JPanel();
        p6 = new JPanel();
        p0.add(tf);
        p0.setBorder(t2);
        p1.add(one); p1.add(two); p1.add(three);
        p2.add(four); p2.add(five); p2.add(six);
        p3.add(seven); p3.add(eight); p3.add(nine);
        p4.add(ce);p4.add(zero); p4.add(back);
        p5.add(p1); p5.add(p2); p5.add(p3); p5.add(p4);
        p5.setLayout(new BoxLayout(p5, BoxLayout.PAGE_AXIS));
        p5.setBorder(t0);
        p6.add(p0); p6.add(p5);
        p6.setLayout(new BoxLayout(p6, BoxLayout.PAGE_AXIS));
        p6.addKeyListener(kl);

        f.add(p6);
        f.pack();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        f.setLocation(dim.width/2 - f.getSize().width/2, dim.height/2 - f.getSize().height/2);
        f.setVisible(true);
    }
    KeyListener kl = new KeyAdapter(){
        public void keyPressed(KeyEvent e){
            if(word.length() == 1 && word.equals("0")){
                word = "";
            }
            if(e.getKeyCode() == KeyEvent.VK_1)
                word += "1";
            else if(e.getKeyCode() == KeyEvent.VK_2)
                word += "2";
            else if(e.getKeyCode() == KeyEvent.VK_3)
                word += "3";
            else if(e.getKeyCode() == KeyEvent.VK_4)
                word += "4";
            else if(e.getKeyCode() == KeyEvent.VK_5)
                word += "5";
            else if(e.getKeyCode() == KeyEvent.VK_6)
                word += "6";
            else if(e.getKeyCode() == KeyEvent.VK_7)
                word += "7";
            else if(e.getKeyCode() == KeyEvent.VK_8)
                word += "8";
            else if(e.getKeyCode() == KeyEvent.VK_9)
                word += "9";
            else if(e.getKeyCode() == KeyEvent.VK_0)
                word += "0";
            else if(word.length() > 1 && e.getKeyCode() == KeyEvent.VK_BACK_SPACE){
                word = word.substring(0, word.length()-1);
            }
            else if((word.length() == 1 && e.getKeyCode() == KeyEvent.VK_BACK_SPACE) || 
                     e.getKeyCode() == KeyEvent.VK_CONTROL ||
                    (word.length() == 0 && e.getKeyCode() == KeyEvent.VK_BACK_SPACE))
                word = "0";
            else
                word = word;

            tf.setText(word);
        }
    };
    ActionListener al = new ActionListener(){
        public void actionPerformed(ActionEvent e){
            String action = e.getActionCommand();
            if(word.length() == 1 && word.equals("0")){
                word = "";
            }
            if(action.equals("1"))
                word += "1";
            else if(action.equals("2"))
                word += "2";
            else if(action.equals("3"))
                word += "3";
            else if(action.equals("4"))
                word += "4";
            else if(action.equals("5"))
                word += "5";
            else if(action.equals("6"))
                word += "6";
            else if(action.equals("7"))
                word += "7";
            else if(action.equals("8"))
                word += "8";
            else if(action.equals("9"))
                word += "9";
            else if(action.equals("0"))
                word += "0";
            else if(word.length() > 1 && action.equals("back")){
                word = word.substring(0, word.length()-1);
            }
            else if((word.length() == 1 && action.equals("back")) || action.equals("ce") ||
                     (word.length() == 0 && action.equals("back")))
                word = "0";
            tf.setText(word);
        }
    };
}


编辑(0)

好吧,我找到了另一种获取图像的解决方案。我仍然不确定如何在没有参考的情况下抓取图像。我最终创建了一个单独的类来抓取图像,加载它们并将它们拉入使用。这是图像类的代码:

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageMake{
    private String path;
    private int[] pixels;
    public BufferedImage img;
    // You can make img static depending on how you use it.

    public ImageMake(String path){
        this.path = path;
        load();
    }
    public void load(){
        try{
            img = ImageIO.read(ImageMake.class.getResource(path));
            int w = img.getWidth();
            int h = img.getHeight();
            pixels = new int[w * h];
            img.getRGB(w, h, 0, 0, pixels, 0, w);
        }catch(IOException e){e.printStackTrace();}
    }
}

在我继续之前,我想说ImageMake.class部分可以互换为getClass(),因此声明最终将成为:

img = ImageIO.read(getClass().getResource(path));

所以现在,在另一个课程中,你会做同样的事情:

// Your code...
ImageMake image = new ImageMake("/res/textures/smiley.png");
genericJFrame.setIconImage(image.img); // This is just a random JFrame
// More of your code...

所以现在我将讨论一些重要的事情,那些从未在java中处理图像的人(比如我自己)应该知道。

请记住,我在上面发布的ImageMake类中,有类似的代码:

img = ImageIO.read(ImageMake.class.getResource(path));

ImageMake.class部分引用了您的类在您正在使用的任何存储设备上的文件夹。

就我而言,ImageMake类位于以下目录中:C:\ Users \ Charlie \ Documents \ Overall

在同一个文件夹中,我创建了另一个名为&#34; res&#34;然后在那个名为&#34; textures&#34;然后添加一个名为&#34; smiley.png&#34;

的.png图像

当您传入字符串&#39;路径&#39;对于图像,它开始在您的班级所在的文件夹中搜索。在我的情况下,我必须传入&#34; /res/textures/smiley.png"确保您使用正斜杠&#34; /&#34;否则您可能会收到编译时错误&#39;非法转义符号,或某些运行时错误。

所以到达我的图像的整个代码外目录最终是这样的:C:\ Users \ Charlie \ Documents \ Overall \ res \ textures \ smiley.png

以下是主类的半成品代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.BorderFactory.*;
import javax.swing.JApplet;
import java.util.ArrayList;

public class Calculator{
    private static JFrame f;
    private Font font;
    private boolean x = false, y = false;
    private double num, num1, num2, num3, ans;
    private int c = 0;
    private String word = "", save = "", keep = "";
    private JTextField tf = new JTextField("0");
    private static JPanel p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14;
    //private static ImageMake img = new ImageMake("/res/textures/smiley.png");
    public Calculator(){
        f = new JFrame("Calculator");
        try{
            javax.swing.UIManager.setLookAndFeel(new
                com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
        }catch(Exception e){}
        ArrayList<String> titles = new ArrayList<String>();
        ArrayList<JButton> buttons = new ArrayList<JButton>();
        for(int i = 0; i < 10; i++){
            titles.add("" + i);
        }
        titles.add("C");
        titles.add(".");
        titles.add("/");
        titles.add("*");
        titles.add("+");
        titles.add("-");
        titles.add("<");
        titles.add("=");

        for(int i = 0; i < titles.size(); i++){
            buttons.add(new JButton(titles.get(i)));
            buttons.get(i).addKeyListener(kl);
            buttons.get(i).addActionListener(al);
            buttons.get(i).setFocusable(false);
            if(i > 11 && i < 16)
            buttons.get(i).setPreferredSize(new Dimension(40, 40));
        else if(i > 15)
            buttons.get(i).setPreferredSize(new Dimension(85, 40));
        else
            buttons.get(i).setPreferredSize(new Dimension(50, 40));
        }

        font = new Font(Font.MONOSPACED, Font.PLAIN, 24);
        tf.setPreferredSize(new Dimension(290, 60));
        tf.setEditable(false);
        tf.setHorizontalAlignment(JTextField.RIGHT);
        tf.setFont(font);

        TitledBorder t0, t1, t2, t3;
        t0 = BorderFactory.createTitledBorder(" INPUT ");
        t1 = BorderFactory.createTitledBorder(" OPERATIONS ");

        p0 = new JPanel();
        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        p4 = new JPanel();
        p5 = new JPanel();
        p6 = new JPanel();
        p7 = new JPanel();
        p8 = new JPanel();
        p9 = new JPanel();
        p10 = new JPanel();
        p11 = new JPanel();
        p12 = new JPanel();
        p13 = new JPanel();
        p14 = new JPanel();

        p0.add(tf);
        p14.add(p0);
        p1.add(buttons.get(1)); p1.add(buttons.get(2)); p1.add(buttons.get(3));
        p2.add(buttons.get(4)); p2.add(buttons.get(5)); p2.add(buttons.get(6));
        p3.add(buttons.get(7)); p3.add(buttons.get(8)); p3.add(buttons.get(9));
        p4.add(buttons.get(10)); p4.add(buttons.get(0)); p4.add(buttons.get(11));
        p5.add(p1); p5.add(p2); p5.add(p3); p5.add(p4);
        p5.setLayout(new BoxLayout(p5, BoxLayout.PAGE_AXIS));
        p5.setBorder(t0);
        p6.add(buttons.get(16));
        p7.add(buttons.get(12)); p7.add(buttons.get(13));
        p8.add(buttons.get(14)); p8.add(buttons.get(15));
        p9.add(buttons.get(17));
        p10.add(p6); p10.add(p7); p10.add(p8); p10.add(p9);
        p10.setLayout(new BoxLayout(p10, BoxLayout.PAGE_AXIS));
        p10.setBorder(t1);
        p11.add(p5); p11.add(p10);
        p12.add(p14); p12.add(p11);
        p12.setLayout(new BoxLayout(p12, BoxLayout.PAGE_AXIS));

        f.addKeyListener(kl);
        f.add(p12);
    }
    public static void main(){
        new Calculator();
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //f.setIconImage(img.img);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setFocusable(true);
        f.setVisible(true);
    }
    public void operationType(String operation){
        if(operation.equals("=")){
            num2 = num3;
            operation = keep;
        }
        switch(operation){
            case "/": num = (num1 / num2); word = "" + num; break;
            case "*": num = (num1 * num2); word = "" + num; break;
            case "+": num = (num1 + num2); word = "" + num; break;
            case "-": num = (num1 - num2); word = "" + num; break;
        }
        num1 = num;
    }
    KeyListener kl = new KeyAdapter(){
        public void keyPressed(KeyEvent e){
            int press = e.getKeyCode();
            if(!word.equals("") && !word.equals("/") && !word.equals("*") && !word.equals("+") && !word.equals("-") && !word.equals(".")) ans = Double.parseDouble(word);
            if((word.equals("0") && press != KeyEvent.VK_ENTER && press != KeyEvent.VK_EQUALS) || 
                word.equals("/") ||
                word.equals("*") ||
                word.equals("+") ||
                word.equals("-") || x){
                word = "";
                x = false;
            }
            if(e.getKeyChar() == '+'){
                num1 = Double.parseDouble(word); word = save = keep = "+";
            }
            switch(press){
                case KeyEvent.VK_1: word += "1"; break;
                case KeyEvent.VK_2: word += "2"; break;
                case KeyEvent.VK_3: word += "3"; break;
                case KeyEvent.VK_4: word += "4"; break;
                case KeyEvent.VK_5: word += "5"; break;
                case KeyEvent.VK_6: word += "6"; break;
                case KeyEvent.VK_7: word += "7"; break;
                case KeyEvent.VK_8: word += "8"; break;
                case KeyEvent.VK_9: word += "9"; break;
                case KeyEvent.VK_0: word += "0"; break;
                case KeyEvent.VK_PERIOD: word += "."; break;
                case KeyEvent.VK_SLASH: num1 = ans; word = save = keep = "/"; break;
                case KeyEvent.VK_X: num1 = ans; word = save = keep = "*"; break;
                case KeyEvent.VK_MINUS: num1 = ans; word = save = keep = "-"; break;
                case KeyEvent.VK_ENTER:
                if(save.equals("=")){
                    num2 = ans; x = true; operationType(save);}
                else{
                    num2 = ans; num3 = num2; save = "="; x = true; operationType(save);} break;
                case KeyEvent.VK_BACK_SPACE:
                if(word.length() > 1)
                    word = word.substring(0, word.length() - 1);
                else if(word.length() == 1 || word.length() == 0)
                    word = "0"; break;
                case KeyEvent.VK_ESCAPE: word = "0"; break;
                case KeyEvent.VK_CONTROL: word = "0";
            }
            tf.setText(word);
        }
    };
    ActionListener al = new ActionListener(){
        public void actionPerformed(ActionEvent e){
            String action = e.getActionCommand();
            if(!word.equals("") && !word.equals("/") && !word.equals("*") && !word.equals("+") && !word.equals("-") && !word.equals(".")) ans = Double.parseDouble(word);
            if((word.equals("0") && !action.equals("=")) ||
                word.equals("/") || 
                word.equals("*") || 
                word.equals("+") || 
                word.equals("-") || x){
                word = "" ;
                x = false;
            }
            switch(action){
                case "1": word += "1"; break;
                case "2": word += "2"; break;
                case "3": word += "3"; break;
                case "4": word += "4"; break;
                case "5": word += "5"; break;
                case "6": word += "6"; break;
                case "7": word += "7"; break;
                case "8": word += "8"; break;
                case "9": word += "9"; break;
                case "0": word += "0"; break;
                case ".": word += "."; break;
                case "/": num1 = ans; word = save = keep = "/"; break;
                case "*": num1 = ans; word = save = keep = "*"; break;
                case "+": num1 = ans; word = save = keep = "+"; break;
                case "-": num1 = ans; word = save = keep = "-"; break;
                case "=":
                if(save.equals("=")){
                    num2 = ans; x = true; operationType(save);}
                else{
                    num2 = ans; num3 = num2; save = "="; x = true; operationType(save);} break;
                case "<":
                if(word.length() > 1)
                    word = word.substring(0, word.length() - 1);
                else if(word.length() == 1 || word.length() == 0)
                    word = "0"; break;
                case "C": word = "0"; break;
            }
            tf.setText(word);
        }
    };
}

它仍然有一些需要修复的潜在错误。

1 个答案:

答案 0 :(得分:0)

试试这个:

public static ImageIcon createIcon(String spec) {
    URL url = ClassLoader.getSystemResource(spec);
    if (url != null) {
        return new ImageIcon(url); 
    }
    try {
        return new ImageIcon(new URL(spec));
    } catch (MalformedURLException ex) {
        return new ImageIcon(spec);
    }
}