我正在创建一个二十一点游戏,并且我试图在按下点击按钮时让牌显示在桌面图像的顶部。然而,它们一直显示在 table 图像的一侧,并且只有其中一个显示。当我在 ActionListener 中使用 pack() 方法时,或者如果我不使用 pack() 时,当我调整窗口大小时。
我的代码:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
public class BlackjackTable3 extends JFrame {
JButton stayButton = new JButton("STAY");
JButton hitButton = new JButton("HIT");
JPanel mainPanel = new JPanel();
public BlackjackTable3() {
this.setTitle("Blackjack Test Table");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel tablePanel = new JPanel();
ImageIcon pic = new ImageIcon("blackjackTableCanvas.jpg");
mainPanel.add(new JLabel(pic), BorderLayout.NORTH);
this.add(mainPanel);
this.setSize(1600,1600);
this.setVisible(true);
JPanel buttonPanel = new JPanel();
ActionListener pressChoice = new DecisionListener();
hitButton.addActionListener(pressChoice);
stayButton.addActionListener(pressChoice);
buttonPanel.setSize(300,150);
buttonPanel.add(hitButton,BorderLayout.WEST);
buttonPanel.add(stayButton,BorderLayout.EAST);
buttonPanel.setVisible(true);
this.add(buttonPanel, BorderLayout.SOUTH);
}
class DecisionListener implements ActionListener{
public void actionPerformed(ActionEvent a){
//code for hit/stay to go here
if(a.getSource() == hitButton){
System.out.println("YOU CHOSE HIT!");
CardRender2 c = new CardRender2(new Card());
mainPanel.add(c, BorderLayout.CENTER);
pack();
}
else if(a.getSource() == stayButton){
System.out.println("YOU CHOSE STAY!");
}
}
}
public static void main(String[] args){
BlackjackTable3 b = new BlackjackTable3();
}
}
我的 CardRender2 代码:
public class CardRender2 extends JComponent{
public CardRender2(Card card) {
this.val = card.value.face;
this.suit = card.suit.toString();
String filename = this.fetchCardFileLabel();
try {
image = ImageIO.read(new File("card deck\\" + filename + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
JLabel j = new JLabel();
j.add(this);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(image, 0, 0, null);
}
...}
我尝试使用 repaint(),但无法使用 Paint bc 我收到编译器错误。我该如何解决这个问题?
最佳答案
how can I place these cards OVER, ON TOP OF, the table image?
您需要一个组件层次结构,例如:
- JFrame
- 带有图像的背景组件
- 带有图像的卡片组件
- 带有图像的背景组件
一种方法是使用标签来包含图像:
JLabel card = new JLabel(...);
JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );
background.add( card );
frame.add(background, BorderLayout.CENTER);
这仅在背景图像大于卡片组件时才有效。
关于java - 当我在 JFrame 中使用 PaintComponent 时,我必须调整窗口大小才能显示它,除非我使用 pack。我该如何补救?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44894905/