【发布时间】:2014-05-28 23:43:37
【问题描述】:
目前,我看到的只是一条从 JFrame 屏幕左上角延伸出来的细黑线。我假设它是我卡片的底部边缘,其余部分被挡住了
当我将卡片直接添加到 JFrame 时,我可以看到所有内容,所以我很困惑为什么当我将卡片添加到框架中的 JPanel 时我只能看到这条线(测量卡片的宽度)。
JFrame 代码:
public class WarFrame extends JFrame
{
public WarFrame()
{
setSize(600, 800);
setTitle("War");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
add(panel);
panel.add(new Card(Rank.ACE));
}
public static void main(String[] args)
{
WarFrame game = new WarFrame();
game.setVisible(true);
}
}
卡代码:
public class Card extends JComponent
{
private final Rank rank;
private boolean faceUp;
private int x;
private int y;
private final int width;
private final int height;
private final int arcWidth;
private final int arcHeight;
public Card(Rank r)
{
rank = r;
faceUp = false;
x = 0;
y = 0;
width = 75;
height = 100;
arcWidth = 10;
arcHeight = 10;
}
public Card(Rank r, int x, int y)
{
rank = r;
faceUp = false;
this.x = x;
this.y = y;
width = 75;
height = 100;
arcWidth = 10;
arcHeight = 10;
}
@Override
protected void paintComponent(Graphics g)
{
Graphics2D pen = (Graphics2D) g;
//this is the black boarder
pen.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
//white card body
pen.setColor(Color.WHITE);
pen.fillRoundRect(x + 5, y + 5, width - 10, height - 10, arcWidth, arcHeight);
if (faceUp)
{
//draw the card's symbol
pen.setFont(pen.getFont().deriveFont(50f));
pen.setColor(Color.RED);
if (rank == Rank.TEN)
{
//10 has 2 digits, so needs to be shifted a bit
pen.drawString(rank.getSymbol(), x + 5, y + 65);
}
else
{
pen.drawString(rank.getSymbol(), x + 20, y + 65);
}
}
else
{
//draw a blue rectangle as back of card pic
pen.setColor(Color.BLUE);
pen.fillRoundRect(x + 10, y + 10, width - 20, height - 20, arcWidth, arcHeight);
}
}
我还注意到将卡片直接添加到 JFrame 的一些有趣的事情。如果从 0, 0 开始绘制,整张卡片就会显示出来
frame.add(new Card(Rank.ACE, 0, 0));
但是如果我在 x > 0 的地方添加它,
frame.add(new Card(Rank.ACE, 2, 10));
然后卡片的右侧开始被切断。不知何故,当 y > 0 时,卡片会正确地绘制在屏幕的下部。
所以,任何建议为什么 A. 将卡片添加到面板只会使一小行可见并且 B. 直接加到框架上,为什么只有x > 0时卡才会被剪掉?
【问题讨论】:
标签: java swing jframe jpanel jcomponent