图像不会显示但可点击

时间:2013-12-23 14:31:54

标签: java image swing paintcomponent

我尝试在包含背景的JDialog上绘制图像。我所做的是打电话给画这个图像的班级。这里,永远不会调用“paintComponent”:

// class Card
public Card(BufferedImage faceUp, int value) {

    this.faceUp = faceUp;
    this.hide = false;
    this.value = value;
    setOpaque(false);
    setLayout(new FlowLayout());

    this.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println(Card.this.getX());
            System.out.println("click");
        }

    });

    repaint();
}

@Override
public void paintComponent(Graphics g) {
     System.out.println("here");
    g.drawImage((this.hide) ? Cards.back : this.faceUp, Cards.CARD_WIDTH, Cards.CARD_HEIGHT, this);

}

我在我的主构造函数中调用它:

public Constructor() {
    initComponent();

    Card c1 = new Card(Cards.cardsContainer.get(1), 1%14); //Image, value

    jPanel1.add(c1);

    c1.setVisible(true);
    c1.setPreferredSize(new Dimension(200, 100));

    c1.revalidate();
    c1.repaint();
    repaint();
}

@Override
public void paint(Graphics g) {
    try {
        Graphics2D g2 = (Graphics2D) g;
        BufferedImage background_image;

        background_image = ImageIO.read(new File(this.background));
        Graphics2D big = background_image.createGraphics();
        Rectangle rectangle = new Rectangle(0, 0, 20, 20);
        g2.setPaint(new TexturePaint(background_image, rectangle));

        Rectangle rect = new Rectangle(0, 0, this.getWidth(), this.getHeight());
        g2.fill(rect);
    } catch (IOException ex) {
        Logger.getLogger(Bataille.class.getName()).log(Level.SEVERE, null, ex);
    }
}

知道为什么吗?

2 个答案:

答案 0 :(得分:0)

我怀疑您的卡片大小为0。你可以做的一件事是给它一个首选尺寸:

public Dimension getPreferredSize() {
  if (Cards.back != null) {
    return new Dimension(Cards.back.getWidth(), Cards.back.getHeight());
  } else {
    return super.getPreferredSize();
  } 
}

答案 1 :(得分:0)

哦,我的...... 显示了卡片,但borderLayout有一个保证金。所以我放大了面板,它出现了。