绘JPanel背景 [英] Paint background of JPanel

查看:144
本文介绍了绘JPanel背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何告诉paint方法仅在JPanel上绘制背景而不是在整个JFrame上绘制背景。
我的JFrame大小比JPanel大。当我尝试为JPanel绘制网格背景时,网格似乎遍布JFrame而不仅仅是JPanel。

How can I tell the paint method to draw background on JPanel only and not on the entire JFrame. My JFrame size is bigger than the JPanel. When I try to paint a grid background for the JPanel, the grid seems to be painted all over the JFrame instead of just the JPanel.

这里有部分代码:

public class Drawing extends JFrame {
  JPanel drawingPanel;
  ...........
  public Drawing (){
    drawingPanel = new JPanel();
    drawingPanel.setPreferredSize(new Dimension(600,600));
  }


public void paint(Graphics g) 
{
  super.paintComponents(g);
  Graphics2D g2 = (Graphics2D) g;
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

  paintBackground(g2); //call a METHOD to paint the for JPANEL
}


private void paintBackground(Graphics2D g2)
{
  g2.setPaint(Color.GRAY);
  for (int i = 0; i < drawingPanel.getSize().width; i += 300) 
  {
     Shape line = new Line2D.Float(i, 0, i, drawingPanel.getSize().height);
     g2.draw(line);
  }

  for (int i = 0; i < drawingPanel.getSize().height; i += 300) 
  {
    Shape line = new Line2D.Float(0, i, drawingPanel.getSize().width, i);
    g2.draw(line);
  }      
} //END private void paintBackground(Graphics2D g2)

}


推荐答案

camickr是正确的。所以:

camickr is correct. So:

public class Drawing extends JFrame {
  JPanel drawingPanel;
  ...........
  public Drawing (){
    drawingPanel = new MyPanel();
    drawingPanel.setPreferredSize(new Dimension(600,600));
    add(drawingPanel);
  }
}

public class MyPanel extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    myBackgroundRoutine(g2);
  }
}

您需要严格区分不同组件的图纸。 Swing已经是
管理子组件,因此绝对不需要在Frame中的
面板中实现绘图(调用paintComponents()是一个严重的错误)。
你永远不应该覆盖paint(),因为在Swing中只使用了paintComponent()
。在你完全知道自己在做什么之前,不要混两用。

You need to strictly separate your drawing from different components. Swing is already managing subcomponents, so there is absolutely no need to implement drawings in your Panel in the Frame (calling paintComponents() is a severe error). And you should never override paint(), because only paintComponent() is used in Swing. Don't mix both until you absolutely know what you are doing.

这篇关于绘JPanel背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆