此刻,我看到的只是一条从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> 1时卡才被切断。 0?
答案 0 :(得分:1)
默认情况下,JPanel
使用FlowLayout
,该getPreferredSize()
会考虑添加到其中的任何组件的首选大小。自定义绘制时,JComponent的默认首选大小为(0,0)。
您需要覆盖Card类的Dimension
,以便为Card
返回正确的{{1}}。