在下面的简单代码中,我只需创建一个框架,然后在其中添加一个JPanel
和menubar
即可。JFrame的奇怪显示问题
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);
}
}
应用程序在运行中日食的应用程序,这是我所得到的 -
为什么双菜单栏和线?这非常烦人。在循环应用程序或弹出窗口时,重绘的窗口很好(右侧图像)。
也在我的DrawPanelpaintComponent
我将背景设置为黑色,但没有效果?
上述两个问题的原因是什么?请帮忙!
您通常在初始化组件时设置背景色,而不是在绘制方法中。尝试将该行移至构造函数。 - 对于加倍问题:这只是一个猜测,但尝试添加此行之前打开框架:'System.setProperty(“sun.java2d.noddraw”,“true”);' – Thomas 2011-12-30 07:26:57
嘿谢谢,移动(或评论)这行'setBackground(Color.BLACK);'从paint到构造函数解决了双线和菜单的问题。但面板仍然不是黑色。也许你应该添加你的评论作为答案。顺便说一句'setProperty'没有帮助。 – 2011-12-30 07:39:57