Dispose_on_Close закрывает JFrame, но он все еще активен - PullRequest
0 голосов
/ 23 февраля 2019

Я пишу программу, в которой мне нужно открыть JFrame при нажатии кнопки.Я установил для операции закрытия по умолчанию значение Dispose_on_close, чтобы при закрытии окна программа не закрывалась полностью.Во фрейме, который будет открыт, я хочу поместить JTable, поэтому я написал два метода, метод createFrame () и mechanicListTableProperties (), который является методом, который создает JTable и добавляет к нему элементы.Затем я вызываю mechanicListTableProperties внутри createFrame () и createFrame внутри метода actionPerformed ().Когда я открываю фрейм 1 раз, таблица показывается внутри окна, но если я закрываю и снова открываю фрейм, таблица также читается, и я вижу 2 таблицы, когда я пытаюсь снова увидеть только одну таблицу.Вот мой исходный код:

public class SeeMechanicsButtonHandler implements ActionListener {      
    JFrame mechanicListFrame;
    boolean isOpen = false;     
    JTable mechanicListTable;   
    JPanel tablePanel = new JPanel(new GridLayout()); 
    JScrollPane sp;     
    List<String> names = new ArrayList<String>();   
    String[] namesArray;

     public void createFrame() {        
        mechanicListFrame = new JFrame();
        mechanicListFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);       
        mechanicListFrame.setSize(new Dimension(500,500));      
        mechanicListFrame.add(tablePanel);
        mechanicListFrame.setVisible(true);                 
        //Prevents the window from being opened multiple times  
        mechanicListFrame.addWindowListener(new WindowAdapter(){            
            public void windowClosing(WindowEvent e) {              
                isOpen = false;                 
            }       
        });          
    }

     public void mechanicListTableProperties(){
        mechanicListTable = new JTable(){
        public boolean isCellEditable(int row, int column) {
            return false;           
            }       
        };      
        DefaultTableModel model = new DefaultTableModel();  
        model.addColumn("Nome", namesArray); 
        //Creates a column with title as Nome and lines as the array    

        mechanicListTable.setModel(model); //adds column to the the table
        mechanicListTable.setBounds(30, 40, 200, 300); //table size

        mechanicListTable.setFont(new Font("Arial Rounded MT", Font.BOLD, 15)); 
                        // adding it to JScrollPane
        sp = new JScrollPane(mechanicListTable);    
        tablePanel.add(sp);     
    }

public void actionPerformed(ActionEvent e) {    
    if(!isOpen) {       
        try {
             //SQL code to get the data from mechanics table
            ResultSet rs = ServerConnection.createQueryStatement("SELECT * FROM mechanics");
            while (rs.next()){
                //loop to add each entry in the table to an array list
                names.add(rs.getString("nome"));
                }
                //creates an array to put the values from the arraylist
                namesArray = new String[names.size()];
                for (int iterate = 0; iterate < names.size(); iterate++){
                    //loop that iterates through the arraylist and puts the values in the array
                    namesArray[iterate] = names.get(iterate);

                    System.out.println(namesArray[iterate]);
                     //prints to the console for testing purposes
                }
            } catch (SQLException e1) {
            e1.printStackTrace();
            }
        createFrame();
        isOpen = true;
     }
    }
}
...