我正在制作一个小卡片游戏而且我遇到了一些麻烦:当我尝试向我的JLayeredPane
添加动态组件时,它不会显示它们。
我有一个代表卡片的自定义组件,我希望以分层方式显示其中的2个。为此,我有以下课程:
public class PairView extends JPanel {
private JLayeredPane layeredPane;
private CardView attackCard;
private CardView defenceCard;
private static Point origin = new Point(0, 0);
private static int offset = 10;
public PairView() {
}
public PairView(Card attackCard) {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(120, 170));
this.defenceCard = null;
this.attackCard = new CardView(attackCard);
this.attackCard.setOpaque(true);
this.attackCard.setForeground(Color.black);
this.attackCard.setBorder(BorderFactory.createLineBorder(Color.black));
this.attackCard.setBounds(origin.x, origin.y, 100, 150);
layeredPane.add(this.attackCard, 0);
this.origin.x += offset;
this.origin.y += offset;
}
public void addDefenceCard(Card defenceCard) throws DurakException {
if (this.defenceCard == null) {
this.defenceCard = new CardView(defenceCard);
this.defenceCard.setOpaque(true);
this.defenceCard.setForeground(Color.black);
this.defenceCard.setBorder(BorderFactory.createLineBorder(Color.black));
this.defenceCard.setBounds(origin.x, origin.y, 100, 150);
layeredPane.add(this.defenceCard, 1);
} else {
throw new DurakException("A defence Card is already present");
}
}
我通过NetBeans中的拖放界面对此进行了测试,我遇到了以下问题:
CardView
组件并将它们添加到默认构造函数中的分层窗格时,父JFrame
显示它们就好了。 addDefenceCard
方法),则不会显示添加的组件。revalidate()
或repaint()
没有做任何事情。如何让组件显示?
答案 0 :(得分:1)
您的类扩展了JPanel,但您从不向面板添加任何组件,因此无需显示任何内容。
您需要将JLayeredPane添加到面板:
layeredPane = new JLayeredPane();
this.add( layeredPane );
我不知道您是否需要将布局设置为BoxLayout。面板的默认FlowLayout将遵循添加到其中的任何组件的preferredSize。
this.attackCard.setOpaque(true);
this.attackCard.setForeground(Color.black);
this.attackCard.setBorder(BorderFactory.createLineBorder(Color.black));
您可能需要考虑在CardView类的构造函数中设置这些属性。这样,默认属性就可以在一个地方设置,并且可以轻松更改。
您可能需要考虑使用Overlap Layout,而不是使用分层窗格。它旨在支持重叠组件的要求。