Results 1 to 12 of 12
  1. #1
    sajjadbandari is offline Member
    Join Date
    Sep 2012
    Posts
    6
    Rep Power
    0

    Default pass data between jFrame objects and class in Java

    i'm trying to create a sudoko solver in NetBeans via Java, i created a new project, a package, and in the package i created a Java Class named sudokuCode and a jFrame Form named sudokuGUI. what i'm going to do is when a jButton on jFrame is pressed, sudokuCode catch values from jTextfields (that user entered before), store them in an array, do some calculations on them, and then update jTextfield values with new (actually solved) values, my question is how can i access jTexfield values from inside sudokuCode class and vice versa , is it possible? because they are in same package, or even is it the right way to do these things or i'm wrong?

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,453
    Rep Power
    25

    Default Re: pass data between jFrame objects and class in Java

    To access methods in another class. you need a reference to the class that can be used to call its methods.

    If you need more help, make a small simple program with some classes and methods that show your problem.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    sajjadbandari is offline Member
    Join Date
    Sep 2012
    Posts
    6
    Rep Power
    0

    Default Re: pass data between jFrame objects and class in Java

    hi
    thank you
    here is my problem
    its my project screenshot in netbeans
    pass data between jFrame objects and class in Java-sc.png
    and this is my interface look
    pass data between jFrame objects and class in Java-sc1.png
    i have jTextField1 & jTextField2 & jButton1
    in console everything is ok, my problem is how to change the input type and output type to GUI, i know i must use jTextField1.getText() & jTextField1.setText
    but they are not accessible form SudokuSolver.java
    & here comes my code:
    Java Code:
    package me;
    
    import java.util.ArrayList;
    import me.SudokuSolverGUI;
    
    public class SudokuSolver
    {
      // structure for holding sudoku grid
      ArrayList<Integer>[] cells=new ArrayList[81];
      
      private int[][] row=new int[][] {
        { 0, 1, 2, 3, 4, 5, 6, 7, 8}, // row 0
        { 9,10,11,12,13,14,15,16,17}, // row 1
        {18,19,20,21,22,23,24,25,26}, // row 2
        {27,28,29,30,31,32,33,34,35}, // row 3
        {36,37,38,39,40,41,42,43,44}, // row 4
        {45,46,47,48,49,50,51,52,53}, // row 5
        {54,55,56,57,58,59,60,61,62}, // row 6
        {63,64,65,66,67,68,69,70,71}, // row 7
        {72,73,74,75,76,77,78,79,80}  // row 8
      };
    
      private int[][] column=new int[][] {
        { 0, 9,18,27,36,45,54,63,72}, // column 0
        { 1,10,19,28,37,46,55,64,73}, // column 1
        { 2,11,20,29,38,47,56,65,74}, // column 2
        { 3,12,21,30,39,48,57,66,75}, // column 3
        { 4,13,22,31,40,49,58,67,76}, // column 4
        { 5,14,23,32,41,50,59,68,77}, // column 5
        { 6,15,24,33,42,51,60,69,78}, // column 6
        { 7,16,25,34,43,52,61,70,79}, // column 7
        { 8,17,26,35,44,53,62,71,80}  // column 8
      };
    
      private int[][] region=new int[][] {
        { 0, 1, 2, 9,10,11,18,19,20}, // region 0, upper left region (North West)
        { 3, 4, 5,12,13,14,21,22,23}, // region 1, top region (North)
        { 6, 7, 8,15,16,17,24,25,26}, // region 2, upper right region (North East)
        {27,28,29,36,37,38,45,46,47}, // region 3, left region (west)
        {30,31,32,39,40,41,48,49,50}, // region 4, middle region
        {33,34,35,42,43,44,51,52,53}, // region 5, right region (east)
        {54,55,56,63,64,65,72,73,74}, // region 6, lower left region (South West)
        {57,58,59,66,67,68,75,76,77}, // region 7, bottom region (south)
        {60,61,62,69,70,71,78,79,80}  // region 8, lower right right (South East)
      };
    
    
      public void init(String puzzle)
      {
        for (int i=0;i<81;i++)
        {
          cells[i]=new ArrayList<Integer>();
          String s=puzzle.substring(i,i+1);
          if (s.equals("."))  // unsolved cells, all values are possible
            for (int digit=1;digit<=9;digit++) cells[i].add(digit);
          else  // solved cells, only one possible value
            cells[i].add(Integer.parseInt(s));
        }
      }
      // display all possible of the grid
      public void printGrid()
      {
        String delimiter="";
    
        for (int i=0;i<81;i++)
        {
          String s="";
          for (int j=0;j<cells[i].size();j++)
          {
            s+=cells[i].get(j);
          }
          // make sure each cell contains exactly 8 character
          for (int j=0;j<8-cells[i].size();j++) s+=" ";
         
          if (s.length()>8) s="ALL     ";  // overflow
          s=delimiter+s;
          delimiter="|";
          System.out.print(s);
          if ((i+1)%9==0) { System.out.println(); delimiter=""; }
        }
      }
    
    
      // eliminate duplicate digit of the same row
      public boolean rowElimination()
      {
        boolean newSolved=false;
        for (int i=0;i<81;i++) // loop over all cells
        {
          int n=cells[i].size(); // get number of possible values of current cell
          if (n==1)  // this is a solved cell
          {
            Integer solvedDigit=cells[i].get(0);
            int rowNumber=i/9;   // which row does the current cell belong to ?        
            for (int j=0;j<9;j++)  // loop over all cells in the affected row
            {
              int cellNum=row[rowNumber][j];
              // all other cells in the row cannot contain the solved digit
              if (cellNum!=i && cells[cellNum].contains(solvedDigit)) 
              {
                cells[cellNum].remove(solvedDigit);
                if (cells[cellNum].size()==1) newSolved=true;  // newly solved cell found
              }
            }
          }
        }
        return newSolved;
      }
    
      // eliminate duplicate digit of the same column
      public boolean columnElimination()
      {
        boolean newSolved=false;
        for (int i=0;i<81;i++) // loop over all cells
        {
          int n=cells[i].size(); // get number of possible values of current cell
          if (n==1)  // this is a solved cell
          {
            Integer solvedDigit=cells[i].get(0);
            int columnNumber=i % 9;   // which column does the current cell belong to ?        
            for (int j=0;j<9;j++)  // loop over all cells in the affected column
            {
              int cellNum=column[columnNumber][j];
              // all other cells in the column cannot contain the solved digit
              if (cellNum!=i && cells[cellNum].contains(solvedDigit)) 
              {
                cells[cellNum].remove(solvedDigit);
                if (cells[cellNum].size()==1) newSolved=true;  // newly solved cell found
              }
            }
          }
        }
        return newSolved;
      }
    
      // eliminate duplicate digit of the same region
      public boolean regionElimination()
      {
        boolean newSolved=false;
        for (int i=0;i<81;i++) // loop over all cells
        {
          int n=cells[i].size(); // get number of possible values of current cell
          if (n==1)  // this is a solved cell
          {
            Integer solvedDigit=cells[i].get(0);
            int rowNumber = i / 9;    // which row does the current cell belong to ?        
            int columnNumber=i % 9;   // which column does the current cell belong to ?        
            int regionNumber=3*(rowNumber/3) + columnNumber/3;
            for (int j=0;j<9;j++)  // loop over all cells in the affected region
            {
              int cellNum=region[regionNumber][j];
              // all other cells in the region cannot contain the solved digit
              if (cellNum!=i && cells[cellNum].contains(solvedDigit))
              {
                cells[cellNum].remove(solvedDigit);
                if (cells[cellNum].size()==1) newSolved=true;  // newly solved cell found
              }
            }
          }
        }
        return newSolved;
      }
    
    
      public void solveByElimination()
      {
        boolean newCellSolved=false;
        while (true)
        {
          newCellSolved=false;
          if (rowElimination()) newCellSolved=true;
          if (columnElimination()) newCellSolved=true;
          if (regionElimination()) newCellSolved=true;
          if (!newCellSolved) break;  // no newly solved cell generated, quit
        }
      }
    
      // check whether the puzzle is solved
      public boolean isSolved()
      {
        boolean solved=true;
        for (int i=0;i<81;i++)
        {
          if (cells[i].size()!=1) { solved=false; break; }
        }
        return solved;
      }
    
      // check whether the puzzle is in a conflict state
      // if some cell contains no possible values at all, then it is in a conflict state
      public boolean isConflict()
      {
        boolean conflict=false;
        for (int i=0;i<81;i++)
        {
          if (cells[i].size()==0) { conflict=true; break; }
        }
        return conflict;
      }
    
      // backup or restore a puzzle
      private void cellCopy(ArrayList<Integer>[] src,ArrayList<Integer>[] dest)
      {
        for (int i=0;i<81;i++)
        {
          dest[i].clear();
          for (int j=0;j<src[i].size();j++)
          {
            dest[i].add(src[i].get(j));
          }
        }
      }
    
      public boolean solveByRecursion()
      {
        // before doing anything, backup the puzzle first
        ArrayList<Integer>[] backupCells=new ArrayList[81];
        for (int i=0;i<81;i++) // allocate back structure
        {
          backupCells[i]=new ArrayList();
        }
     
        cellCopy(cells, backupCells);  // backup
        
        // get next unsolved cell
        int unsolvedCellIndex=-1;
        for (int i=0;i<81;i++)
        {
          if (cells[i].size()>1) { unsolvedCellIndex=i; break; }
        }
    
        // no unsolved cell, the puzzle is solved
        if (unsolvedCellIndex==-1) return true;
    
        for (int j=0;j<cells[unsolvedCellIndex].size();j++) // try all possible digits
        {       
          Integer digit = cells[unsolvedCellIndex].get(j); 
          cells[unsolvedCellIndex].clear();  // clear all values
          cells[unsolvedCellIndex].add(digit);  // then fill it with only one value         
          solveByElimination();
          if (isSolved()) return true;  // solved
          if (!isConflict()) 
          {
            // The unsolved cell is filled with a trial value, but the puzzle is not solved,
            // call myself recursively to do a trial and error on another unsolved cell.
            if (solveByRecursion()) return true; // solved        
          }
          // the trial digit cannot solve the puzzle
          cellCopy(backupCells,cells); // restore from backup, try next digit
        }
        // all values of a cell have been tried 
        return false;   // cannot solve this way.
      }
    
      public static void main(String[] args) throws Exception
      {
        // change this String for another puzzle
        String puzzle= "9.1..4..."+
                       "......296"+
                       ".8....4.7"+
                       "21...6..."+
                       "..6.23..4"+
                       ".5.94...."+
                       ".....8.4."+
                       "....7..3."+
                       "....316.5";
    
    
    
        SudokuSolver solver=new SudokuSolver();
        solver.init(puzzle);
        solver.printGrid();
    
        solver.solveByElimination();
    
        System.out.println("After all eliminations:");
        solver.printGrid();
    
        System.out.println("Puzzle solvable by method of eliminations : "+solver.isSolved());
    
        if (!solver.isSolved())
        {
          solver.solveByRecursion();
          solver.printGrid();
    
          System.out.println("Puzzle solvable by method of recursion : "+solver.isSolved());
        }
    
      }
    }
    -----------------------------------------------------------------------------------------

    & GUI source, how must i change it?
    Java Code:
    package me;
    
    /**
     *
     * @author Faramarz
     */
    public class SudokuSolverGUI extends javax.swing.JFrame {
    
        /** Creates new form SudokuSolverGUI */
        public SudokuSolverGUI() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField2ActionPerformed(evt);
                }
            });
    
            jLabel1.setText("input");
    
            jLabel2.setText("output");
    
            jButton1.setText("solve");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(14, 14, 14)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jTextField1)
                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(19, 19, 19)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(28, 28, 28)
                            .addComponent(jButton1)))
                    .addContainerGap(19, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        }
    
        private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        }
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new SudokuSolverGUI().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        // End of variables declaration
    }
    Last edited by sajjadbandari; 09-05-2012 at 04:35 PM.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,453
    Rep Power
    25

    Default Re: pass data between jFrame objects and class in Java

    Please edit you post and wrap the code in code tags. See: BB Code List - Java Programming Forum

    how to change the input type and output type to GUI,
    Can you explain what the above means?

    Working with IDE generated names like: jTextField1 is very unpleasant. Variable names should describe the data that they hold, not just be the name of the class with an index number suffix.
    Last edited by Norm; 09-05-2012 at 04:20 PM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    sajjadbandari is offline Member
    Join Date
    Sep 2012
    Posts
    6
    Rep Power
    0

    Default Re: pass data between jFrame objects and class in Java

    hi again, sorry, i edited my post, excuse me
    ok, i will
    the code above gets a string (in this code a sample entered) like 28..95....7 etc.
    parses it to integers & sloves puzzle by two method, first elimination and second recursion
    then prints it to output, till now i'm ok
    i created a new jFormFrame and two text fields and one button
    i want change the program like this
    you enter your text in inputTexfield, then press solve button, then you receive solved puzzle in outputTextfield
    i just thought i can do it by this way in main method (i know i must remove printGrid() & init() methods)
    Java Code:
    s = inputTextfield.getText();
    //& after solving
    outputTextfield.setText(s);
    i imported me.SudokuSolverGUI at the top of SudokuSolver.java
    but it didn't worked
    i'm very very happy that you are reading my question, thank you & thank you :-* :-*
    no is it clear or i must explain more?

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,453
    Rep Power
    25

    Default Re: pass data between jFrame objects and class in Java

    When you execute your program what happens? Can you explain what you do and what the program does?
    Does the program compile without errors? Is there an error when you execute it?
    If so, copy and paste the full text of the error messages here.

    What happens when you press the solve button?
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    sajjadbandari is offline Member
    Join Date
    Sep 2012
    Posts
    6
    Rep Power
    0

    Default Re: pass data between jFrame objects and class in Java

    hi
    sorry for late, i was couple days away
    i changed something in my code
    i hope you remember what i was doing
    for accessing getText() & setText() of textFields i created to public methods in GUI source as come below
    Java Code:
    public String getter (){
            String i;
            i = inputTexfield.getText();
            return i;
        }
        
        public void setter (String args){
            outputTextfield.setText(args);
        }
    then i created a GUI object in SudokuSolver and know i can access setter() and getter() of GUI from SudokuSolver
    Java Code:
    String puzzle;
        SudokuSolverGUI test = new SudokuSolverGUI();
        puzzle = test.getter();
    till now everything is ok & one problem solved
    now i must call main() method of SudokuSolver in solveButtonActionPerformed to solve the puzzle
    i do it this way
    Java Code:
    private void solveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
            SudokuSolver start = new SudokuSolver();
            start.main(String[] args);
        }
    but i got this error:
    '.class' expected
    ';' expected
    unexpected type
    required: value
    found: class

    now how can i fix this new problem?
    how can i call the main method?
    main method follows:
    Java Code:
    public void main (String[] args) throws Exception
      {String puzzle;
        SudokuSolverGUI test = new SudokuSolverGUI();
        puzzle = test.getter();
        SudokuSolver solver = new SudokuSolver();
        solver.init(puzzle);
        solver.solveByElimination();
        if (!solver.isSolved())
        {
          solver.solveByRecursion();
          test.setter(puzzle);
          }
        }

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,453
    Rep Power
    25

    Default Re: pass data between jFrame objects and class in Java

    i got this error:
    Can you post the full text of the compiler's error message. It shows where the error occurred.
    how can i call the main method?
    You don't normally call the main() method. Can you explain why you need to?
    To call a static method (main() is static) specify the classname dot main(the args): Classname.main(<a String array>);
    <a String array> can be null if main() does not use it.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    sajjadbandari is offline Member
    Join Date
    Sep 2012
    Posts
    6
    Rep Power
    0

    Default Re: pass data between jFrame objects and class in Java

    i got 2 print screens first in my way, an second by way that you said, i got the same error
    here it is
    pass data between jFrame objects and class in Java-sc2.png
    pass data between jFrame objects and class in Java-sc3.png

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,453
    Rep Power
    25

    Default Re: pass data between jFrame objects and class in Java

    The args passed to a method are different from those used to define a method. You are coding the call to the method with the syntax used to define a method.
    Either define a one dim array and pass that to main(): new String[] {"something here ???"}
    or if main() does not use the args, then you can pass null as the argument.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    sajjadbandari is offline Member
    Join Date
    Sep 2012
    Posts
    6
    Rep Power
    0

    Default Re: pass data between jFrame objects and class in Java

    hi mr. Norm
    i did it this way (that you said)
    Java Code:
    SudokuSolver.main(null);
    & errors are gone, thank you :-*, thank you :-*, thank you :-*, thank you :-*
    but i think i must go and do some changes for converting main code flew from console to GUI, because it's runnable now, but does not solve the input Sudoku, by the way thank you very very very very much. :-*
    i'll be here if have some questions.
    once again, thank you :-*

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,453
    Rep Power
    25

    Default Re: pass data between jFrame objects and class in Java

    You're very welcome. Good luck with the rest of the project.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. pass data from Jdialog back to jFrame
    By Rogue45 in forum AWT / Swing
    Replies: 4
    Last Post: 04-05-2012, 12:35 AM
  2. Replies: 9
    Last Post: 10-21-2011, 09:07 PM
  3. Replies: 5
    Last Post: 06-14-2010, 06:10 PM
  4. Jframe pass variable to Applet
    By wayn in forum AWT / Swing
    Replies: 0
    Last Post: 03-10-2010, 09:54 AM
  5. Replies: 7
    Last Post: 05-06-2009, 12:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •