按下按钮时图像更改Java

时间:2013-06-10 23:55:52

标签: java image swing jbutton jlabel

好的,我希望在按下helpButton时更改背景图片。当鼠标悬停在鼠标监听器上时,我可以更改按钮图像。除了Action Listener之外,我做了同样的步骤,但没有成功。任何帮助都会很棒!

public class test extends JFrame{

    private JLabel label;
    private JButton button;

    private ImageIcon bgi;
    private JLabel bgl;

    public static Rectangle gameSquare;


    private JButton startButton;
    private JButton helpButton;
    private final Action action = new SwingAction();


    public static void main(String[] args) throws MalformedURLException, IOException {
        test gui = new test ();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
        gui.setSize(902, 305);
        gui.setVisible(true);
        gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
    }

    public test() throws MalformedURLException, IOException{

        bgi = new ImageIcon(getClass().getResource("tu.png"));
        getContentPane().setLayout(null);

        BufferedImage img = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/start_zpsf3781681.png"));
        //ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
        startButton = new JButton("");
        startButton.setIcon(new ImageIcon(img));
        startButton.setBounds(22, 186, 114, 50);


        getContentPane().add(startButton);

        BufferedImage img2 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/help_zpsc4fad867.png"));
        final JButton helpButton = new JButton("");
        helpButton.setIcon(new ImageIcon(img2));
        helpButton.setBounds(192, 186, 114, 50);

        getContentPane().add(helpButton);

        bgl = new JLabel (bgi);
        bgl.setBounds(0, 0, 886, 272);
        getContentPane().add(bgl);

        Events e = new Events();
        startButton.addActionListener(e);
        helpButton.addActionListener(e);
    }

    public class Events implements ActionListener {


        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == startButton) {
               label.setText("Searching");

               try {
                Unfollow();
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            }
            else if (e.getSource() == helpButton){
                System.out.println("gottem");
                bgi = new ImageIcon(getClass().getResource("tu2.png"));
            bgl = new JLabel (bgi);
            }
    }

    }

1 个答案:

答案 0 :(得分:4)

bgl = new JLabel (bgi);

在这里,您将创建一个新的JLabel,并将其放入bgl变量,但正在对其执行任何操作,并且不会对继续在GUI中显示的JLabel对象进行任何更改。这是一个常见的新手陷阱,认为通过更改变量的引用,您可以更改变量先前引用的原始对象的状态。这不是它的工作原理。换句话说,由bgl变量保存的原始JLabel仍然存在,并且仍然在GUI中显示其原始内容,尽管上面的代码。您应该做的是更改原始JLabel显示的图标,换句话说,更改当前JLabel对象的状态,而不是更改bgl变量保存的引用。即,

bgl.setIcon(bgi);

此外,您将希望摆脱任何和所有使用null布局和调用setBounds(...),因为这将导致难以维护和升级代码的错误。让布局管理人员在布局GUI方面做了很多工作。