Home > Net >  Need help creating a simple program to create a matrix based on user input in java swing
Need help creating a simple program to create a matrix based on user input in java swing

Time:09-05

The program asks for user input in the terminal: the number of rows and columns. After getting said input it is supposed to generate a matrix using grid layout with the provided numOfRows and numOfColumns.

However, it doesn't really work the way it's supposed to sometimes. For example, an input of numOfRows as 1 & numOfColumns as 5 would not create a matrix with 1 row and 5 columns but instead, it would create one with 1 row and 6 columns.

Below is my code.

import java.awt.*;
import java.io.PrintStream;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Main extends JFrame  {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter num of rows for  matrix:");
        int numOfRow = kb.nextInt();
        kb.nextLine();

        System.out.println("Enter num of columns for  matrix:");
        int numOfColumns = kb.nextInt();
        kb.nextLine();

        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout(numOfRow, numOfColumns));
        frame.setLocation(0,0);
        for(int i=0; i<numOfRow; i  ){
            frame.add(new TextField());
        }

        for(int i=0; i<numOfColumns; i  ){
            frame.add(new TextField());
        }

        frame.pack();
        frame.setVisible(true);

    }
}

Any help or insight is genuinely appreciated.

CodePudding user response:

You're adding more text fields than you should. You add 1 row plus 5 columns, that's 6 total. If you want the number of items in a rectangular arrangement, you multiply the width times the depth to get the total.

    for(int i=0; i<numOfRow*numOfColumns; i  ){
        frame.add(new TextField());
    }

Delete the other for loop.

CodePudding user response:

Your for loop should be nested, not consecutive:

    for (int i = 0; i < numOfRow; i  ) {
        for (int j = 0; j < numOfColumns; j  ) {
            frame.add(new TextField());
        }
    }

enter image description here

  • Related