![](/img/trans.png)
[英]I have to resize my JFrame for the contents to show up. How can i fix that?
[英]When I use an PaintComponent to my JFrame, I have to resize my window to get it to show up unless I use pack. How can I remedy this?
我正在创建一个二十一点游戏,并且我试图在单击“击中”按钮时使卡片显示在桌面图像的顶部。 但是,它们一直显示在表格图像的侧面,并且只显示一个。 当我在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,但出现编译器错误。 如何解决此问题?
如何将这些卡放在桌面图像上方?
您需要类似以下内容的组件层次结构:
一种方法是使用标签包含图像:
JLabel card = new JLabel(...);
JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );
background.add( card );
frame.add(background, BorderLayout.CENTER);
仅当背景图像大于卡组件时,此功能才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.