因此,我有一個JPanel對象作爲JFrame的組件,並且我定期用Timer對象重新繪製JPanel的內容。除了在JFrame菜單頂部重繪JPanel時,一切都工作正常,因此導致菜單項無法讀取。有沒有辦法解決這個問題,而不必每次用戶訪問菜單時都暫停計時器?Janel內的JFrame在JFrame的菜單頂部繪製
控制框架類
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ControlFrame extends JFrame implements ActionListener{
/*======Public Constants======*/
public static int DEFAULT_HEIGHT = 400;
public static int DEFAULT_WIDTH = 400;
/*======Private Instance Variables======*/
private AnimationPanel animPane;
private JMenu menu;
private JMenuItem menuExit;
private JMenuBar menuBar;
/*======Constructors======*/
public ControlFrame(){
initialize();
}
/*======Public Instance Methods======*/
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("exit")){
System.exit(0);
}
}
/*======Private Instance Methods======*/
private void initialize(){
this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(0,2));
this.animPane = new AnimationPanel(this.getWidth(), this.getHeight());
this.add(animPane);
createCFMenu();
this.setVisible(true);
}
private void createCFMenu(){
this.menuBar = new JMenuBar();
this.menu = new JMenu("File");
this.menu.setMnemonic(KeyEvent.VK_F);
this.menuBar.add(this.menu);
this.menuExit = new JMenuItem("Exit", KeyEvent.VK_X);
this.menuExit.addActionListener(this);
this.menuExit.setActionCommand("exit");
this.menu.add(menuExit);
this.setJMenuBar(this.menuBar);
}
/*======Main Method======*/
public static void main(String[] args){
ControlFrame cf = new ControlFrame();
}
}
AnimationPanel類
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class AnimationPanel extends JPanel implements ActionListener{
/*======Private Instance Variables======*/
private int timeInterval;
private Timer animTimer;
/*======Constructor======*/
public AnimationPanel(int width, int height){
timeInterval = 50;
this.setSize(width, height);
this.animTimer = new Timer(timeInterval, this);
animTimer.start();
}
public void actionPerformed(ActionEvent arg0) {
paint();
}
/*======Private Instance Variables======*/
private void paint(){
BufferedImage bImage = new BufferedImage(this.getWidth(),
this.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics bg = bImage.getGraphics();
bg.setColor(Color.WHITE);
bg.fillRect(0, 0, bImage.getWidth(), bImage.getHeight());
this.getGraphics().drawImage(bImage, 0, 0, this);
}
}
問題是動畫面板是在ControlFrames菜單
解決方案是修復您的代碼中的錯誤。如果您需要我們的幫助,您需要顯示該代碼,或者其中的一部分。要發佈的最佳代碼是創建一個[SSCCE](http://sscce.org),它是一個最小的可編譯和可運行程序,可以顯示您的問題,並且沒有與手頭問題無關的代碼。我不太清楚你如何在沒有這些重要信息的情況下猜測錯誤,但也許是因爲你是新來的。順便提一下,歡迎使用stackoverflow。 – 2012-02-04 04:30:32
添加了代碼。 – pmurph 2012-02-04 04:53:06
發佈代碼的好處。 +1 – 2012-02-04 05:05:53