S
S
Stanislav Ivanov2021-03-22 01:30:57
Java
Stanislav Ivanov, 2021-03-22 01:30:57

How to create object in button method?

Good afternoon, I recently started studying Java, namely the Swing library, such a question - I create a button (button1) and set a method to it, or, as in Java, a listener using addActionListener, which, in theory, when pressed, should add a JTable table to the panel panel , but nothing happens when you click, can you tell me what's wrong, or maybe there are alternative methods for adding methods to buttons?

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

import java.awt.Font;
import java.awt.event.*;
import java.awt.FlowLayout;

import java.awt.event.ItemEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ActionListener;

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);

        JButton button1 = new JButton("Создать массив");
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTable table = new JTable(2,2);
                panel.add(table);
            }
        });

        JButton button2 = new JButton("Сохранить измененный массив в файл");

        panel.add(label);
        panel.add(textField);
        panel.add(textField2);
        panel.add(button1);
        panel.add(button2);

        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)
D
Dmitry Roo, 2021-03-22
@xez

Problem in rendering panel. If you try to resize the window, it will redraw with your changes.
Can be added panel.updateUI();afterpanel.add(table);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question