JFrame出现奇怪的显示问题

时间:2011-12-30 07:14:04

标签: java eclipse swing graphics paintcomponent

在下面的简单代码中,我只需创建一个框架,然后为其添加JPanelmenubar

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 中运行应用程序时,这就是我得到的 - enter image description here enter image description here

为什么双菜单栏?这非常烦人。在循环应用程序或弹出窗口时,重绘窗口很好(右侧图像)。

同样在我的 DrawPanel paintComponent我将背景设置为黑色,但没有效果?

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

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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);
        }
    });
}