在下面的简单代码中,我只是创建了一个 Frame,并在其中添加了一个JPanel
and 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中运行应用程序时,这就是我得到的 -
为什么是双菜单栏和行?这很烦人。在应用程序循环或弹出窗口时重绘窗口很好(右侧图像)。
同样在我的DrawPanel paintComponent
中,我将背景设置为黑色,但没有效果?
以上两个问题的原因是什么?请帮忙!