gpt4 book ai didi

java - JButton 无法删除

转载 作者:行者123 更新时间:2023-12-01 22:57:07 27 4
gpt4 key购买 nike

抱歉这个新问题,但我是 JStuff 的新手。我见过很多不同的方法来删除 JButton,但它们似乎都不起作用。谁能告诉我我在这里缺少什么吗?

当我按下按钮时,我的 actionPerformed 被调用,并且我的屏幕按照我想要的方式变化,但是 JButton exit 不会消失

JButton exit;

@Override
public void draw() {
exit = new JButton("Exit");
exit.setLayout(null);
exit.setBounds(new Rectangle(SCREEN.getWidth() / 2 + 50, SCREEN
.getHeight() - 50, SCREEN.getWidth() / 2 - 100, 50));
exit.setActionCommand("Exit");
exit.addActionListener(this);
frame.add(exit);
frame.repaint();
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Exit")) {
frame.remove(exit);
frame.validate();
frame.repaint();
eraseEverythingAndPutSomethingNewUp();
System.out.println("This is being called.");
}
}

最佳答案

在没有 runnable example that demonstrates your problem 的情况下,这个例子有效...

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class TestFrame {

public static void main(String[] args) {
new TestFrame();
}

public TestFrame() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}

final JButton btn = new JButton("Remove");

final JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.remove(btn);
((JComponent)frame.getContentPane()).revalidate();
((JComponent)frame.getContentPane()).repaint();
}
});

}
});
}

}

关于java - JButton 无法删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23879214/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com