最近我一直在experementing Java和搖擺,我遇到一個問題的Java的JMenuBar重繪背景
我有一個「歡迎屏幕」用一些隨機產生的背景。
我重寫了paintComponent,並根據當前JPanel的分辨率繪製背景。不是花哨只是橢圓
但是,當我使用的菜單,菜單的背景被粉刷一新。
大小和橢圓的potision基於屏幕分辨率。 有什麼辦法可以解決?
注:歡迎面板的JPanel
最近我一直在experementing Java和搖擺,我遇到一個問題的Java的JMenuBar重繪背景
我有一個「歡迎屏幕」用一些隨機產生的背景。
我重寫了paintComponent,並根據當前JPanel的分辨率繪製背景。不是花哨只是橢圓
但是,當我使用的菜單,菜單的背景被粉刷一新。
大小和橢圓的potision基於屏幕分辨率。 有什麼辦法可以解決?
注:歡迎面板的JPanel
發生這種情況是因爲PopUpMenu下的區域在關閉popUp後重繪,但其他區域沒有。
您可以關閉彈出像旁邊後重繪您的面板:
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class TestFrame extends JFrame {
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DrawPanel p = new DrawPanel();
add(p);
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("menu");
JPopupMenu popupMenu = menu.getPopupMenu();
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
repaint();
}
@Override
public void popupMenuCanceled(PopupMenuEvent arg0) {
}
});
bar.add(menu);
menu.add(new JMenuItem("item"));
setJMenuBar(bar);
}
public static void main(String args[]) {
new TestFrame();
}
private class DrawPanel extends JPanel{
@Override
public Dimension getPreferredSize() {
return new Dimension(100,100);
}
@Override
protected void paintComponent(Graphics arg0) {
super.paintComponent(arg0);
Random r = new Random();
int nextInt = r.nextInt(20);
arg0.drawOval(nextInt, nextInt, 20, 20);
}
}
}
謝謝你的工作。但它重新繪製整個窗口,但我想沒有其他的方式 – 2014-09-03 15:08:00
您可以使用省略號重繪目標'JPanel'。 – alex2410 2014-09-03 15:45:37
這不是一個正確的解決方案。請看我的擴展答案! – 2014-09-04 17:59:47
畫出你的上一個位圖的背景,以及它在paintComponent()
方法複製。繪畫事件可以隨時發生,在這種情況下,您的隨機源生成新的值。
另一種解決方法:製作一個方法getRandom()
,它創建一個具有相同種子的Random
對象,並使用它。例如:
protected long seed = 0L;
protected void initRandom() { // call this in constructing time
seed = Calendar.getInstance().getTimeInMillis();
}
protected Random getRandom() { // call this at the start of the painting method
return new Random(seed);
}
這會爲所有窗口實例創建新的種子,並一致地使用它。任何重漆都不會產生不良影響。
任何評論由downvoter? – 2014-09-03 14:58:11
哪裏是你的代碼?在問題中發佈代碼,請參閱[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – DavidPostill 2014-09-03 14:27:08
你真的需要哪部分代碼?只是一個與randoms() – 2014-09-03 14:28:43
一個paintComponent方法一個最小,完整和可驗證的例子,所以我們可以編譯和運行它... – DavidPostill 2014-09-03 14:30:22