A main menu for class A extends Applet - java

Hi i have made a game in java that extends applet. The game works perfectly fine but one of the requirements of this assignment is that there should be a menu. For example: As the program is run a screen with "Play" and "Quit" Options should appear and if user clicks "Play", this should lead on to the game, etc...
Q) Is there a way to do this specifically for applets?
I have attempted to make a a menu using the following code but it doesn't work (I think this is only for extends JPanel or JFrame not extends Applet):
MainMenu.java
public class MainMenu extends JFrame {
int screenWidth = 200;
int screenHeight = 150;
int buttonWidth = 100;
int buttonHeight = 40;
JButton Play;
JButton Quit;
public MainMenu() {
addButtons();
addActions();
Play.setBounds((screenWidth - buttonWidth)/2, 5 , buttonWidth, buttonHeight); // Positions the play button
Quit.setBounds((screenWidth - buttonWidth)/2, 10 , buttonWidth, buttonHeight);
//Adding buttons
getContentPane().add(Play); //add the button to the Frame
getContentPane().add(Quit);
pack();
setVisible(true);
setLocationRelativeTo(null);
setSize(screenWidth , screenHeight);
setTitle("Drop");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
}
private void addButtons() {
Play = new JButton ("Play");
Quit = new JButton ("Quit");
}
private void addActions() {
Play.addActionListener(new ActionListener() { // takes play button, adds new actionlistener
public void actionPerformed(ActionEvent e) { // Turn actionPerformed into variable for usage
dispose(); // wipes out Jframe
Board game = new Board();
game.run();
}
}); //Play Button
Quit.addActionListener(new ActionListener() { // takes quit button, adds new actionlistener
public void actionPerformed(ActionEvent e) { // Turn actionPerformed into variable for usage
System.exit(0);
}
}); //Quit Button
}
}
Launcher.java (Where menu is run from)
public class Launcher {
public static void main (String[] args){
new MainMenu();
}
}
Any help is much appreciated (Ideas, tutorials...)

For many components in one space, use a CardLayout as see in this short example.

I just ended up making a text based menu.
Initially set a variable to true, for eg: menu = true
and make the paint method paint whatever you want on the menu, like start...
if(menu) {
paint what's on the menu
}
then when when user clicks on a certain option within the menu turn menu variable to false i.e. menu = false.
You need to get mouse input to get the user's input so use either the mouse pressed or mouse clicked methods that come with the mouselistener.
After turning it false, get the paint method to paint your game.
i.e.
if(!menu) {
paint the game
}
Pretty much a bunch of if statements.
Hope this helps someone.

Related

Java swing bug with custom button

Having problems creating a custom JButton that is an Image. I had everything working with a normal JButton (like in the comment on the 2nd line) this way I wouldn't have to get an InputStream and start the button has an icon.
The trouble I'm having is that when I pressed the replay button (to play again) the window closes and only one window should pop out (as it happens with a "normal" JButton) but in this case 4-5 windows reopen and I don't know why.
I started thinking it was because the time to get an InputStream and doing ImageIO.read() the game would start and see that the variable running was false and then started reopening windows until it's true but I can't see how to verify that.
Note: I have functions that on ActionPerformed verify if the snake has collided and if so running = false and GameOver() will be called
public class GamePanel extends JPanel implements ActionListener {
JButton replay; //= new JButton("Play Again");
GamePanel() {
...
try {
InputStream is_replay = this.getClass().getResourceAsStream("/Snake/lib/img/playagain.png");
ImageIcon icon = new ImageIcon(ImageIO.read(is_replay));
replay = new JButton(icon);
replay.setBorder(BorderFactory.createEmptyBorder());
replay.setContentAreaFilled(false);
...
} catch (IOException|FontFormatException e) {
e.printStackTrace();
}
this.add(replay);
replay.setVisible(false);
replay.setBounds(SCREEN_WIDTH/2 - 100, SCREEN_HEIGHT - 200, 200, 100);
...
startGame();
}
public void startGame() {
spawnApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void gameOver(Graphics g) {
...
replay.setVisible(true);
replay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == replay) {
JComponent comp = (JComponent)e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose(); //It will close the current window
new GameFrame(); //It will create a new game
}
}
});
}
}
public class GameFrame extends JFrame {
GameFrame() {
JPanel panel = new GamePanel();
this.add(panel);
panel.setLayout(null); //Needed to add components
this.setTitle("Snake Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack(); //Fit JFrame to the components
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
public class SnakeGame {
public static void main(String[] args) throws Exception {
new GameFrame();
}
}
"in this case 4-5 windows reopen"
This suggests that you are probably adding multiple ActionListeners to the replay JButton. A new listener is added each time game over method is called, and this is incorrect. I would not add the ActionListener to the button in the game over method but rather add it once where you create the replay button.

Change JButton ImageIcon on Click

I am attempting to create a JFrame Application in java that is similar to Minesweeper but with slightly different rules/goals.
I have created a grid of JButtons, 12x12 and have a JButton 2D array.
I'm trying to change the image of a button when it is clicked (make it an X or an image of a gold nugget). I know how to do this if I had an individual name for each button, but it seems not logical to create 144 individual buttons and name each of them.
So what I need to do is on the click event of that button, change/set the image of that button, but in my action listener I can only figure it out if I know the specific array coordinates of that button.
My question is how do I change the Image of that specific button? Or how do I get the values of the button[?][?] so I can change the image of that button?
Thanks!
public class GoldPanel extends JPanel{
ImageIcon xImage = new ImageIcon("x.png");
ImageIcon goldImage = new ImageIcon("");
losingButtonListener loseButton = new losingButtonListener();
winningButtonListener winButton = new winningButtonListener();
JButton[][] button = new JButton[12][12];
//creates the layout
GridLayout layout = new GridLayout(12,12);
Random myRand = new Random();
public GoldPanel(){
//creates panel for name/title/score/etc
JPanel titlePanel = new JPanel();
add(titlePanel);
JLabel title = new JLabel("Welcome to the Goldmine Game!");
titlePanel.add(title);
//creates panel for the game board
JPanel gamePanel = new JPanel();
add(gamePanel);
gamePanel.setLayout(layout);
for(int i=0;i<12;i++)
{
for(int j=0;j<12;j++)
{
button[i][j] = new JButton(" ");
gamePanel.add(button[i][j]);
button[i][j].addActionListener(loseButton);
}
}
button[0][0].addActionListener(winButton);
}//end constuctor
private class losingButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}//actionPerformed
}//buttonListener
private class winningButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("you win");
}//actionPerformed
}//winningButtonListener
}//end GoldPanel class
If you look at the ActionEvent Documentation Page you see that every action event is constructed with an Object source. This means that if the system registers a click on the button this button gets passed to the constructor of the ActionEvent as source.
So you're actually getting the right button by casting this object to the right class.
[...]
public void actionPerformed(ActionEvent ae) {
JButton theRightButton = (JButton) ae.getSource();
// do stuff with the button...
}
[...]
Use a toggle button
http://docs.oracle.com/javase/7/docs/api/javax/swing/JToggleButton.html
So swing keeps track of the state for you in the button model.
Extend the button to pass x,y coord in the constructor and store them as field
Attach the same event listener to all buttons, cast source to button class and retrieve x/y of the button having been clicked
Change on the fly the pressed icon to mine or number in the event
Call click to all neighbouring empty fields if you want to replicate this rule, but make sure to check the pressed state so you don't loop back over already processed neighbours.

Comparing/Switching Selected JButtons within a 2D Array

Similar questions to my own have been asked, but I'm at a bit of a loss as to how to proceed. I really have a poor grasp of some of the more subtle nuances of java, so I apologize if anything isn't clear.
Say for example I wanted to compare one JButton within a 2D array with another. To be more specific, all of these JButton's would be stores within a 2D array and displayed in grid format. All of the buttons would have the same action listener that, upon the button being pressed, calls the setselected() method.
How would I go about comparing one of these selected JButton's with another selected JButton within the same array? And upon doing so, how could I swap the positions or more specifically, the icons of said buttons.
Below, I've included some example code and my own attempt on the subject. I understand that I can use .getSource() to grab a JButton object itself, but would this not only allow me to capture 1 selected button at a time. This is all considering the use of the same actionlistner code for each button, but a secular listener for each button.
The code below sets every icon to 1 of 7 randomly generated image icons. A frame is generated within secular main class. Upon being pressed or "selected" the image icons change to a selected iteration of the same image.
EDIT: Based on Ameer's suggestion, I've run into several nullpointer exceptions that are caused by my actionPerformed method. Is this as a result to my button array not being filled with button objects at this point, or am I simply presuming something within my code?
public class SButtonGame extends JFrame implements ActionListener {
public static ImageIcon[] icons={
new ImageIcon("img1.png"),
new ImageIcon("img2.png"),
new ImageIcon("img3.png"),
new ImageIcon("img4.png"),
new ImageIcon("img5.png"),
new ImageIcon("img6.png"),
new ImageIcon("img7.png"),
};
public static ImageIcon[] selectedIcons={
new ImageIcon("simg1.png"),
new ImageIcon("simg2.png"),
new ImageIcon("simg3.png"),
new ImageIcon("simg4.png"),
new ImageIcon("simg5.png"),
new ImageIcon("simg6.png"),
new ImageIcon("simg7.png"),
};
int rowNum=0;
int colNum=0;
JButton[][] Buttons;
boolean swaptf=false;
JButton CButton; // Selected button "holder". Doesn't accomplish anything I think it should
public SButtonGame(String title) {
//Constructs frame
super(title);
getContentPane().setLayout(null)
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(578,634);
int colLoc=10;
int rowLoc=10;
this.colNum=0;
this.rowNum=0;
for(int r=0; r<8; r++)
{
this.Buttons= new JButton[9][9];
this.rowNum++;
for(int c=0; c<8; c++)
{
ActionListener listner = new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(e.getSource() instanceof JButton)
{
((JButton) e.getSource()).setSelected(true);
CButton=(JButton)e.getSource();
}
}
};
int ranImg;
ranImg=0+(int)(Math.random()*7);
int sranImg=ranImg;
this.Buttons[this.colNum][this.rowNum]= new JButton(icons[ranImg]);
this.Buttons[this.colNum][this.rowNum].setSelectedIcon(selectedIcons[sranImg]);
this.Buttons[this.colNum][this.rowNum].addActionListener(listner);
this.Buttons[this.colNum][this.rowNum].setSize(59,59);
this.Buttons[this.colNum][this.rowNum].setLocation(rowLoc,colLoc);
rowLoc=rowLoc+69;
this.Buttons[this.colNum][this.rowNum].setVisible(true);
this.Buttons[this.colNum] [this.rowNum].setBorder(BorderFactory.createLineBorder(Color.black));
add(this.Buttons[this.colNum][this.rowNum]);
}
this.colNum++;
colLoc=colLoc+69;
rowLoc=10;
}
JButton Newgame;
Newgame= new JButton("NewGame");
Newgame.setSize(100, 30);
Newgame.setLocation(350, 560);
Newgame.setVisible(true);
add(Newgame);
JButton Quit;
Quit= new JButton("Quit");
Quit.setSize(60, 30);
Quit.setLocation(480, 560);
Quit.setVisible(true);
add(Quit);
New.addActionListener(new ActionListener()
{
//dispose of current frame and generates a new one;
public void actionPerformed(ActionEvent e)
{
dispose();
SButtonGame Frame;
Frame = new SButtonGame("ShinyButtons");
Frame.setVisible(true);
}
});
Quit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
}
#Override
public void actionPerformed(ActionEvent ae){
if(ae.getSource() instanceof JButton){
JButton sButton;
int rindex=0;
int cindex=0;
((JButton) ae.getSource()).setSelected(true);
sButton=(JButton)ae.getSource();
if(SButtonGame.this.Buttons[(int)sButton.getClientProperty("rownum")][(int)sButton.getClientProperty("colnum")].isEnabled()==true){
}
}
}
public static void main(String[] args)
{
SButtonGame Frame;
Frame = new SButtonGame("ButtonsGame");
Frame.setVisible(true);
}
}
Inside actionPerformed(ActionEvent e) method, you can access the 2D array of buttons by using SButtonGame.this.Buttons (ideally variable name should be buttons starting with small b).
You can then compare the clicked button with the buttons from array and do rest of your stuff.

Newly created JButton doesn't override the previously created JButtons

Essentially, what I have coded is a puzzle game.
It contains an image , and the image is further divided into 9 pieces which is placed onto JPanel containing a 3x3 JButton GridLayout. Initially, the 9 buttons are empty. When the user clicks "Start Game", the 9 buttons will then show the images on the buttons.
I used setPreferredSize() to set the size of the JPanel containing the 9 empty JButtons. After that, I used Inset ( 0,0,0,0 ) to make the button's contents fill the entire button.
But now, when I want to add the imaged buttons to replace the empty buttons when the user clicks "Start Game" , it doesn't work.
I think this is because the setPreferredSize() I set earlier on is preventing the Insets values from working.
I inserted some system.out.println values to check if the method is running, it runs, but the image still refuses to appear on the buttons when user clicks "Start Game" .
public class GameFrame extends JFrame implements ActionListener {
private JButton button1;
private JButton[] button = new JButton[9];
private Insets buttonMargin;
private boolean testImageMethod;
private JPanel puzpiece;
public GameFrame(){
//.. coding ..
// create new buttons - button1
button1 = new JButton("Start Game");
// add action event to "Start" button
button1.addActionListener(this);
// creates a new panel for the splitted puzzle pieces
puzpiece = new JPanel();
puzpiece.setLayout(new GridLayout(3,3));
// check if testImageMethod boolean ( in setupImage() ) is true,
//if it isn't, adds 9 buttons w/o images.
for(int a=0; a<9; a++){
if(testImageMethod){
}
else{
// adds 9 buttons without images
button[a] = new JButton();
puzpiece.add(button[a]);
puzpiece.setPreferredSize(new Dimension(500,200));
}
}
// adds puzpiece panel into the frame
this.add(puzpiece,BorderLayout.WEST);
//.. coding ..
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
// puzpiece.button.setVisible(false);
//puzpiece.remove(button);
// call setImage() method
setImage();
for(int a=0; a<9; a++){
// adds the new 9 buttons with images into panel
puzpiece.add(button[a]);
// test if method is running
System.out.println("qq");
}
}
else{
System.out.println("bbb");
}
}
// method setImage() divides the image into subimages
public void setImage(){
//.. coding ..
// test if method is running
System.out.println("a");
setupImage( count++, sc );
}
// method setupImage() adds the subimages to the buttons
private void setupImage( int a, Image wi )
{
// test if method is running
System.out.println("d");
buttonMargin = new Insets( 0, 0, 0, 0 );
button[a] = new JButton( new ImageIcon( wi ) );
button[a].setMargin( buttonMargin );
// test if method is running
System.out.println("e");
} // end method setupImage()
}
I'm not sure I know exactly what you're doing but, ...
It appears that you are populating a JPanel with a 3x3 grid of plain JButtons,
and that on button press you are adding in JButtons that display an image.
But I don't see you removing the original buttons before adding new buttons.
Nor do I see you call revalidate() and then repaint() on the puzpiece JPanel after changing components.
And even more importantly, why swap JButtons when it's much easier to swap ImageIcons in JButtons that are already held by the puzpiece JPanel? This is something that I recommended in comment 10 minutes ago but am now making an answer.
Simply setIcon for the said JButton, don't add JButton anew to the JPanel, already visible
A small example for the same :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 1/19/13
* Time: 10:05 AM
* To change this template use File | Settings | File Templates.
*/
public class ButtonImageTest
{
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private JButton button;
private int counter = 1;
private void displayGUI()
{
JFrame frame = new JFrame("Button Image Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
button = new JButton();
button.setBorderPainted(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (counter % 2 != 0)
{
button.setIcon(errorIcon);
counter = 2;
}
else
{
button.setIcon(infoIcon);
counter = 1;
}
}
});
contentPane.add(button);
frame.setContentPane(contentPane);
frame.setSize(100, 100);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonImageTest().displayGUI();
}
});
}
}

getContentPane and linking GUIs together

I'm having trouble with getContentPane() in my GUI.
public class CryptoMainMenu extends JPanel implements ActionListener {
public CryptoMainMenu()
{
Templates template = new Templates();
//setting up the primary panel
primaryPanel = new JPanel();
primaryPanel.setLayout(new BorderLayout());
//setting up algorithm button
algorithm = new JButton("Algorithm");
algorithm.addActionListener(this);
add(primaryPanel);
setSize(730, 400);
}
}
public class CryptoCategoriesMenu extends JFrame implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == back)
{
CryptoMainMenu main = new CryptoMainMenu();
main.setVisible(true);
this.setVisible(false);
}
}
}
In CryptoMainMenu if I'm extending JPanel I can't use getContentPane().add(primaryPanel), but if I just have add(primaryPanel), then my program isn't working because I linked all of my GUI classes together, so that when it gets to CryptoCategoriesMenu, and if I try pressing the JButton back, CryptoMainMenu shows as blank window. Is there something similar to getContentPane() that I can use with JPanel?
Edit:
This is suppose to a menu type GUI. In CryptoMainMenu, it displays a GUI where the user can press a button and it leads to another GUI which is CryptoCategoriesMenu. In CryptoCategoriesMenu, it shows another set of buttons and one of them is back. When I just have add() and I press back, CryptoMainMenu doesn't show up and that's the problem I'm having.

Categories

Resources