[問題] 當JMenuBar遇上awt
我弄了一個JFrame物件,並開了一個Thread來畫畫面
然後弄了JMenuBar來當作選單
不過更新畫面的同時,選單也會跟著被洗掉(爬文應該是Swing被awt蓋掉)
我想請問有沒有什麼辦法可以偵測 Menu 有沒有被按下去
如果被按下去就停止更新畫面
或者有沒有更好的方法可以達成?
謝謝。
以下是程式碼:
[Main.java]
package MyPackage
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Main {
private static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenuItem menuFileExit = new JMenuItem("Exit");
menuBar.add(menuFile);
menuFile.add(menuFileExit);
menuFile.setMnemonic('F');
menuFileExit.setMnemonic('X');
menuFileExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
return menuBar;
}
public static void main(String[] args) {
MyWindow myWindow = new MyWindow("MyWindowTitle", createMenuBar());
}
}
[MyWindow.java]
package MyPackage
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class MyWindow extends JFrame {
private long timeLastDraw = -1; // 上次畫圖時間
private long timeDrawInterval = (long) Math.ceil(Math.pow(10, 9) / 60);
// 畫圖間隔(FPS=60)
public MyWindow(String windowTitle, JMenuBar menuBar) {
super(windowTitle);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(640, 480);
setBackground(Color.white);
setJMenuBar(menuBar);
setVisible(true);
DrawThread drawThread = new DrawThread();
drawThread.start();
}
protected class DrawThread extends Thread {
private boolean flagRun = false;
public void stopRun() {
flagRun = false;
}
public boolean isRunning() {
return flagRun;
}
public void run() {
flagRun = true;
while (flagRun) {
if (timeLastDraw < 0 ||
System.nanoTime() - timeLastDraw >= timeDrawInterval) {
repaint();
timeLastDraw = System.nanoTime();
}
}
}
}
public void paint(Graphics g) {
BufferedImage buffedCanvas = new BufferedImage(
640, 480, BufferedImage.TYPE_INT_ARGB
);
Graphics c = bufferedCanvas.getGraphics();
c.setColor(Color.blue);
c.fillRect(0, 0, 640, 480);
c.setColor(Color.red);
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
c.drawString(String.format("%1d x %1d = %2d"), i * 16, j * 60);
}
}
g.drawImage(bufferedCanvas, 0, 0, null);
g.finalize();
}
}
--
★∥ ○ ◢ 〞` ◣ ◥◣◢◣◢◣ ◢▏。 ○ ο ∣★
★| ° ◢ ╮ ██◤ █◤◥◤█ ∥ o ° ∥★
★∥ 。 ● ● ◤ ◥ █ █ ∥ ◢╱﹋◣ 。 ∣★
★∣ ◥ˍ ◤◤ ◢◤ ◢◢◤██◤ ◣ ◢╱ ● ︶ ( ∥★
★∥ ( ◢◤ ◤ing ∥say ◢███ ╰ ◤ ζ ) ∣★
★│ ) mt.rmstudio.tw ︾ mt@moztw.org ◤ ◥◢ ◤◤ wnqui ∥★
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.42.69.66
※ 編輯: a60301 來自: 114.42.69.66 (07/21 05:54)
※ 編輯: a60301 來自: 114.42.69.66 (07/23 03:17)
討論串 (同標題文章)
完整討論串 (本文為第 1 之 3 篇):