自定义JComponent上的图像不可见?

时间:2012-03-06 16:48:07

标签: java swing user-interface jcomponent

当我运行我的代码时,它不显示。 基本上我有一个自定义的Jcomponent,我添加到我的JFrame或View,然后创建一个View,使我的main方法框架。 我已经在JFrame中添加了我的JComponent代码:

public class CardDisplay extends JComponent {
private Card card;
private Image cardImage;

public CardDisplay()
{
    cardImage = Toolkit.getDefaultToolkit().createImage(("Phase10//res//Blue2.png"));
}

@Override
public void paint(Graphics g)
{
    g.drawImage(cardImage, 125 ,200, this);
}
public class View {
public View(){

}

public void makeFrame()
{
   JFrame frame = new JFrame("Phase 10");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setLayout(new BorderLayout());
   JPanel handPanel = new JPanel();
   CardDisplay cd = new CardDisplay();
   handPanel.setLayout(new FlowLayout());
   frame.add(handPanel, BorderLayout.SOUTH);
   handPanel.add(cd);
   frame.pack();
   frame.setSize(600,500);
   frame.setResizable(false);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
}

public static void main(String[] args){
    View view = new View();
    Game game = new Game();
    view.makeFrame();
    //game.run();

}

2 个答案:

答案 0 :(得分:3)

这是工作版本。问题主要与组件的首选大小有关。请注意方法getPreferredSize()的实施。

如果您想查看组件边界是什么,我建议在调试模式下使用MigLayout布局管理器(该站点包含所有必要的文档)。

public class CardDisplay extends JComponent {
    private BufferedImage cardImage;

    public CardDisplay() {
        try {
            cardImage = ImageIO.read(new File("Phase10//res//Blue2.png"));
        } catch (final IOException e) {
            e.printStackTrace();
        }    
    }

    @Override
    public void paintComponent(final Graphics g) {
        super.paintComponent(g);
        g.drawImage(cardImage, 0, 0, null);
    }

    @Override
    public Dimension getPreferredSize() {
        if (cardImage == null) {
            return new Dimension(100, 100);
        } else {
            return new Dimension(cardImage.getWidth(null), cardImage.getHeight(null));
        }
    }

    public static class View {
        public View() {}

        public void makeFrame() {
            final JFrame frame = new JFrame("Phase 10");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            final JPanel handPanel = new JPanel();
            final CardDisplay cd = new CardDisplay();
            handPanel.setLayout(new FlowLayout());
            frame.add(handPanel, BorderLayout.SOUTH);
            handPanel.add(cd);
            frame.pack();
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }

    public static void main(final String[] args) {
        final View view = new View();
        view.makeFrame();
    }
}

答案 1 :(得分:2)

对于JComponents,您使用paintComponent而不是paint。 Paint实际上用于绘制组件,而paintComponent用于绘制图像。