import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Random; import java.applet.*; public class SimpleApplet extends JApplet { JButton ng; JPanel pane1; Container cont; int in[] = new int[9]; JButton jl[] = new JButton[9]; JButton jl1[] = new JButton[9]; String moves = Integer.toString(0); JPanel pane2; JLabel mov = new JLabel(moves); public void init() { cont = getContentPane(); JPanel pane = new JPanel(); ng = new JButton("New Game"); pane.add(ng); pane1 = new JPanel(); pane1.setLayout(new GridLayout(3,3,10,10)); Random randomGenerator = new Random(); jl[0] = new JButton("1"); jl[1] = new JButton("2"); jl[2] = new JButton("3"); jl[3] = new JButton("4"); jl[4] = new JButton("5"); jl[5] = new JButton("6"); jl[6] = new JButton("7"); jl[7] = new JButton("8"); jl[8] = new JButton(); for(int y = 0;y<9;y++) { if (y == 8){jl[y].setBackground(Color.BLACK);} else{jl[y].setBackground(Color.GRAY);} } for(int j =0;j<9;j++){in[j]=0;} for(int i =0;i<9;i++){ int x = randomGenerator.nextInt(9); jl[x].setFont(new Font("", Font.BOLD, 25)); if(in[x]==0) { pane1.add(jl[x]); in[x]=1; jl1[i]=jl[x]; } else i--; } pane1.setBackground(Color.BLACK); pane2 = new JPanel(); pane2.add(new JLabel("Moves: ")); pane2.add(mov); cont.add(pane1,BorderLayout.CENTER); cont.add(pane,BorderLayout.NORTH); cont.add(pane2,BorderLayout.SOUTH); Action pr = new Action(cont); ng.addActionListener(pr); for(int a=0;a<9;a++) { jl[a].addActionListener(pr); jl1[a].addActionListener(pr); } } class Action implements ActionListener { int j,j1; public Action(Container c) { Container container = c; } public void actionPerformed(ActionEvent evt) { String s = evt.getActionCommand(); if (s.equals("New Game")) { pane1.removeAll(); shufle(); mov.setText("0"); repaint(); pane1.validate(); pane2.validate(); } else if( s.equals("New Game") ==false) { } } public void shufle() { Random randomGenerator = new Random(); for(int j =0;j<9;j++){in[j]=0;} for(int i =0;i<9;i++) { int x = randomGenerator.nextInt(9); jl[x].setFont(new Font("", Font.BOLD, 25)); if(in[x]==0) { pane1.add(jl[x]); in[x]=1; jl1[i]=jl[x]; } else i--; } } } }
Well first of all thx for your time. I am making a game (applet) where i have 9 buttons.Eight of them got the numbers from 0-8 on them and there is one blank box. The objective of this game is to put them in order (1,2,3,4,5,6,7,8,blank). The thing is how do i make change position with the blank one. The thing is that only neighbouring buttons can swap. I have tried everythin but.. My main idea was to swap the 2 block from the arrays i use then panel.removeAll(); add them again validate and repaint the applet but i got a problem with swap,when i swap the to block of the array i want to swap end up with the same JButton. please help.