Reputation: 311
This is my homework.
My directions: Class GuessGame: This class contains the main function which creates a JFrame object, sets up the JFrame’s size, visibility and exit.
Class GuessGameFrame: GuessGameFrame class extends JFrame. So the GuessGameFrame class has all variables and methods defined in class JFrame.
I am not 100% sure what my problem is but I believe the JPanel is not working correctly
Any help would greatly be appreciated, if I left out anything important please let me know and I can add more detail.
main class:
public class GuessGame {
public static void main(String[] args){
GuessGameFrame localGuessGameFrame = new GuessGameFrame();
localGuessGameFrame.setVisible(true); //set visible
localGuessGameFrame.setSize(380,175); // set size 380 width 175 height
localGuessGameFrame.setDefaultCloseOperation(localGuessGameFrame.EXIT_ON_CLOSE); // needed to enable the red X button to close the program
}
}
extended class:
import javax.swing.*;
import java.awt.*;
public class GuessGameFrame extends JFrame
{
private int lastDistance; // distance between last guess and number
private Color background; // background color of application
private JFrame f;
static JPanel p;
private JButton b1;
private JLabel l1;
private JLabel l2;
JTextField t1 = new JTextField(8);
private JLabel l3;
//declare constructor
public GuessGameFrame()
{
//create our JFrame
f = new JFrame("Guessing game");
//create our panel
p = new JPanel();
p.setBackground(Color.MAGENTA); // background color is magenta
//create our labels
l1 = new JLabel("I have a number between 1 and 1000.");
l2 = new JLabel("Can you guess my number? Enter your first Guess:.");
l3 = new JLabel("Guess result appears here.");
//create our button
b1 = new JButton("New Game");
//add button and label to panel
p.add(l1); // Adds label 1
p.add(l2); // adds label 2
p.add(t1); // adds textfield 1
p.add(l3); // adds label 3
p.add(b1); // adds button 1
//add panel to JFrame
f.add(p);
}
}
Screenshot of the output window when executed:
I expect it to look like this:
Upvotes: 1
Views: 112
Reputation: 3409
You need remove JFrame f
in GuessGameFrame
class because GuessGameFrame
is already a JFrame
:
And update your code:
f = new JFrame("Guessing game");
to this.setTitle("Guessing game");
f.add(p);
to this.getContentPane().add(p);
Upvotes: 4