2

在下面的简单代码中,我只是创建了一个 Frame,并在其中添加了一个JPaneland 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中,我将背景设置为黑色,但没有效果?

以上两个问题的原因是什么?请帮忙!

4

2 回答 2

5

您正在调用 Container.paintComponents() 方法。一定是super.paintComponent(g)

@Override
public void paintComponent(Graphics g) 
{
    super.paintComponent(g); //super.paintComponents(g);
    setBackground(Color.BLACK);
    g.setColor(Color.RED);
    g.drawLine(100, 50, 150, 100);
}
于 2011-12-30T08:12:43.573 回答
3

javadoc提到

  • isOpaque 必须为真
  • 根据 L&F,此属性可能会被忽略
  • JComponent 的子类必须覆盖paintComponent 才能遵守此属性。

将 setBackground 放入构造函数中,并添加这两行代码paintComponent(在绘制红线之前)使面板变黑。

g.setColor(getBackground());
g.fillRect(getX(), getY(), getWidth(), getHeight());

另请注意,应始终在 EDT 中创建和修改 Swing 组件。你的主要方法应该是这样的:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            MainFrame appFrame = new MainFrame();
            appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            appFrame.setSize(300, 275);
            appFrame.setVisible(true);
        }
    });
}
于 2011-12-30T08:00:48.417 回答