我有课程:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MyTimer extends JFrame {
static JButton quitButton;
static JButton quit_2Button;
public MyTimer() {
initUI();
}
public static void random(){
int x = (int)(Math.random() * 100 + 1);
int y = (int)(Math.random() * 150 + 1);
System.out.println(x);
System.out.println(y);
quitButton = new JButton("Press this to quit?");
quitButton.setBounds(x, y, 200, 20);
}
public void initUI() {
random();
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quit_2Button = new JButton("Or maybe press this to quit!");
quit_2Button.setBounds(50, 100, 200, 20);
quit_2Button.setRolloverEnabled(true);
quit_2Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
finder.main(null);
}
});
panel.add(quitButton);
panel.add(quit_2Button);
setTitle("Java");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
, 和
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class timer_run {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.remove(); //error here
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyTimer ex = new MyTimer();
ex.setVisible(true);
new timer_run();
}
});
}
public timer_run() {
Timer timer = new Timer(1000, al);
timer.start();
}
}
我正在努力做到这一点,以便在激活 actionlistener al 时jpanel.remove(quit_2Button)
调用它。问题是,每当我尝试这样做时,它都会给我一个错误“面板无法解决”。我认为发生这种情况的原因是因为 timer_run 无法访问 JPanel 框架,但通过各种试验和错误无法解决此问题。有人对我可以做些什么让 timer_run 看到 JPanel 框架有任何建议吗?提前谢谢,请注意我是一个java菜鸟,所以如果可能的话,让答案尽可能简单吗?