Hi, I'm new-ish to java so please excuse any mistakes I make. Please Ignore stuff in brackets:[I've been making a dice game That when you press space, the dice "rolls" and a random number is generated. I've been trying to add the class to an html as an applet. I read somewhere that I had to Extend JApplet, but since I already extended JFrame I Can't extend Both. Can and I remove the JFrame inheritance and make my code work with JApplet? if so, How?]
Code so far:
EDIT: OK, I think I figured out what I'm supposed to do, but it doesn't display in my browser. Here's my new code:
What's Wrong with it?import java.awt.FlowLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.*; import java.awt.event.*; import java.applet.*; public class DiceGameApplet extends JApplet implements KeyListener, ActionListener { private JLabel label2 = new JLabel(); JTextArea displayArea = new JTextArea(); int width, height; JButton button = new JButton("Clear"); JScrollPane scrollPane = new JScrollPane(displayArea); Icon DiceGame = new ImageIcon( getClass().getResource( "dice.gif" ) ); static final String newline = System.getProperty("line.separator"); public void init() { width = getSize().width; height = getSize().height; button.addActionListener(this); displayArea.setEditable(true); displayArea.addKeyListener(this); scrollPane.setPreferredSize(new Dimension(375, 125)); getContentPane().add(scrollPane, BorderLayout.CENTER); getContentPane().add(button, BorderLayout.PAGE_END); setLayout( new FlowLayout() ); label2.setText( "" ); label2.setIcon( DiceGame ); label2.setToolTipText( "DiceGame" ); label2.setHorizontalTextPosition( SwingConstants.LEFT ); label2.setVerticalTextPosition( SwingConstants.BOTTOM ); add( label2 ); } public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) { if(e.getKeyChar() == e.VK_SPACE) { int d = (int)(Math.random() * 10) % 6 + 1; displayInfo(d); } displayArea.requestFocusInWindow(); } public void keyReleased(KeyEvent e) {} public void actionPerformed(ActionEvent e) { displayArea.setText(""); displayArea.requestFocusInWindow(); } private void displayInfo(int g){ displayArea.setText(""); String keyString = Integer.toString(g); displayArea.append(keyString + newline); displayArea.setCaretPosition(displayArea.getDocument().getLength()); } }
Thanks in advance!