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 = null然后添加(custom2);但它没有显示出来 PS:忽略注册按钮
答案 0 :(得分:1)
您需要在按钮上添加一个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);
}
}
}
注意:代码是由我的头脑组成的,可能会有错误。此外,它只是一个片段,随时可以评论完整的代码