this is Sudoku.java this is the main class. Reminder does the time keeping, the SudokuBoardDisplay displays the board and draws images. The one who handles the logic is the SudokuModel

How do I make the images clickable and do something. how to display the remaining time as JLabel ....?

i used textfields but instead of the textfields being the container of the row col and val, i want to use the images ,,, when the images is clicked, a frame pops up with 9 buttons, that has a value of 1 to 9. and when the user chooses, the clicked image will turn to the value the button has.

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;
    public final class Sudoku extends JFrame implements ActionListener {
    private int row,col,mode,sec;
    private JButton start,exit,easy,med,hard,submit,change;
    private Container pane;
    private JFrame frame; 
    private JPanel panel;
    private String ftxt;t
    private SudokuModel model;
    private SudokuBoardDisplay board;
    //temporary, image click not done
    private JTextField row_board = new JTextField(1);
    private JTextField col_board = new JTextField(1);
    private JTextField value = new JTextField(1);
    public Sudoku(){
        frame=new JFrame("Sudoku Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,300);
        JLabel contentPane=new JLabel();
        ImageIcon icon=new ImageIcon("bg.png");
        contentPane.setIcon(icon);
        contentPane.setLayout(new BorderLayout());
        frame.setContentPane(contentPane);
        welcomeScreen();
    }
    public void welcomeScreen(){
        pane=frame.getContentPane();
        panel=new JPanel(new GridBagLayout());
        GridBagConstraints c=new GridBagConstraints();
        c.fill=GridBagConstraints.HORIZONTAL;
        pane.setLayout(new GridBagLayout());
        panel=new JPanel(new GridBagLayout());      
        start=new JButton("Start Game");
        exit=new JButton("Exit");
        start.addActionListener(this);
        exit.addActionListener(this);
        c.insets=new Insets(15,15,0,0);
        c.fill=GridBagConstraints.SOUTH;        
        c.gridx=1;
        c.gridy=3;
        pane.add(start,c);
        c.gridx=2;
        c.gridy=3;
        pane.add(exit,c);
        frame.setVisible(true);
        setLocationRelativeTo(null);
    }
    public void difficulty(){
        pane=frame.getContentPane();
        panel=new JPanel(new GridBagLayout());
        GridBagConstraints c=new GridBagConstraints();
        pane.setLayout(new GridBagLayout());
        easy=new JButton("Easy");
        med=new JButton("Medium");
        hard=new JButton("Hard");
        easy.addActionListener(this);
        med.addActionListener(this);
        hard.addActionListener(this);
        c.insets=new Insets(15,15,0,0);  
        c.fill=GridBagConstraints.HORIZONTAL;   
        c.gridx=0;
        c.gridy=2;
        pane.add(easy,c);
        c.gridx=1;
        c.gridy=2;
        pane.add(med,c);
        c.gridx=2;
        c.gridy=2;
        pane.add(hard,c);
        setResizable(false);    
        setLocationRelativeTo(null); 
        frame.setVisible(true);
    }
    public void play(String temp_board){
        Reminder startTimer;
        startTimer = new Reminder(mode);
        if(mode==300){
            JOptionPane.showMessageDialog(null, "You have 5 minutes to solve the puzzle. START!!!");
        }
        else if(mode==360){
            JOptionPane.showMessageDialog(null, "You have 6 minutes to solve the puzzle. START!!!");
        }
        else if(mode==480){
            JOptionPane.showMessageDialog(null, "You have 8 minutes to solve the puzzle. START!!!");
        }
        //displaying moving timer not done
        JLabel label=new JLabel("Time Passed: "+sec);
        model=new SudokuModel(temp_board);
        board=new SudokuBoardDisplay(model);
        change=new JButton("Change");
        submit=new JButton("Submit");
        JPanel controlPanel=new JPanel();
        controlPanel.setLayout(new FlowLayout());
        controlPanel.add(new JLabel("Row: "));
        controlPanel.add(row_board);
        controlPanel.add(new JLabel("Column: "));
        controlPanel.add(col_board);
        controlPanel.add(new JLabel("Value:"));
        controlPanel.add(value);
        controlPanel.add(change);
        controlPanel.add(submit);
        controlPanel.add(label);
        submit.setEnabled(false);
        change.addActionListener(new Sudoku.ChangeListener());
        submit.addActionListener(new Sudoku.ChangeListener());
        JPanel content=new JPanel();
        content.setLayout(new BorderLayout());
        content.add(controlPanel,BorderLayout.NORTH);
        content.add(board,BorderLayout.CENTER);
        setContentPane(content);
        setTitle("Sudoku");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setResizable(false);      
    }
    @Override
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==start){
            difficulty();
            pane.remove(start);
            pane.remove(exit);
        }
        else if(e.getSource()==exit){
            JOptionPane.showMessageDialog(null, "Thank you for using Sudoku application.");
            System.exit(0);
        }
        else if(e.getSource()==easy){
            try{
                Scanner sc=new Scanner(new File("boards/easy.txt"));
                ftxt="";
                mode=300;
                while(sc.hasNext()){
                    ftxt=ftxt+sc.nextLine();
                }
                JOptionPane.showMessageDialog(null, "Chosen difficulty is easy.");
                play(ftxt);
                }catch(FileNotFoundException ex){
                }
       }
       else if(e.getSource()==med){
            try{
                Scanner sc2=new Scanner(new File("boards/medium.txt"));
                ftxt="";
                mode=360;
                while(sc2.hasNext()){
                    ftxt=ftxt+sc2.nextLine();
                }
                JOptionPane.showMessageDialog(null, "Chosen difficulty is medium.");
                    play(ftxt);
            }catch(FileNotFoundException ex){
            }
       }
       else if(e.getSource()==hard){
                try{
                    Scanner sc3=new Scanner(new File("boards/hard.txt"));
                    ftxt="";
                    mode=480;
                    while(sc3.hasNext()){
                        ftxt=ftxt+sc3.nextLine();
                    }
                    JOptionPane.showMessageDialog(null, "Chosen difficulty is hard");
                    play(ftxt);
                }catch(FileNotFoundException ex){
                }
            }
}
class ChangeListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==change){
            try {
                row=Integer.parseInt(row_board.getText().trim())-1;
                col=Integer.parseInt(col_board.getText().trim())-1;
                int val=Integer.parseInt(value.getText().trim());
                if(model.isLegalMove(row,col,val,ftxt)){
                    model.setValue(row,col,val);      
                    if(!(model.zero_check()>0)){
                        submit.setEnabled(true);
                    }
                    board.repaint();
                }else{
                    JOptionPane.showMessageDialog(null, "Invalid Input");
                }
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(null, "Fill all fields");
            } catch (StringIndexOutOfBoundsException sioobe){
                JOptionPane.showMessageDialog(null, "Invalid Input");
            }
        }
        else if(ae.getSource()==submit){
            model.check();
            board.showResult(model.check());
        }
    }
}
public String getBoard(){
    return ftxt;
}
public static void main(String[] args){
    new Sudoku().setVisible(true);
}
}

this is SudokuBoardDisplay.java

import java.awt.*; 
import javax.swing.*;
public class SudokuBoardDisplay  extends JComponent{
private SudokuModel _model;
//commented out because _solve.getBoard().charAt(i+(j*10))=='0' produces an error
//private Sudoku _solve;
public SudokuBoardDisplay(SudokuModel model){
    setPreferredSize(new Dimension(450+2,450+2));
    _model = model;
}
@Override public void paintComponent(Graphics g){
    g.setColor(getBackground());
    g.fillRect(0,0,getWidth(),getHeight());
    g.setColor(Color.BLACK);
    drawGridLines(g);
    drawCellValues(g);
}
private void drawGridLines(Graphics g){
    for(int i=0;i<=9;i++){
        int down=i*50;
        g.drawLine(down,0,down,450);
        g.drawLine(0,down,450,down);
        if(i%3==0){
            down++;
            g.drawLine(down,0,down,450);
            g.drawLine(0,down,450,down);
        }
    }
}
private void drawCellValues(Graphics g){
    Image bufferedImage;
    for(int i=0;i<9;i++) {
        int y=(i+1)*50-15;
        for(int j=0;j<9;j++){
            if(_model.getValue(i,j)!=10){
                int x=j*50+15;
                String path="/images/"+_model.getValue(i,j)+".png";
                //these lines of code should identify if the cell is editable or not, but unfortunately. _solve.getBoard().charAt(i+(j*10))=='0' produces an error
                //String patht="/images/"+_model.getVal(i,j)+"t.png";
                //if(_solve.getBoard().charAt(i+(j*10))=='0'){
                //    bufferedImage=new ImageIcon(this.getClass().getResource(patht)).getImage();
                //}
                //else{  
                    bufferedImage=new ImageIcon(this.getClass().getResource(path)).getImage();  
                //}
                g.drawImage(bufferedImage,x-14,y-34,this);
            }
        }
    }
}
public void showResult(int i){
    if(i>0){
        JOptionPane.showMessageDialog(null, "FAIL!!! Better luck next time!");
    }
    else{
        JOptionPane.showMessageDialog(null, "Congratulations, you solved the sudoku puzzle.");
    }
    System.exit(0);
}
}

this is SudokuModel

public final class SudokuModel {
private int[][] _board;
public SudokuModel(){
    _board =new int[9][9];
}
public SudokuModel(String initialBoard) {
    this();
    initialize(initialBoard);
}
public void initialize(final String str) {
    clear();
    int row2=0;
    int col2=0;
    for(int i=0;i<str.length();i++){
        char c=str.charAt(i);
        if(c>='1'&&c<='9'){
            if(row2>9||col2>9){
                throw new IllegalArgumentException("SudokuModel: Initializing beyond 1-9 at row "+(row2+1)+" and col "+(col2+1));
            }
            _board[row2][col2]=c-'0';
            col2++;
        } 
        else if(c=='0'){
            col2++;
        } 
        else if(c=='/'){
            row2++;
            col2=0;
        }
        else{
            throw new IllegalArgumentException("SudokuModel: Special character '"+c+"' not allowed in board specification");
        }
    }
}
public boolean isLegalMove(int row,int col,int val,String y){
    char z;
    int x=col+(row*10);
    z=y.charAt(x);
    return (row>=0&&row<9&&col>=0&&col<9&&val>0&&val<=9&&z=='0');
}
public void setValue(int r,int c,int v){
    _board[r][c]=v;
}
public int getValue(int row,int col){
    return _board[row][col];
}
public void clear(){
    for(int row1=0;row1<9;row1++) {
        for(int col1=0;col1<9;col1++){
            setValue(row1,col1,0);
        }
    }
}
public int rows_check(int[][] _board){
    int sum=0,k=1,l=0;
            for(int i=l;i<k;i++) {
               sum=0;
               for(int j=0;j<9;j++){
                   sum=sum+_board[i][j];
               }
               System.out.println(sum);
               if(sum!=45){
                   return 1;
               }
               k++;
               l++;
               if(k>9){
                   break;
               }
            }
            if(sum!=45){
                return 1;
            }
            else{
                return 0;
            }
}
public int columns_check(int[][] _board){
    int sum=0,k=1,l=0;
        for(int j=l;j<k;j++) {
               sum=0;
               for(int i=0;i<9;i++){
                   sum=sum+_board[i][j];
               }
               System.out.println(sum);
               if(sum!=45){
                   return 1;
               }
               k++;
               l++;
               if(k>9){
                   break;
               }
            }
            if(sum!=45){
                return 1;
            }
            else{
                return 0;
            }
}
public int small_boxes_check(int[][] board){
        int sum=0,k=3,l=0,m=3,n=0;
        for(int o=l;o<3;o++){
                sum=0;
                for(int i=l;i<k;i++){
                   for(int j=n;j<m;j++){
                       sum=sum+_board[i][j];
                   }
                }
                System.out.println(sum);
                if(sum!=45){
                   return 1;
                }
                k=k+3;
                l=l+3;
                if(k>9){
                    k=3;
                    l=3;
                    m=m+3;
                    n=n+3;
                }
          }
                if(sum!=45){
                    return 1;
                }
                else{
                    return 0;
                }
}
//temporary check
public int check(){
    int check;
        check=rows_check(_board)+columns_check(_board)+small_boxes_check(_board);
        if(check>0){
            return 1;
        }
        else{
            return 0;
        }
}
public int zero_check(){
int x,y,a=0;
for(x=0;x<9;x++){
        for(y=0;y<9;y++){
          if(_board[y][x]==0){
            a++;
            break;
          }
    }
}
if(a>0){
    return 1;
}
else{
    return 0;
}
}
}

this is Reminder.java

import java.util.*;
import javax.swing.JOptionPane;
public class Reminder{
Timer timer;
public Reminder(int sec){
        timer=new Timer();
        timer.schedule(new stop(),sec*1000);
}
class stop extends TimerTask{
    @Override
    public void run(){
        JOptionPane.showMessageDialog(null, "TIME IS UP!!! YOU FAIL!!");
        timer.cancel();
        System.exit(0);
    }
}
}

Recommended Answers

All 2 Replies

(At least) two approaches:
1. Make each image an imageIcon in a JButton and use an ordinary ActionListener for the buttons. Chose a suitable button margin to make it look good.
2. Add a MouseListener to the panel where the images are drawn and use th x.y coords of the mouse click to work out which image was clicked

put points 1. and 2. by JamesCherrill together and to use JToggleButton, crossposted on another Java Forum

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.