开发者

Conversion to JApplet -- where did I go wrong?

开发者 https://www.devze.com 2023-03-11 08:08 出处:网络
PokerFrame (called from a viewer class) worked perfectly, but once I tried to convert it to an applet, it won\'t load. I don\'t get any runtime exceptions, just a blank applet space. I won\'t be able

PokerFrame (called from a viewer class) worked perfectly, but once I tried to convert it to an applet, it won't load. I don't get any runtime exceptions, just a blank applet space. I won't be able to respond/pick an answer until hours from now, but I'd really appreciate any insights anyone might have....

<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();
    }

}


I can see two weak points in your code.

First.

If your applet consists of several classes, you should add codebase attribute to your applet tag, to let it know where to find them. For example:

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

So, in this example, your PockerApplet.class, PokerFrame.class and other used classes should be in classes folder.

If you don't use codebase attribute, then your classes should be in the same folder where your html page with applet tag resides.

Do you consider this?

Second.

Your applet init() method seems strange. Try to use the following variant:

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");
    }
}

You can get more help, after you add SSCCE code to your question.


first add the frame then set it to visible. THat usually works

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号