gpt4 book ai didi

java - 转换为 JApplet —— 我哪里出错了?

转载 作者:行者123 更新时间:2023-11-30 05:02:18 24 4
gpt4 key购买 nike

PokerFrame(从查看器类调用)工作得很好,但是一旦我尝试将其转换为小程序,它就无法加载。我没有得到任何运行时异常,只是一个空白的小程序空间。直到几个小时后我才能回复/选择答案,但我真的很感激任何人可能有的见解......

<HTML><head></head>
<body>
<applet code="PokerApplet.class" width="600" height="350"> </applet>
</body>
</HTML>

import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JFrame;

public class PokerApplet extends JApplet {
public void init() {
final JApplet myApplet = this;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JPanel frame = new PokerFrame();
frame.setVisible(true);
myApplet.getContentPane().add(frame);
}
});
}
catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}


import java.awt.Color;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.net.MalformedURLException;

/** A class that displays a poker game in a JFrame. */
public class PokerFrame extends JPanel {
public static final int HEIGHT = 350;
public static final int WIDTH = 600;
private static final int BUTTON_HEIGHT = 50;
private static final int BUTTON_WIDTH = 125;

// the following variables must be kept out as instance variables for scope reasons
private Deck deck;
private Hand hand;
private int[] handCount; // for keeping track of how many hands of each type player had
private int gamesPlayed;
private int playerScore;
private String message; // to Player
private boolean reviewMode; // determines state of game for conditional in doneBttn listener
private JLabel scoreLabel;
private JLabel gamesPlayedLabel;
private JLabel msgLabel;
private JLabel cardImg1;
private JLabel cardImg2;
private JLabel cardImg3;
private JLabel cardImg4;
private JLabel cardImg5;


/** Creates a new PokerFrame object. */
public PokerFrame() {

this.setSize(WIDTH, HEIGHT);
// this.setTitle("Poker");
gamesPlayed = 0;
playerScore = 0;
handCount = new int[10]; // 10 types of hands possible, including empty hand
message = "<HTML>Thanks for playing poker!"
+ "<br>You will be debited 1 point"
+ "<br>for every new game you start."
+ "<br>Click \"done\" to begin playing.</HTML>";
reviewMode = true;
this.add(createOuterPanel());
deck = new Deck();
hand = new Hand();
}

/** Creates the GUI. */
private JPanel createOuterPanel() {
JPanel outerPanel = new JPanel(new GridLayout(2, 1));
outerPanel.add(createControlPanel());
outerPanel.add(createHandPanel());
return outerPanel;
}

/** Creates the controlPanel */
private JPanel createControlPanel() {
JPanel controlPanel = new JPanel(new GridLayout(1, 2));
controlPanel.add(createMessagePanel());
controlPanel.add(createRightControlPanel());
return controlPanel;
}

/** Creates the message panel */
private JPanel createMessagePanel() {
JLabel msgHeaderLabel = new JLabel("<HTML>GAME STATUS:<br></HTML>");
msgLabel = new JLabel(message);
JPanel messagePanel = new JPanel();
messagePanel.add(msgHeaderLabel);
messagePanel.add(msgLabel);
return messagePanel;
}

/** Creates the right side of the control panel. */
private JPanel createRightControlPanel() {
scoreLabel = new JLabel("Score: 0");
gamesPlayedLabel = new JLabel("Games Played: 0");
JPanel labelPanel = new JPanel(new GridLayout(2, 1));
labelPanel.add(scoreLabel);
labelPanel.add(gamesPlayedLabel);

JButton doneBttn = new JButton("Done");
doneBttn.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));

class DoneListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (reviewMode) {
reviewMode = false;
startNewHand();
return;
}
else {
reviewMode = true;
while (!hand.isFull()) {
hand.add(deck.dealCard());
}
updateCardImgs();
score();
}
}
}

ActionListener doneListener = new DoneListener();
doneBttn.addActionListener(doneListener);
JPanel donePanel = new JPanel();
donePanel.add(doneBttn);

// stats button!
JButton statsBttn = new JButton("Statistics");
statsBttn.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));

final JPanel myFrame = this;
class StatsListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// add stats pop window functionality after changing score() method to keep track of that stuff
double numGames = gamesPlayed;
String popupText = "<HTML>You've played " + gamesPlayed + " games. This is how your luck has played out:<br>"
+ "<table>"
+ "<tr><td>HAND DESCRIPTION</td>PERCENTAGE</td></tr>"
+ "<tr><td>royal flush</td><td>" + getPercentage(0) + "</td></tr>"
+ "<tr><td>straight flush</td><td>" + getPercentage(1) + "</td></tr>"
+ "<tr><td>four of a kind</td><td>" + getPercentage(2) + "</td></tr>"
+ "<tr><td>full house</td><td>" + getPercentage(3) + "</td></tr>"
+ "<tr><td>straight</td><td>" + getPercentage(4) + "</td></tr>"
+ "<tr><td>four of a kind</td><td>" + getPercentage(5) + "</td></tr>"
+ "<tr><td>three of a kind</td><td>" + getPercentage(6) + "</td></tr>"
+ "<tr><td>two pair</td><td>" + getPercentage(7) + "</td></tr>"
+ "<tr><td>pair of jacks or better</td><td>" + getPercentage(8) + "</td></tr>"
+ "<tr><td>empty hand</td><td>" + getPercentage(9) + "</td></tr>"
+ "</table></HTML>";

JOptionPane.showMessageDialog(myFrame, popupText, "Statistics", 1);
}

private double getPercentage(int x) {
double numGames = gamesPlayed;
double percentage = handCount[x] / numGames * 100;
percentage = Math.round(percentage * 100) / 100;
return percentage;
}
}

ActionListener statsListener = new StatsListener();
statsBttn.addActionListener(statsListener);
JPanel statsPanel = new JPanel();
statsPanel.add(statsBttn);


JPanel bttnPanel = new JPanel(new GridLayout(1, 2));
bttnPanel.add(donePanel);
bttnPanel.add(statsPanel);
JPanel bottomRightControlPanel = new JPanel(new GridLayout(1,2));
bottomRightControlPanel.add(bttnPanel);
JPanel rightControlPanel = new JPanel(new GridLayout(2, 1));
rightControlPanel.add(labelPanel);
rightControlPanel.add(bottomRightControlPanel);
return rightControlPanel;
}

/** Creates the handPanel */
private JPanel createHandPanel() {
JPanel handPanel = new JPanel(new GridLayout(1, Hand.CARDS_IN_HAND));
JPanel[] cardPanels = createCardPanels();
for (JPanel each : cardPanels) {
handPanel.add(each);
}
return handPanel;
}

/** Creates the panel to view and modify the hand. */
private JPanel[] createCardPanels() {
JPanel[] panelArray = new JPanel[Hand.CARDS_IN_HAND];

class RejectListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (reviewMode) return;
// find out which # button triggered the listener
JButton thisBttn = (JButton) event.getSource();
String text = thisBttn.getText();
int cardIndex = Integer.parseInt(text.substring(text.length() - 1));
hand.reject(cardIndex-1);
switch (cardIndex) {
case 1:
cardImg1.setIcon(null);
cardImg1.repaint();
break;
case 2:
cardImg2.setIcon(null);
cardImg2.repaint();
break;
case 3:
cardImg3.setIcon(null);
cardImg3.repaint();
break;
case 4:
cardImg4.setIcon(null);
cardImg4.repaint();
break;
case 5:
cardImg5.setIcon(null);
cardImg5.repaint();
break;
}
}
}
ActionListener rejectListener = new RejectListener();

for (int i = 1; i <= Hand.CARDS_IN_HAND; i++) {
JLabel tempCardImg = new JLabel();
try {
tempCardImg.setIcon(new ImageIcon(new URL("http://erikaonearth.com/evergreen/cards/top.jpg")));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
String bttnText = "Reject #" + i;
JButton rejectBttn = new JButton(bttnText);
rejectBttn.addActionListener(rejectListener);
switch (i) {
case 1:
cardImg1 = tempCardImg;
case 2:
cardImg2 = tempCardImg;
case 3:
cardImg3 = tempCardImg;
case 4:
cardImg4 = tempCardImg;
case 5:
cardImg5 = tempCardImg;
}
JPanel tempPanel = new JPanel(new BorderLayout());
tempPanel.add(tempCardImg, BorderLayout.CENTER);
tempPanel.add(rejectBttn, BorderLayout.SOUTH);
panelArray[i-1] = tempPanel;
}
return panelArray;
}

/** Clears the hand, debits the score 1 point (buy in),
* refills and shuffles the deck, and then deals until the hand is full. */
private void startNewHand() {
playerScore--;
gamesPlayed++;
message = "<HTML>You have been dealt a new hand.<br>Reject cards,\nthen click \"done\"<br>to get new ones and score your hand.";
hand.clear();
deck.shuffle();
while (!hand.isFull()) {
hand.add(deck.dealCard());
}
updateCardImgs();
updateLabels();
}

/** Updates the score and gamesPlayed labels. */
private void updateLabels() {
scoreLabel.setText("Score: " + playerScore);
gamesPlayedLabel.setText("Games played: " + gamesPlayed);
msgLabel.setText(message);
}

/** Updates the card images. */
private void updateCardImgs() {
try {
String host = "http://erikaonearth.com/evergreen/cards/";
String ext = ".jpg";
cardImg1.setIcon(new ImageIcon(new URL(host + hand.getCardAt(0).toString() + ext)));
cardImg2.setIcon(new ImageIcon(new URL(host + hand.getCardAt(1).toString() + ext)));
cardImg3.setIcon(new ImageIcon(new URL(host + hand.getCardAt(2).toString() + ext)));
cardImg4.setIcon(new ImageIcon(new URL(host + hand.getCardAt(3).toString() + ext)));
cardImg5.setIcon(new ImageIcon(new URL(host + hand.getCardAt(4).toString() + ext)));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}

/** Fills any open spots in the hand. */
private void fillHand() {
while (!hand.isFull()) {
hand.add(deck.dealCard());
updateCardImgs();
}
}

/** Scores the hand.
* @return a string with message to be displayed to player
* (Precondition: hand must be full) */
private void score() {
String handScore = hand.score();
int pointsEarned = 0;
String article = "a ";
if (handScore.equals("royal flush")) {
handCount[0]++;
pointsEarned = 250;
}
else if (handScore.equals("straight flush")) {
handCount[1]++;
pointsEarned = 50;
}
else if (handScore.equals("four of a kind")) {
handCount[2]++;
pointsEarned = 25;
article = "";
}
else if (handScore.equals("full house")) {
handCount[3]++;
pointsEarned = 6;
}
else if (handScore.equals("flush")) {
handCount[4]++;
pointsEarned = 5;
}
else if (handScore.equals("straight")) {
handCount[5]++;
pointsEarned = 4;
}
else if (handScore.equals("three of a kind")) {
handCount[6]++;
pointsEarned = 3; article = "";
}
else if (handScore.equals("two pair")) {
handCount[7]++;
pointsEarned = 2;
article = "";
}
else if (handScore.equals("pair of jacks or better")) {
handCount[8]++;
pointsEarned = 1;
}
else if (handScore.equals("empty hand")) {
handCount[9]++;
article = "an ";
}
playerScore = playerScore + pointsEarned;
message = "<HTML>You had " + article + handScore + ",<br>which earned you " + pointsEarned + " points.<br>Click \"done\" to start a new hand.";
updateLabels();
}

}

最佳答案

我可以看到您的代码中有两个弱点。

首先。

如果您的小程序由多个类组成,您应该将 codebase 属性添加到您的 applet 标记中,以让它知道在哪里可以找到它们。例如:

<applet code="PokerApplet.class" 
codebase="http://localhost/classes" width="600" height="350">
</applet>

因此,在此示例中,您的 PockerApplet.class、PokerFrame.class 和其他使用的类应该位于 classes 文件夹中。

如果您不使用codebase属性,那么您的类应该位于带有applet标记的html页面所在的同一文件夹中。

你考虑这个吗?

第二。

你的小程序init()方法看起来很奇怪。尝试使用以下变体:

public void init() {
// Bad idea: the applet is not initialized yet
// but you already use link to its instance.
//final JApplet myApplet = this;

try {
SwingUtilities.invokeAndWait(new Runnable() {

public void run() {
JPanel frame = new PokerFrame();
//frame.setVisible(true); // You don't need this.
// You don't need myApplet variable
// to call getContentPane() method.
//myApplet.getContentPane().add(frame);
getContentPane().add(frame);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}

添加SSCCE后您可以获得更多帮助您的问题的代码。

关于java - 转换为 JApplet —— 我哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6273281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com