I am writing a tetris game. When the application starts Jlabel with button "Play" opens. How do I switch to a different label (Board) within the existing Jframe?
Like this it opens the game directly.. But first I would want to use the ButtonPage class to show some welcome screen with a button instead and then call the game.
public class Tetris extends JFrame {
public Tetris(){
// JFrame Properties
setSize(198, 409);
setResizable(false);
setTitle("Tetris");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// ButtonPage buttons = new ButtonPage();
// add(buttons);
// buttons.setOpaque(true);
Board board = new Board(this);
add(board);
board.start();
} // end of constructor
public static void main(String[] args){
Tetris game = new Tetris();
game.setLocationRelativeTo(null);
game.setVisible(true);
game.setLayout(null);
} // end of main
} // end of class
Here is the ButtonPage class.
public class ButtonPage extends JPanel implements ActionListener{
JButton buttonPLAY = new JButton();
JLabel backgroundImage = new JLabel();
public ButtonPage(){
setLayout(null);
ImageIcon buttonIcon = new ImageIcon(getClass().getResource("PlayButton.png"));
ImageIcon buttonIconHover = new ImageIcon(getClass().getResource("PlayButtonHover.png"));
ImageIcon buttonIconClicked = new ImageIcon(getClass().getResource("PlayButtonClicked.png"));
int buttonHeight = buttonIcon.getIconHeight();
int buttonWidth = buttonIcon.getIconWidth();
buttonPLAY.addActionListener(this);
buttonPLAY.setActionCommand("Play");
buttonPLAY.setIcon(buttonIcon);
buttonPLAY.setRolloverIcon(buttonIconHover);
buttonPLAY.setPressedIcon(buttonIconClicked);
buttonPLAY.setBorderPainted(false);
add(buttonPLAY);
Dimension size2 = getSize();
Dimension size = buttonPLAY.getPreferredSize();
buttonPLAY.setBounds((192 - buttonWidth)/2, 100 ,buttonWidth, buttonHeight);
}// end of constructor
#Override
public void actionPerformed(ActionEvent e) {
if ("Play".equals(e.getActionCommand())) {
Tetris game = new Tetris();
// opens the window in the middle of the screen
game.setLocationRelativeTo(null);
// set the tetris window visible, unless its true - its invisible DUH!
game.setVisible(true);
game.setLayout(null);
}
} // end of actionPerformed
}// end of class
Using the actionPerformed method I can open the game in a new Frame, but I have no idea how to switch the Panels.
Thanks in advance for any tips!
Tetris is intanciated from main, the following line from actionPerformed():
Tetris game = new Tetris();
instanciates a second Tetris, it's really what's you want?
To add several panels to a frame, only one visible at a time, use CardLayout.
Have you tried a card layout?
http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
Related
Okai, so basically everything works but the second private class which I named project 2. In this program a grid of 2 by 2 is built out, now in one of the grid spaces (Project3), I want to have an image to be displayed.
public class Project1 extends JFrame
{
private Project2 topleft; // Buttons
private Project3 topright; // Picture
private Project4 bottomleft; // Schedule
//private Project5 bottomright; // Help - Pad
// Constructor
public Project1() throws IOException
{
// Display a title.
setTitle(" UAE University Interactive Course Calculator");
// Specify an action for the close button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a GridLayout manager.
setLayout(new GridLayout(2, 2));
// Create the custom panels.
topleft = new Project2();
topright = new Project3();
bottomleft = new Project4();
//bottomright = new Project5();
//bottomright = new Project5();
// Create the button panel.
add(topleft);
add(topright);
add(bottomleft);
//add(bottomright);
// setting formatting options
pack();
setResizable(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setVisible(true);
}
// Main method
public static void main(String[] args) throws IOException
{
new Project1();
}
}
This is where I got to so far, maybe my logic is wrong. All I need is just an image to be displayed, that's all
public class Project3 extends JPanel
{
private JButton run,fancyButton, hel, but, done_by,exit, past;
public Project3()
{
Icon java1 = new ImageIcon( "untitled1.jpg" );
fancyButton = new JButton( "Fancy Button", java1 );
add(fancyButton);
}
}
EDIT!!!: okai now this works, but it's a buttoned image, I want it to become just an image without the button any ideas?
One of the simplest options to load and show an image on a JPanel:
Create an ImageIcon.
Create a JLabel and pass the ImageIcon as a parameter.
Add the JLabel to the JPanel (or any other swing component).
You can find a detailed example by reading How to use icons.
I have been breaking my head for days over a project I have to do in my Java beginner class about GUI BorderLayout Jbutton and I really hope some one here can help me out to understand it or shed some light. My task is to create a BorderLayout window with 4 button left right up and down
Each button moves the window/ Borderlayout 20 pixel left or right or up or down.
I have already created a code with the buttons but I do not to know how to make the buttons move and above all I must not allow the Window to move out/ disappear from the desktop. Please be patient with me I am totally fresh student.
Here is my code so far:
import java.awt.*;
import javax.swing.*;
public class WindowBorder extends JFrame {
private static final long serialVersionUID = 1L;
private int x, y; //the coordinates for moving in the screen
public WindowBorder (String titel){
super (titel);
//create the buttons and the layout and add the buttons
JButton right = new JButton ("Right");
JButton left = new JButton ("Left");
JButton up = new JButton ("Up");
JButton down = new JButton ("Down");
//JButton center = new JButton ("Default"); hide the middle button
setLayout (new BorderLayout (75,75));
add(BorderLayout.EAST,right);
add(BorderLayout.WEST,left);
add(BorderLayout.NORTH,up);
add(BorderLayout.SOUTH,down);
//add(BorderLayout.CENTER,default); hide the middle button
//I must create the inner class with the constructors for the task project for school
class WindowBorderInner implements ActionListener {
#Override
public void actionPerformed (ActionEvent e){
if(e.getActionCommand().equals("right"))
//this is the part that I am lost :(
}
}
//configuration the size and the location of the Border layout
setSize (400,400);
setLocationByPlatform (true);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] arg){ //the test method
new WindowBorder("Move Window");
}
}
I'm on my mobile so I can't(won't) type out much code, but I copied this out of another thread
jFrame.setLocation(jFrame.getX() + 5, jFrame.getY());
You can manually set the location of the JFrame in this way when the action listener is called.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width); int y = (screenSize.height);
class ListenerInnerClass implements ActionListener {
#Override
public void actionPerformed (ActionEvent e){
if (e.getActionCommand ().equals("Right"))
Toolkit.getDefaultToolkit().getScreenSize();
setLocation (+20,y);
}
}
public MoveBorderDemo (String titel){
super (titel);
//create the buttons and the layout and add the buttons
JButton Right = new JButton ("Right");
JButton Left = new JButton ("Left");
JButton Up = new JButton ("Up");
JButton Down = new JButton ("Down");
Right.addActionListener(new ListenerInnerClass());
setLayout (new BorderLayout (75,75));
add(BorderLayout.EAST,Right);
add(BorderLayout.WEST,Left);
add(BorderLayout.NORTH,Up);
add(BorderLayout.SOUTH,Down);
//configuration the size and the location of the Border layout
setSize (400,400);
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(200,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] arg){ //the test method
new MoveBorderDemo ("Move Window");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
System.out.println("Screen width = " + d.width);
System.out.println("Screen height = " + d.height);
}
}
So I'm working an an assignment and I seemed to be stuck on a bug I can't seem to overcome. Essentially when trying to create a 10x10 grid, it isn't appearing while everything else (eg. title and menu) is when I'm running the application. Here's the essential part of what I've done so far
public class minesweeperGUI extends JFrame{
private JFrame gameGUI;
private JPanel board;
private JButton[][] boardButtons = new JButton [10][10];
public minesweeperGUI(){
gameGUI = new JFrame("Enhanced Minesweeper"); //Title of the Window
gameGUI.setVisible(true); //We want (true) to set it visible
gameGUI.setSize(400,550); //400 550
gameGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This will close the frame when you press X. IMPORTANT
gameGUI.getContentPane().setBackground(Color.CYAN);
gameGUI.setLayout(null);
//Panel for minesweeper board
board = new JPanel();
GridLayout experimentLayout = new GridLayout(10, 10);
board.setLayout(experimentLayout);
board.setSize(400,550);
for(int x=0;x<boardButtons.length;x++){
for(int y=0;y<boardButtons[x].length;y++){
boardButtons[x][y] = new JButton();
board.add(boardButtons[x][y]);
}
}
gameGUI.add(board);
}
public static void main(String[] args) {
minesweeperGUI mainInterface = new minesweeperGUI();
}
}
Any type of help would be greatly appreciated :)
gameGUI.setVisible(true); //We want (true) to set it visible
yes but its should be last code line in minesweeperGUI(), otherwise you added JComponents to the already visible Swing Gui (missing notifier for automatical refresh, repaint)
minesweeperGUI mainInterface = new minesweeperGUI();
should be wrapped into invokeLater, more in Oracle trail Initial Thread
class name should be MinesweeperGUI, search for Java Namings Convention
gameGUI.setLayout(null); and board.setSize(400,550);
missing there setBounds for board.setSize(400,550); (placing JPanel to JFrame, because JPanel has zero Dimension)
there no reason to use null layout, remove gameGUI.setLayout(null);
override getPreferredSize for private JPanel board;
remove code lines gameGUI.setLayout(null); and board.setSize(400,550);
add code line pack() before setVisible(true), for proper sizing for JFrame (based on getPreferredSize for private JPanel board;)
Remove the gameGUI.setLayout(null); call and move the next line to be after buttons adding
gameGUI.setSize(400,550); //400 550
gameGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This will close the frame when you press X. IMPORTANT
gameGUI.getContentPane().setBackground(Color.CYAN);
gameGUI.setVisible(true); //We want (true) to set it visible
I think one Problem is that you mix up your instances...
public static void main(String[] args) {
minesweeperGUI mainInterface = new minesweeperGUI();
}
makes a new Instance of your minesweeperGUI wich extends JFrame - so this simply makes a new JFrame...
but in your construktor you create another JFrame instance private JFrame gameGUI; and gameGUI = new JFrame("Enhanced Minesweeper"); ...
i suggest you remove the private variable gameGUI (private JFrame gameGUI;) and use simply this for your layout...
//private JFrame gameGUI; //remove this one!
private JPanel board;
private JButton[][] boardButtons = new JButton [10][10];
public minesweeperGUI(){
super("Enhanced Minesweeper"); //construktor from superclass
this.setVisible(true); //use of this
this.setSize(400,550); //use of this
...
//Panel for minesweeper board
board = new JPanel();
GridLayout experimentLayout = new GridLayout(10, 10);
board.setLayout(experimentLayout);
board.setSize(400,550);
for(int x=0;x<boardButtons.length;x++){
for(int y=0;y<boardButtons[x].length;y++){
boardButtons[x][y] = new JButton();
board.add(boardButtons[x][y]);
}
}
this.add(board); //use of this
}
you don't HAVE to write this.setXXX() you can also simply write setVisible(true)for instance...
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.
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();
}
});
}
}