【发布时间】:2012-01-30 10:01:55
【问题描述】:
在下面的简单代码中,我只是创建了一个 Frame,并在其中添加了 JPanel 和 menubar。
public class MainFrame extends JFrame {
private DrawPanel drawPanel;
public MainFrame()
{
super("Coordinate Geometry Visualiser");
drawPanel = new DrawPanel();
add(drawPanel);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
fileMenu.add(newItem);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic('E');
menuBar.add(editMenu);
}
}
绘制面板代码-
public class DrawPanel extends JPanel {
public DrawPanel()
{
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
setBackground(Color.BLACK);
g.setColor(Color.RED);
g.drawLine(100, 50, 150, 100);
}
}
最后是main()的应用程序
public class CGVApplication {
public static void main(String[] args) {
MainFrame appFrame = new MainFrame();
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
appFrame.setSize(300, 275);
appFrame.setVisible(true);
}
}
在 eclipse 中运行应用程序时,这就是我得到的 -
为什么是双 menubar 和 line?这很烦人。在循环浏览应用程序时或出现弹出窗口时,重新绘制的窗口很好(右侧图像)。
在我的 DrawPanel paintComponent 我也将背景设置为黑色,但没有效果?
以上两个问题的原因是什么?请帮忙!
【问题讨论】:
-
您通常在初始化组件时设置背景颜色,而不是在绘制方法中。尝试将该行移至构造函数。 - 至于倍增问题:这只是一个猜测,但请尝试在打开框架之前添加此行:
System.setProperty("sun.java2d.noddraw", "true"); -
嘿,谢谢,将这一行
setBackground(Color.BLACK);从绘图移动(或评论)到构造函数解决了双行和菜单的问题。但是面板仍然不是黑色的。也许您应该添加您的评论作为答案。顺便说一句setProperty没有帮助。
标签: java eclipse swing graphics paintcomponent