简体   繁体   English

单击按钮更改图标。 爪哇

[英]Change icon with click on button. Java

I use Netbeans to make a Java application. 我使用Netbeans制作Java应用程序。 I am still a beginner. 我还是一个初学者。 I have 4 buttons and I want to change an icon, when a user click one of them. 我有4个按钮,当用户单击其中一个按钮时,我想更改一个图标。 I have already put buttons and one icon but I have no idea on how to continue. 我已经放了按钮和一个图标,但是我不知道如何继续。

You will need an ActionListener that changes the icon (use an ImageIcon for this). 您将需要一个ActionListener来更改图标(为此使用ImageIcon)。 Add that ActionListener to the Button which should be responding to a click, with that action. 将该ActionListener添加到应该对此操作做出响应的Button中。

button.addActionListener(/*here your listener*/);

Are you using the windowbuilder of netbeans? 您是否正在使用netbeans的windowbuilder? If yes, check the generated code for your specified button and see how they did it :) 如果是,请检查为您指定的按钮生成的代码,并查看它们是如何完成的:)

Ok, i created a new JFrame Form to my package called TestFrame. 好的,我为我的程序包创建了一个新的JFrame表单,称为TestFrame。

public class TestFrame extends javax.swing.JFrame {

        static public ImageIcon imageCross; 
        static public ImageIcon imageCircle;


        URL cross = TestFrame.class.getResource("cross.jpg");
        URL circle = TestFrame.class.getResource("circle.jpg");

        boolean clicked = true;
    /**
     * Creates new form TestFrame
     */
    public TestFrame() {
        imageCross = new javax.swing.ImageIcon(cross);
        imageCircle = new javax.swing.ImageIcon(circle);
        initComponents();
    }
    ...

This is just how i declare my images. 这就是我声明图像的方式。

Now i need to change them when i click on a button. 现在,我需要在单击按钮时进行更改。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if(clicked) {
        jButton1.setIcon(imageCircle);
        clicked = false;
    } else {
        jButton1.setIcon(imageCross);
        clicked = true;
    }

} 

Just add all your images you need. 只需添加您需要的所有图像即可。 Add for every single JButton a actionPerformed() and switch your icons with a if-condition or maybe switch/case ( if you have more). 为每个JButton添加一个actionPerformed()并使用if条件或(如果有更多的话)switch / case来切换图标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM