我想寫一個二十一點遊戲,我想有一個窗口,其中的表格圖像坐,並打/保持按鈕坐。然而,即使當我嘗試添加(@參數)擊中/停留按鈕對象到框架,按鈕顯示在單獨的窗口作爲表。如何讓我的JButton與我的圖像進入相同的窗口?
我的代碼:
import java.awt.*;
import javax.swing.*;
public class BlackjackTable extends JComponent{
private static final int WIDTH = 1200;
private static final int HEIGHT = 800;
private Rectangle table;
private JButton hitOrStay;
public BlackjackTable(){
table = new Rectangle(0,0,WIDTH,HEIGHT);
JFrame frame = new JFrame();
JLabel lab = new JLabel(new ImageIcon("blackjackTableCanvas.jpg"));
frame.setSize(1200,800);
lab.setSize(1200,800);
frame.add(lab);
hitOrStay = new HitOrStayButton();
frame.add(hitOrStay);
frame.setTitle("Test Canvas");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.draw(table);
}
public static void main(String[] args){
BlackjackTable b = new BlackjackTable();
}
}
我的命中或留按鈕:
public class HitOrStayButton extends JButton{
JButton stayButton = new JButton("STAY");
JButton hitButton = new JButton("HIT");
public HitOrStayButton(){
ActionListener pressChoice = new DecisionListener();
hitButton.addActionListener(pressChoice);
stayButton.addActionListener(pressChoice);
JPanel testPanel = new JPanel();
testPanel.add(hitButton);
testPanel.add(stayButton);
JFrame testFrame = new JFrame();
testFrame.add(testPanel);
testFrame.setSize(300, 150);
testFrame.setVisible(true);
}
class DecisionListener implements ActionListener{
public void actionPerformed(ActionEvent a){
if(a.getSource() == hitButton){
System.out.println("YOU CHOSE HIT!");
}
else if(a.getSource() == stayButton){
System.out.println("YOU CHOSE STAY!");
}
}
}
public static void main(String[] args){
HitOrStayButton h = new HitOrStayButton();
}
}
我怎麼能得到框架有在底部面板的按鈕,它的形象呢?
我沒有看到'HitOrStayButton'需要創建一個新窗口,甚至不知道我看到你需要從'JButton'進行擴展。 'BlackjackTable'不需要創建它自己的窗口,這些都是不必要的副作用。您應該創建一個窗口並將其他組件放置到 – MadProgrammer
上以一個基本教程開始:[add image](http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/LoadimagetoImageIconandaddittoPanel.htm)。成功時,在JFrame中添加另一個「JPanel」。將兩個按鈕添加到第二個'JPanel' – c0der
謝謝!但現在我只看到按鈕,但沒有看到框架。另外,如何保留我的面向對象的設計(如在按鈕中設置它自己是一個對象?我試圖保持它爲一個,但在這種情況下,它不會顯示出來。 – Derry