【问题标题】:Java adding Graphic to JPanel and then to JFrameJava将Graphic添加到JPanel,然后添加到JFrame
【发布时间】:2014-05-20 18:27:16
【问题描述】:

好的,所以我花了很多时间寻找我的问题的一些答案,但我运气不佳。我正在尝试将已绘制的图形添加到 JPanel,然后将 JPanel 添加到 JFrame。这是我的代码:

import java.awt.*;
import javax.swing.*;

public class Testing
{  
   public static void main(String[] args)
{  
  JFrame f = new JFrame("JFrame with a JPanel");
  f.setSize(500,500);
  JLabel l1 = new JLabel("Hello !");
  JPanel p1 = new JPanel();
  JPanel p2 = new JPanel();
  DrawBox dB = new DrawBox(400,200,20,20);

  p1.add(l1);
  p2.add(dB);
  f.add(p1,BorderLayout.PAGE_END);
  f.add(p2,BorderLayout.CENTER);    
  //f.add(dB);                      //Adding directly to the JFrame works fine
  f.setVisible(true);
  }
}

接下来是创建图形的类

public class DrawBox extends JPanel {

int xVal = 0;
int yVal = 0;
int width = 0;
int height = 0;

public DrawBox(int x, int y, int w, int h) {
    xVal = x;
    yVal = y;
    width = w;
    height = h;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(xVal, yVal, width, height);
}

}

如果我将 DrawBox 直接添加到 JFrame 中,它似乎工作正常。但是,如果我尝试直接向 JFrame 添加多个图形,则只会显示其中一个。

【问题讨论】:

标签: java swing jframe jpanel


【解决方案1】:

来自您的评论

//f.add(dB); //Adding directly to the JFrame works fine

它之所以有效,是因为框架的 BorderLayout 不尊重首选尺寸。它将拉伸绘图面板以适应。

另一方面,当您在另一个面板中添加包装绘图面板时,包装面板具有默认的 FlowLayout,确实 尊重首选尺寸。如果您没有通过覆盖getPreferredSize() 明确设置它,您的绘图面板的首选大小为 0x0@

@Override
public Dimension getPreferredSize() {
    return new Dimension( ... , ... );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多