简体   繁体   English

将绘画组件添加到JPanel

[英]Adding Paint Component To A JPanel

In my application (using java), a button is pushed and then a panel opens up with a graph on it. 在我的应用程序中(使用Java),按下一个按钮,然后打开一个面板,上面有一个图形。 To create the graph I am using graphics/paint. 要创建图形,我正在使用图形/绘画。 However, I am unable to get the graphics to show up. 但是,我无法显示图形。 For now, I am just trying to paint a circle (instead of the actual graph). 现在,我只是试图绘制一个圆圈(而不是实际的图形)。 It would be much appreciated if someone could explain what I am doing wrong. 如果有人可以解释我做错了,将不胜感激。

public class SeeProgressHandleClass extends JPanel{

  public SeeProgressHandleClass(JFrame window) {
    this.window = window;
  }

  public void mouseClicked(MouseEvent e) {
    panel = new JPanel();

    fillPanel();

    window.add(panel);      
    panel.setBackground(Color.white);       
    panel.setBounds(50, 40, 1100, 660);
  }

  public static void fillPanel() {
    Graph graph = new Graph();
    panel.add(graph);
 }
}

public class Graph extends JPanel{

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.setBackground(Color.white);
    g.setColor(Color.green);
    g.fillOval(50, 50, 50, 50);
  }

}
  • Graph should provide preferredSize hints, which will allow the layout manager to make better determinations about how the component should be displayed. Graph应提供preferredSize提示,这将使布局管理器可以更好地确定组件的显示方式。 Consider overriding getPreferredSize 考虑覆盖getPreferredSize
  • Don't call this.setBackground(Color.white); 不要调用this.setBackground(Color.white); inside paintComponent , each time you do this, it will trigger a potential repaint request, which will eventually consume all your CPU cycles. paintComponent内部,每次执行此操作时,都会触发潜在的重新绘制请求,最终将消耗所有CPU周期。 Set this in the constructor 在构造函数中设置
  • You're adding Graph into JPanel and then adding this to the screen ... not sure why, but it's making it more confusing 您正在将Graph添加到JPanel ,然后将其添加到屏幕中……不知道为什么,但这会使它更加混乱
  • After window.add(panel); window.add(panel); , all window.revalidate() and window.repaint() to trigger a new layout and paint pass ,所有window.revalidate()window.repaint()触发新的布局和绘制过程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM