這是我的黑傑克程序,它仍然是一個WIP,但程序將運行。問題是單擊JButton命中不會將.setText設置爲JLabel中存儲的新值。有人請幫忙!從JButton接收輸入的問題
import java.awt.Color;
import javax.swing.*;
import java.text.*;
import java.awt.Font.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class A3_Poltoranos_Max implements ActionListener{
int playerCard1 = (int)(Math.random() * 11) * 1 + 1;
int playerCard2 = (int)(Math.random() * 11) * 1 + 1;
int totalScore = playerCard1 + playerCard1;``
JPanel background;
JLabel total, totalTitle;
JButton hit, stand;
public JPanel createContentPane(){
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
JPanel background = new JPanel();
Color feltGreen = new Color(27, 154, 25);
background.setLayout(null);
background.setBackground(feltGreen);
background.setLocation(0, 0);
background.setSize(800,600);
totalGUI.add(background);
JLabel totalTitle = new JLabel("Your total:");
totalTitle.setLocation(150, 50);
totalTitle.setSize(100, 40);
totalTitle.setHorizontalAlignment(0);
background.add(totalTitle);
JLabel total = new JLabel(""+totalScore);
total.setLocation(150, 200);
total.setSize(100, 40);
total.setHorizontalAlignment(0);
background.add(total);
JButton hit = new JButton("Hit!");
hit.setLocation(50, 450);
hit.setSize(100, 30);
hit.addActionListener(this);
background.add(hit);
JButton stand = new JButton("Stand!");
stand.setLocation(250, 450);
stand.setSize(100, 30);
stand.addActionListener(this);
background.add(stand);
totalGUI.setOpaque(true);
return totalGUI;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == hit)
{
playerCard2 = (int)(Math.random() * 11) * 1 + 1;
totalScore = totalScore + playerCard2;
total.setText(""+totalScore);
}
else if(e.getSource() == stand)
{
total.setText(""+totalScore);
}
}
private static void createWindow() {
JFrame frame = new JFrame("Black Jack V 0.1");
A3_Poltoranos_Max demo = new A3_Poltoranos_Max();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createWindow();
}
});
}
}
我非常愛你 – user3285292
Thx,但接受答案就夠了;) –
是的,我剛剛意識到你可以做到這一點 – user3285292