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/