按下按钮时更改图像 Java

3

好的,当点击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);
            }
    }

    }

你好像忽略了我昨天问题的回答——为什么呢?我们是志愿者,你的感谢通常是激励我们帮助你的动力。 - Hovercraft Full Of Eels
1个回答

4
bgl = new JLabel (bgi);

在此,您创建了一个新的JLabel,并将其放入bgl变量中,但没有对其进行任何更改,并且没有对继续显示在GUI中的JLabel对象进行更改。认为通过更改变量的引用即可更改先前变量所引用的原始对象的状态是新手常见的误区,但这并不是它的工作方式。换句话说,尽管上述代码,仍然存在被bgl变量持有的原始JLabel,并且仍在GUI中显示其原始内容。您应该做的是更改当前JLabel对象的图标或者换句话说,更改当前JLabel对象的状态,而不是更改bgl变量所持有的引用。即,
bgl.setIcon(bgi);

此外,您需要摆脱所有使用空布局和调用setBounds(...)的做法,因为这会导致代码难以维护和升级。让布局管理器负责GUI的布局。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接