S
S
Stanislav Ivanov2021-04-23 13:45:13
Java
Stanislav Ivanov, 2021-04-23 13:45:13

How to use uninitialized variables in button method?

Good afternoon. I'm learning Java on my own. At the moment I am mastering the graphic library. The following problem arose - I have 2 fields for entering text, in this case the dimension of a two-dimensional array fits into them. Then, when the button is pressed, the array is assigned this dimension, respectively, but an error is generated on line 32 (first_array = new Integer[Integer.parseInt(textField.getText())][Integer.parseInt(textField2.getText())];). Is there a way to use variables in a button method so that I can later work with their changed value?

package com.company;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

import java.awt.event.ItemEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ActionListener;
import javax.swing.JTable;

public class Main implements ActionListener{

    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Первое окно");
        frame.setSize(600, 600);

        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JLabel label = new JLabel("Введите длину и высоту двухмерного массива");
        JTextField textField = new JTextField(10);
        JTextField textField2 = new JTextField(10);

        Integer[][] first_array;

        JButton button1 = new JButton("Создать двумерный массив");
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                first_array = new Integer[Integer.parseInt(textField.getText())][Integer.parseInt(textField2.getText())];
            }
        });

        frame.add(panel);

        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e){ }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vodakov, 2021-04-23
@WaterSmith

Variables can of course be used. It is a pity that you did not indicate the error that you have.
It's better not to write like this:

first_array = new Integer[Integer.parseInt(textField.getText())][Integer.parseInt(textField2.getText())];.

And you yourself get confused and it’s hard for others to read, and there are a lot of problems when debugging.
So write:
int rowSize = Integer.parseInt(textField.getText());
int columnSize = Integer.parseInt(textField2.getText());
if (rowSize>0 && columnSize>0) {
    first_array = new Integer[rowSize][columnSize]; 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question