Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 25 of 25

Thread: Matrix multiplying using separate input classes and a GUI

  1. #1
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Matrix multiplying using separate input classes and a GUI

    I have written code for the Matrix Multiplication GUI and I have set up two classes that build panels Matrix A and Matrix B. I used a toString() method in both classes, but how do I bring both methods into a multiplication class to do the math and return it to the GUI to display?

    public class MatrixA extends JPanel
    {
    	private JPanel panel;
    	private JTextArea matrixATextArea;
    	public static String inputA;
     
    	// constructor
    	public MatrixA()
    	{
    		setBorder( BorderFactory.createTitledBorder("Matrix A"));
    		buildPanel();
    		add( panel );
    		setVisible( true );
    	}
     
    	private void buildPanel()
    	{
    		matrixATextArea = new JTextArea( 10, 30 );
    		setPreferredSize( new Dimension( 400, 225 ) );
     
    		panel = new JPanel();
    		panel.setBorder( BorderFactory.createLineBorder( Color.black ) );
    		matrixATextArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    		panel.add( matrixATextArea );
    	}
     
    	public String getTextA() 
    	{
    		 return inputA = matrixATextArea.getText();
    	}
     
        public String toString()
        {
            return inputA;
        }
    }

    *Note: Matrix B is using the same exact code except inputB as the variable.

    MatrixGUI:
    public class MatrixGUI extends JFrame 
    {
    	private MatrixInstructions matrixMain;  // holding instructions.
    	private MatrixA matrixA;  // matrix on left side.
    	private MatrixB matrixB;  // matrix on right side.
    	private JPanel buttonPanel;  // to hold the calculate and exit button.
    	private JButton calcButton;  // to calculate the multiplication.
     
    	// constructor
    	public MatrixGUI()
    	{
    		// display title
    		setTitle( "Matrix Multiplier" );
     
    		// specify action for close button
    		setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
     
    		// create a layout.
    		setLayout( new BorderLayout() );
     
    		// create custom panels.
    		matrixMain = new MatrixInstructions();
    		matrixA = new MatrixA();
    		matrixB = new MatrixB();
     
    		// create button panel
    		buildButtonPanel();
     
    		// add everything to content pane.
    		add( matrixMain, BorderLayout.NORTH );
    		add( matrixA, BorderLayout.WEST );
    		add( matrixB, BorderLayout.EAST );
    		add( buttonPanel, BorderLayout.SOUTH );
     
    		pack();
    		setVisible( true );
    	}
     
    	// build the button panel in the south region.
    	private void buildButtonPanel()
    	{
    		// create a panel for buttons
    		buttonPanel = new JPanel();
     
    		// create the buttons
    		calcButton = new JButton( "Calculate" );
     
    		// register the action buttons
    		calcButton.addActionListener( new MyButtonListener() );
     
    		buttonPanel.add( calcButton );
    	}
     
        private class MyButtonListener implements ActionListener 
        {
            public void actionPerformed( ActionEvent e ) 
            {
            	JOptionPane.showMessageDialog(null, MatrixMult.resultant);
     
            }
         }
     
        public static void main( String[] args ) 
        {
            new MatrixGUI();
     
        }
    }

    and finally the multiplier, which was supplied by the instructor. This is the class that I am having the most issues with, my program compiles but will not do the calculations. I don't think that I am initializing anything in this class, but I need to pull the string from input A and input B into here and do the calculations, then create a string array and send it to the GUI to display.

    public class MatrixMult 
    {
    	public String inputA;
    	public String inputB;
    	public static String resultant;
     
        public static int[][] convertStringToArray( String str ) 
        {
     
            String[] rows = str.split("\\n"); // The \n character separates rows.
            int numRows = rows.length;
     
            // count the non white-space tokens, then count columns.
            int numCols = str.split("\\s+").length / numRows;
     
            Scanner strScanner = new Scanner( str );
     
            //System.out.println( numRows + " " + numCols );
     
            int[][] a = new int[ numRows ][ numCols ];
            for( int i = 0; i < numRows; i++ ) {
                for( int j = 0; j < numCols; j++ ) 
                {
                    a[ i ][ j ] = strScanner.nextInt();
                }
            }
     
            return a;
        }
     
        public static String toString( int arr[][] ) {
            int aRows = arr.length;
            int aColumns = arr[0].length;
            String str = "";
            for(int i = 0; i < aRows; i++) { // aRow
                for(int j = 0; j < aColumns; j++) { // aColumn
                    str += arr[ i ][ j ] + " ";
                }
                str += "\n";
            }
            return str;
        }
     
        public static void printArray( int a[][] ) {
            int aRows = a.length;
            int aColumns = a[0].length;
            for(int i = 0; i < aRows; i++) { // aRow
                for(int j = 0; j < aColumns; j++) { // aColumn
                    System.out.print( a[ i ][ j ] + " " );
                }
                System.out.println();
            }
        }
     
        public static int[][] multiply( int a[][], int b[][] ) {
     
            int aRows = a.length;
            int aColumns = a[0].length; // all rows have the same length.
            int bRows = b.length;
            int bColumns = b[0].length; // all rows have the same length.
     
            if ( aColumns != bRows ) {
                throw new IllegalArgumentException(
                              "A:Rows: " + aColumns 
                              + " did not match B:Columns " + bRows + ".");
            }
     
            int[][] resultant = new int[aRows][bColumns];
     
            for(int i = 0; i < aRows; i++) { 
                for(int j = 0; j < bColumns; j++) { 
                    for(int k = 0; k < aColumns; k++) { 
                        resultant[i][j] += a[i][k] * b[k][j];
                    }
                }
            }
     
            return resultant;
        } 
     
        public String toString()
        {
        	return resultant;
        }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    You have more than one variable named:resultant. This confuses me and probably confuses the compiler.
    Rename one of them so there names are different.

    Using static variables can cause problems. Can you remove the static and call the method to get the value.

  3. #3
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    ok, I changed all my variable so that they are not static anymore and renamed the string variable from resultant to finalMatrix....

    I called it to the MatrixGUI, is that correct?
     private class MyButtonListener implements ActionListener 
        {
            public void actionPerformed( ActionEvent e ) 
            {
            	MatrixMult matrixC = new MatrixMult();
            	JOptionPane.showMessageDialog(null, matrixC.finalMatrix);
     
            }
    }

    If that was correct, why is the results not being displayed?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    What data is in the new MatrixMult class instance you create in the actionPerformed method?
    You need to have a reference to the instance of the class that has the data.
    When you create an instance of the MyButtonListener class, pass a reference to the MatrixMult instance with the data in the MyButtonHandler class's constructor and save it in the class so it can be used to get to the data.

  5. #5
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    I guess I am really confused now. There is nothing in the new MatrixMult class, but need to reference the toString in the MatrixMult which should hold the results in a String. I am not understanding what you mean by "When you create an instance of the MyButtonListener class, pass a reference to the MatrixMult instance with the data in the MyButtonHandler class's constructor and save it in the class so it can be used to get to the data." Am I to create a string in the MyButtonHandler class and then reference it to the MatrixMult?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    What class creates the String you want in the listener?
    How can you get a reference to that class in the listener?

    One way is to pass a reference to the class with the String in the listener class's constructor.

    create a constructor for the listener class
    pass a reference in that constructor
    have the constructor save the reference in a class variable
    then the listener method can use that reference to call the method to get the String

  7. #7
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    The class that creates that String is the MatrixMult, and by creating a new MatrixMult referencing the toString return, right? And then in the MatrixMult I create a null reference to finalMatrix?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    Change the MyButtonListener class to have a constructor that takes a MatrixMult object as a parameter.
    Add a MatrixMult variable to the MyButtonListener class.
    Have the constructor save its argument in the class's variable.
    Use that variable to access the finalMatrix variable.

  9. #9
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    I feel like I am making you run in circles.....I am getting an error when I try to add a parameter to the MyButtonListener class stating that I need {} brackets which I have in there already. Adding another variable in this class, do you mean creating another String= null? and then String = finalMatrix?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    Have you made the changes I recommended for the MyButtonListener class?

  11. #11
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    Is this what you are talking about? I am getting an error on this.

     private class MyButtonListener implements ActionListener 
        {
            public void actionPerformed( ActionEvent e, String matrixC ) 
            {
            	matrixC = new MatrixMult().finalMatrix;
            	JOptionPane.showMessageDialog(null, matrixC);
     
            }
         }

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    No, I said a constructor. I said nothing about changing the parameters to the actionPerformed method.
    Add a constructor to the MyButtonListener class that takes a MatrixMult type as a parameter.

  13. #13
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    Am I on the right track?

     private class MyButtonListener implements ActionListener 
        {
        	public MyButtonListener()
        	{
     
        	}
            public void actionPerformed( ActionEvent e ) 
            {
     
            	MatrixMult matrixC = new MatrixMult();
            	JOptionPane.showMessageDialog(null, matrixC.finalMatrix);
     
            }
         }

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    Yes, now extend it
    Add a constructor to the MyButtonListener class that takes a MatrixMult type as a parameter.
    Last edited by Norm; March 16th, 2012 at 08:23 PM.

  15. #15
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    ok, I tried to add a parameter to the constructor, am I not doing this the right way. I have been trying to follow along with my book too.

    calcButton.addActionListener( new MyButtonListener() );
     
    		buttonPanel.add( calcButton );
    	}
     
        private class MyButtonListener implements ActionListener 
        {
     
        	public MyButtonListener(MatrixMult matrixC)
        	{
        		matrixC = new MatrixMult().finalMatrix;
        	}
            public void actionPerformed( ActionEvent e) 
            {
     
     
            	JOptionPane.showMessageDialog(null, " ");
     
            }
         }

    I keep getting an error and Eclipse wants to remove the parameters

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    Now create a class variable of type MatrixMult in the MyButtonListener class
    and in the constructor assign it the value of the MatrixMult argument passed in the constructor

  17. #17
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    ok...am I getting closer?
    // register the action buttons
    		calcButton.addActionListener( new MyButtonListener() );
     
    		buttonPanel.add( calcButton );
    	}
     
        private class MyButtonListener implements ActionListener 
        {
        	MatrixMult c = new MatrixMult();
     
        	public MyButtonListener(MatrixMult finalMatrix)
        	{
        		c = new MatrixMult().finalMatrix;
        	}
     
    		public void actionPerformed( ActionEvent e) 
            {
     
     
            	JOptionPane.showMessageDialog(null, " ");
     
            }
         }

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    No. I did not say to create new instances of the MatixMult class.
    I said to assign the parameter passed to the constructor (finalMatrix) to the class variable: c.
    <REMOVED> // assign the parameter to the local variable

    You did define a class variable but then added a new statement.

    There are a lot of basic terminology you dont understand:
    constructor
    define a variable
    parameter to a constructor.
    assign value of
    Last edited by Norm; March 16th, 2012 at 08:25 PM. Reason: removed actual code

  19. #19
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    yes I realize this and I am struggling to get through this class with a decent grade, so I am using my resources to learn from. Thank you for making me feel really stupid here. I am asking for guidance that's all I don't want you to give me the answer!

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    I have given you guidance in many posts. But you didn't understand the terminology.
    Look at posts starting at post#4, 6 and 8.
    I have been saying the same thing since then.

    Sorry about giving you the answer in post#18. I'll remove it now.

  21. #21
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    now I am getting this error:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at MatrixGUI$MyButtonListener.actionPerformed(MatrixGUI.java:80)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)

    and here is the code that I think is what you are asking for

        private class MyButtonListener implements ActionListener 
        {
     
        	MatrixMult c = new MatrixMult();
     
        	public MyButtonListener(MatrixMult finalMatrix)
        	{
        		c = finalMatrix;
        	}
     
     
    		public void actionPerformed( ActionEvent e) 
            {
     
     
            	JOptionPane.showMessageDialog(null, c.finalMatrix);
     
            }
         }

    Now after all that and following examples I am getting a null pointer, so now I need to find out what variable is null, the "c" or finalMatrix right?

  22. #22
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    ok I added in print statements
    public void actionPerformed( ActionEvent e) 
            {
            	System.out.println("c" + c);
            	System.out.println("c" + c.finalMatrix);
     
            	JOptionPane.showMessageDialog(null, c.finalMatrix);
     
            }
         }
    and found that cnull printed out but c.finalmatrix did not print out anything. So I need to initialize the finalMatrix variable in MatrixMult right?

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    What is the value of the variable passed to the constructor? If you pass a null value then you'll get a NPE.
    You need to pass a reference to an existing MatrixMult object that has or will have the finalMatrix value set.

  24. #24
    Member
    Join Date
    Mar 2012
    Posts
    42
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    the value of the finalMatrix should be the resultant from multiplying the two initial matrices together. So I want to pass the resultant to the toString finalMatrix, does that make sense?

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Matrix multiplying using separate input classes and a GUI

    I'm not sure how that is related to the NPE you are getting. You must change the code so a valid non null value is passed to the MyButtonListener constructor.

Similar Threads

  1. How to separate ArrayLists in memory?
    By wattieboi in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 22nd, 2011, 01:18 AM
  2. Replies: 1
    Last Post: May 25th, 2011, 07:55 AM
  3. updating SWT Slider from separate java class
    By ppmckee in forum AWT / Java Swing
    Replies: 0
    Last Post: April 14th, 2011, 03:23 PM
  4. how to separate this code in another class
    By Jhovarie in forum AWT / Java Swing
    Replies: 2
    Last Post: February 28th, 2011, 06:22 PM
  5. separate strings
    By ridg18 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: January 21st, 2011, 06:22 AM