creating a restart button help?

1- Do you use Eclipse? Try “Ctrl + Shift + F” :slight_smile:
2- I don’t know much about swing, but why don’t you just do something like:


menuBar = new JMenuBar();
            menu = new JMenu("Restart");
            menu.setMnemonic(1);
            menuBar.add(menu);
            menu.addActionListener(new ActionListener(){ 
            public void actionPerformed(ActionEvent e){
                            if(e.getSource() == menu){
                             game.init();
                            });

Where game.init(); is the method you call when the game FIRST starts.
You can play with

game.init(int level)

where with “int level” you say what level you want to restart. Maybe something like

game.init(game.currentLevel)

Mind you give us ALL your code in PASTEBIN? :slight_smile:

Won’t the game already be running when you call init()? Not to mention it’s more efficient to just reset values (wait…nvm, shouldn’t mention efficiency :P)
If there’s anything involving GUI in the init() method, it might get a bit screwed up. (e.g. add a component twice, etc.)

Yup you’re right, but who knows what’s in there! :slight_smile:
Maybe game.startLevel(int level) is safer.
Idk, I’d look at the whole code to give a better advice. (IN PASTEBIN :slight_smile: )

problem is that how restore initial values in init() method ? I’m asking this kind of issue !

Post your code using pastebin. :slight_smile:

OK everyone !? I have decided to post whole code since my question was a bit of vague. So please be patient to look at whole code below and to find out best way to handle this issue for this tiny little game(yes, I called it game because im beginner)
In addition I want to create a new MENU class that contains start, record etc, if you have more time, please consider this MENU class as well.

best regards,
ganaschka



package puzzle;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;
/**
 *
 * @author Ganaa
 */
public class Puzzle extends JFrame implements Runnable{

    private String iconNames[] = {"D:/images/1.png", "D:/images/2.png", "D:/images/3.png", "D:/images/4.png"
                                    , "D:/images/5.png", "D:/images/6.png"};
    private Vector images = new Vector();
    private JPanel centerPanel;
    private JLabel topLbl;
    private Vector allImages = new Vector();
    private Vector tovchVec;
    Button lastTovch = null;
    private Thread th;
    private int min=0, sec=0;
    boolean game = false;
    boolean running = false;
    JMenuBar menuBar;//цэс гаргах хэсэг
    JMenu menu;
    private JTextField score;// оноо гаргах хэсэг
    private int onoo = 0;
   

    public Puzzle(){
        super("Fruit Puzzle");
        Container con = getContentPane();
        con.setLayout(new BorderLayout());

        tovchVec = new Vector();

        centerPanel = new JPanel();
        topLbl = new JLabel("0:0", SwingUtilities.CENTER);
        topLbl.setBackground(new Color(255, 225, 169));
        topLbl.setOpaque(true);

        for(int i=0; i<iconNames.length; i++){
            images.add(new ImageIcon(iconNames[i]));
        }

        for(int i=0; i<images.size(); i++){
            allImages.add(images.get(i));
        }
        for(int i=0; i<images.size(); i++){
            allImages.add(images.get(i));
        }

        MyHandler handler = new MyHandler();

        for(int i=0; i<iconNames.length*2; i++){
            ImageIcon randIcon = randomIcon();
            final Button t = new Button(randIcon);
//            t.addActionListener(handler);
            t.addMouseListener(handler);
            tovchVec.add(t);
            centerPanel.add(t);            
            // menu bar
            menuBar = new JMenuBar();
            menu = new JMenu("Restart");
            menu.setMnemonic(1);
            menuBar.add(menu);
            menu.addActionListener(new ActionListener(){// I was trying on this but doesnt work :( yeah I need init()
            public void actionPerformed(ActionEvent e){
                            if(e.getSource() == menu){
                             
                                allImages.clear();
                                 for(int i=0; i<images.size(); i++){
                                    allImages.add(images.get(i));
                                }
                                   for(int i=0; i<images.size(); i++){
                                     allImages.add(images.get(i));
                             }
                                 for(int i=0; i<iconNames.length*2; i++){
                                     ImageIcon randIcon = randomIcon();
                                        Button b = (Button)tovchVec.get(i);
                                        b.setZurag(randIcon);
                                        b.setEnabled(true);
                                }
                            }           
                        }});
        
        setJMenuBar(menuBar);//JFrame dr nemj bn
      
        //score garah heseg
        score = new JTextField();
        score.setEditable(false);
        score.setFont(new Font("Serif",Font.BOLD,12));
        score.setBackground(new Color(255, 225, 169));
        con.add(score,BorderLayout.SOUTH);


        }

        con.add(centerPanel, BorderLayout.CENTER);
        con.add(topLbl, BorderLayout.NORTH);

        setLocation(500,50);
        setSize(530,635);
        setResizable(false);
        setVisible(true);

        th = new Thread(this);
        th.start();
        running = true;
    }
    // reset()
    

    public ImageIcon randomIcon(){

        int r = (int)(Math.random() * allImages.size());
        ImageIcon icon = (ImageIcon)allImages.get(r);

        allImages.remove(r);

        return icon;
    }

    public static void main(String[] args) {
        Puzzle game = new Puzzle();
        game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    // Thread run
    public void run() {
        while(running){
            try {
                Thread.sleep(1000);
                sec++;
                if(sec>59)
                {
                    min++;
                    sec = 0;
                }
                topLbl.setText(min+":"+sec);

                for(int i=0; i<tovchVec.size(); i++)
                {
                    Button t = (Button)tovchVec.get(i);
                    if(t.isEnabled()){
                        game = true;
                        break;
                    }

                }
                if(game == false){
                    running = false;
                    JOptionPane.showMessageDialog(Puzzle.this, "Баяр хүргье. Та "+min+" минут "+sec+" секундэд амжилттай гүйцэтгэлээ.");
                    th.stop();
                }
                game = false;
            } catch (InterruptedException ex) {
            }
        }
    }

    class MyHandler implements MouseListener{

        public void mouseClicked(MouseEvent e) {

            if( e.getClickCount() == 1)
            {
                for (int i = 0; i < tovchVec.size(); i++) {
                Button firstTovch = (Button)tovchVec.get(i);
                if(e.getSource() == firstTovch){
                    firstTovch.setNuuh(false);
                    if(lastTovch != null){
                        if(firstTovch.getHashCode() == lastTovch.getHashCode() && firstTovch.hashCode() != lastTovch.hashCode()){
                            firstTovch.removeMouseListener(this);
                            lastTovch.removeMouseListener(this);
                            ++onoo;
                            score.setText("\t\t   "+onoo+" "+"зураг амжилттай оллоо");
                            if(onoo ==6){
                                score.setText("\t\tбүх ижил зурагнуудыг амжилттай оллоо !");
                            }
                            firstTovch.setNuuh(false);
                            lastTovch.setNuuh(false);
                            firstTovch.setBackground(new Color(253, 195, 115));
                            lastTovch.setBackground(new Color(253, 195, 115));
                            firstTovch.setEnabled(false);
                            lastTovch.setEnabled(false);
                        }
                    }
                    lastTovch = firstTovch;

                }
                }
            }
            else return;
        }

        public void mousePressed(MouseEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseReleased(MouseEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseEntered(MouseEvent e) {
//            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void mouseExited(MouseEvent e) {
             for (int i = 0; i < tovchVec.size(); i++) {
                Button tovch = (Button)tovchVec.get(i);
                if(e.getSource() == tovch){
                    tovch.setNuuh(true);
                 }
             }
        }
    }
}


http://pastebin.java-gaming.org/1c5650f7519

| Nathan

I got a strange feeling that I’ve been quoted… Mhmmm nah, I don’t think so :slight_smile:


try
		{
			this.countHowMany("pastebin");
		}
		catch (Exception e)
		{
			System.out.println("I'S OVER 9000!");
		}

A little joke :slight_smile:

I prefer


		try {
			countHowMany("PasteBin");
		} catch (Exception e) {
			System.out.println("IT'S OVER 9000!");
		}

Hey do not judge on me please. I had no idea what in hell Pastebin was. like I said I’m beginner. If there is still problem with Pastebin or something, please post me specifically or give more details.

bests,
ganaschka

It is great that you’ve learned to use the code-tags. But as many have tried in various ways to tell you, big chunks of code are hard to read and difficult for anyone but the original coder to understand, especially without comments.

When you’re posting large chunks of code while writing a message, in the editor you’ll find a link just below the big white text-field, where it says: “Got extraordinary long code dumps? Use our pastebin to keep your thread readable. (link opens in new tab)”. If you click the link, a new pane/window will open, and you can paste your code in there. Then you click “Post Code”, and you get a link which you can use in your message.

Large chunks of code tend to make people think “Gah, I’m not reading through that!”, but if you post a nice, detailed description of your problem, and supply a Pastebin-link, then people interested in helping with the proposed problem, can sit back and look at just the code, and in a separate window, making it much easier to write a reply, without scrolling back and forth.

Hope this helps. As to your problem, it seems you’ve got plenty of good advice. Just reset the fields associated with your game, and restructure it to use an init-method. It’ll make your life much easier.

[code]

I’m cool!

[/code]

Please help !!! I had just posted “the whole code” on Pastabin

Where?

Even not listed on forum’s Lasted Pastebin. Sure use pastebin.java-gaming.org? not the real pastebin.com?

I don’t know but Pasta-bin sounds delicious right now :slight_smile:

postes on pastebin.java-gaming.org

Yeah but we need the link. It will appear after you posted the code.

Second page, it’s not off topic, and we still haven’t seen the code :cranky:
epic fail