2016-02-05 135 views
0

我有一个我正在做的卡片项目,它使用GUI。我有一个JFrame将图像添加到Java中的GUI的最佳方法?

JFrame frame = new JFrame("Card Game"); 
//Splits the Jframe into two sections where the cards will be placed  
//according to what user draws them 
frame.setLayout(new GridLayout(1,2)); 
//The users, with different hands of cards 
JPanel user1 = new JPanel(); 
JPanel user2 = new JPanel(); 
frame.add(user1); 
frame.add(user2); 

我希望能够为每个用户的手有效地添加/删除卡。用户可以绘制的最大数量的卡片是9张。最初用户将开始使用两张卡片,并且我想使它能够整齐地添加另一张卡片。如果面板中的空间用完了,则应该开始在下面形成一排。

我该如何做到这一点?我想用JLabels以某种方式,但不知道这是否是一种正确的方法。此外,我不知道我应该使用什么布局,所以任何帮助/提示将不胜感激。谢谢。

编辑

谢谢你的帮助,但我仍然有一个问题。我使用“Lourenco”发布的代码作为我的面板添加卡片。我没有改变它。 在我的GUI类,我添加

MyPanel myPanel = new MyPanel(); 
public void addPlayerCard(Card c){ 
myPanel.addCard(c.getImageIcon());//should draw the card into the panel 
} 

这是我的我的ImageIcon添加到卡

java.net.URL imgURL = Card.class.getResource(imgFileName); 
    if (imgURL != null) { 
     image = new ImageIcon(imgFileName, ""); 
    } else { 
     System.err.println("Couldn't find file: " + imgFileName); 
     image = new ImageIcon(); 
    } 

我在做什么错?

+0

刊登[MCVE](http://stackoverflow.com/help/mcve)。一定要将你的代码复制粘贴到一个*新的项目中*,并确保它在发布之前编译并运行。 – user1803551

+0

它运行并编译正常,但没有绘制图像 –

+0

请再次阅读链接。发布*在这里,为我们*一个MCVE。 *我们*需要能够运行代码并查看问题。 – user1803551

回答

0

尝试使用这个类。它是一个JPanel,所以你可以创建一个MyPanel的实例并添加到你的JFrame中。

要添加一张卡,您必须创建一个ImageIcon对象[例如:ImageIcon card = new ImageIcon(“c:\ users \ desktop \ aceOfSpades.png”)]。

创建ImageIcon对象后,您必须调用addCard函数并将该卡作为参数传递。该卡将被添加到卡片的ArrayList,并且painel将被重新粉刷。您可以在rapaintComponent方法中操作2个常量CARD_WIDTH和CARD_HEIGHT以及变量x,y和widthToNextCard。

这种方式会给你更多的自由来刷你想要的方式,而不是使用不同的JLabel布局。

好运;)

import java.awt.Graphics; 
import java.awt.Image; 
import java.util.ArrayList; 

import javax.swing.ImageIcon; 
import javax.swing.JPanel; 


public class MyPanel extends JPanel { 

    private static final long serialVersionUID = 1L; 

    public final static int CARD_WIDTH = 50; 
    public final static int CARD_HEIGHT = 100; 

    private ArrayList<ImageIcon> cardsList; 

    public MyPanel() { 
     cardsList = new ArrayList<ImageIcon>(); 
    } 

    public void addCard(ImageIcon newCard) { 
     cardsList.add(newCard); 
     repaint(); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     int widthToDrawNextCard = 75; 
     int x = 50; 
     int y = 100; 
     for (int i = 0; i < cardsList.size(); i++) { 
      ImageIcon card = cardsList.get(i); 
      Image image = card.getImage(); 
      g.drawImage(image, x, y, CARD_WIDTH, CARD_HEIGHT, null); 
      x = x + widthToDrawNextCard; 
     } 
    } 
}