[英]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.