【发布时间】: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 添加多个图形,则只会显示其中一个。
【问题讨论】:
-
+1 表示几乎完整的MCVE
-
尝试在您的自定义类上使用 setPreferredSize() setMinimumSize() 和 setMaximumSize()。
-
@NESPowerGlove 见Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?(是的。)
-
那里的最佳答案是否建议根本不覆盖这些方法?