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