public class SocialNetwork extends Program
implements Constants {
Canvas canvas = new Canvas();
public void init() {
breakoutButton = new JButton("Play Breakout Game");
breakoutButton.setForeground(Color.WHITE);
breakoutButton.setBackground(Color.BLACK);
add(breakoutButton, WEST);
breakoutButton.addActionListener(this);
getContentPane().setBackground(Color.BLACK);
addActionListeners();
add(canvas);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Play Breakout Game") || e.getSource() == breakoutButton) {
canvas.displayMessage("game started"); //displayMessage method displays the parameter string on the canvas.
Breakout bo = new Breakout();
bo.setVisible(true);
}
}
This is the main code which creates the button which is supposed to launch the breakout game. The code for breakout is :
public class Breakout extends GraphicsProgram {
public void run() {
setBackground(Color.BLACK);
setUpBricks();
points = new GLabel("Points: " + pointsCounter);
add(points, getWidth()/2 - points.getWidth()/2, getHeight() - points.getAscent());
points.setColor(Color.WHITE);
for(int i=0; i < NTURNS; i++) {
addMouseListeners();
setUpGame();
playGame();
if (brickCounter == 0) {
GLabel winner = new GLabel("You Win! You got " + pointsCounter + " points.");
winner.setFont("Times New Roman-25");
winner.setColor(Color.WHITE);
add(winner, getWidth()/2 - winner.getWidth()/2, getHeight()/2 - winner.getAscent()/2);
break;
}
}
if (ball.getY() > getHeight()) {
GLabel message = new GLabel("Game Over! You got " + pointsCounter + " points.");
message.setFont("Times New Roman-25");
message.setColor(Color.WHITE);
add(message, getWidth()/2 - message.getWidth()/2, getHeight()/2 - message.getAscent()/2);
}
}
The problem is that when I click on the button, it registers the click, opens a JFrame, but does not run the program. There is just a blank JFrame. What am I doing wrong? Note: I have only posted the basic code for the breakout game part.
Your code creates the
Breakoutobject and sets its visibility:However, you never invoke any other methods. For example you may want to invoke a
runmethod or amainmethod. You have to call those methods somehow in order to execute the code.Another option would be to add a listener to the
Breakoutclass so that it executes your code when the window opens, something like this: