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的人被激活,jpanel.remove(quit_2Button)
被調用。問題是,每當我嘗試這樣做,它給我的錯誤「面板無法解決」。我認爲這是發生的原因是因爲timer_run無法訪問JPanel框架,但通過各種試驗和錯誤還沒有能夠解決這個問題。有沒有人對我可以做些什麼讓timer_run看到JPanel框架有什麼看法?在此先感謝,並且請注意我是java noob,因此儘可能簡單地回答問題,如果可能的話?
順便說一句:你可能不應該延長JFrame的' '...... – Sinkingpoint
你會推薦我用什麼來代替? – quixotrykd
嘗試一個實例變量。 – Sinkingpoint