java - 用另一个按钮替换一个按钮

标签 java windows swing jbutton

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class GUI extends JFrame {

private JButton reg;
private JButton custom;
 private JButton custom2;
public GUI(){
    super("Heartstone Arena Alpha 0.01");
    setLayout(new FlowLayout());

    reg = new JButton("Click Me");
    add(reg);

    Icon ACn = new ImageIcon(getClass().getResource("463.png"));
    Icon ACg = new ImageIcon(getClass().getResource("463 (1).png"));
    custom = new JButton("Custom", ACn);
    custom.setRolloverIcon(ACg);
    add(custom);

    HandlerClass handler = new HandlerClass();
    reg.addActionListener(handler);
    custom.addActionListener(handler);


}

private class HandlerClass implements ActionListener {
    public void actionPerformed(ActionEvent event) {




        Icon An = new ImageIcon(getClass().getResource("Alexstrasza(303).png"));
        custom2 = new JButton(" ", An);
        custom2.setIcon(An);
        custom2.setRolloverIcon(An);





    }
}

这是代码,我想要做的是让custom2在单击时替换custom。 我该如何继续这件事呢? 我尝试使用 custom = null 然后添加(custom2);但它没有出现 PS:忽略注册按钮

最佳答案

您需要向按钮添加一个 ActionListener,这将使第一个按钮不可见,而第二个按钮可见。所以它并没有真正被破坏,你只是不显示它。
像这样:

public class YourClassName implements ActionListener {

  private JButton button1;
  private JButton button2;

  public YourClassName() {

    // Code Snippet ----------------

    button1 = new JButton("Click to replace");
    button1.addActionListener(this);
    // implement code for resizing and positioning here

    button2 = new JButton("I am new here");
    button2.setVisible(false);
    // implement code for resizing and positioning here

    // ...

  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if(e.getSource() == button1) {
      button1.setVisible(false);
      button2.setvisible(true);
    }
  }
}

注意:代码是我自己编出来的,可能有错误。另外,这只是一个片段,请随意评论完整代码

关于java - 用另一个按钮替换一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21254845/

相关文章:

java - 在 arquillian 中设置数据源

c++ - RegisterRawInputDevices() 正在生成 ERROR_FILE_NOT_FOUND

java - 不取决于文本长度的可滚动文本

Java 8 Streams减少删除重复项并保留最新条目

java - RxJava中 'Subscriber Thread'是什么意思

java - 将 jTextPane 样式保存到文档 (xml)

java - 在 JPanel 内的 JtextArea 上显示图像

c++ - 为什么写入此套接字会丢弃读取缓冲区(这是真的发生了什么)?

c++ - linux 到 windows C++ 字节数组

java - 在 Netbeans 中创建的 JList 不允许我添加元素