首页 > 解决方案 > 使用 Java Swing 将 JTable 中的内容输出到 TextArea

问题描述

所以我正在尝试使用 Java Swing 制作一个基本的 GUI。我有一些按钮,一个带有输入按钮的文本字段以及一个更大的文本区域。单击“显示所有团队”按钮时,此按钮的操作侦听器应将 JTable 内容输出到文本区域,但它不起作用并且没有任何输出。

package footballmanager;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollBar;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class FootballGUI 
    {
        private JFrame frame;
        private JTextField textField;


    //Launch the application.
    public static void main(String[] args)
    {
        FootballGUI window = new FootballGUI();
        window.frame.setVisible(true);
    }
    
    //Display the application
       public void displayGUI() {
       this.frame.setVisible(true);
   }
    
    //Create the application.
            
    public FootballGUI() 
    {
        frame = new JFrame();
        frame.setBounds(100, 100, 611, 471);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Text area
        final JTextArea testArea = new JTextArea(5,20);
        testArea.setBounds(6, 6, 329, 343);
        frame.getContentPane().add(testArea);
        
        // Buttons on the window
        JButton displayTeams = new JButton("Display all teams");
        // (x, y, w, h)
        displayTeams.setBounds(370, 6, 200, 29);
        frame.getContentPane().add(displayTeams);
        
        
        class MyActionListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
//                    String s = String.format("%s %s", "Club name", "Club points");
//                    testArea.setText(s);
                        String[] columnNames = {"First Name",
                                                "Last Name",
                                                "Sport",
                                                "# of Years",
                                                "Vegetarian"};
                                            Object[][] data = {
                        {"Kathy", "Smith",
                         "Snowboarding", new Integer(5), new Boolean(false)},
                        {"John", "Doe",
                         "Rowing", new Integer(3), new Boolean(true)},
                        {"Sue", "Black",
                         "Knitting", new Integer(2), new Boolean(false)},
                        {"Jane", "White",
                         "Speed reading", new Integer(20), new Boolean(true)},
                        {"Joe", "Brown",
                         "Pool", new Integer(10), new Boolean(false)}
                    };
                         JTable table = new JTable(data, columnNames);
                         
                         DefaultTableModel model1 = (DefaultTableModel) table.getModel();
                         int nRow = model1.getRowCount(), nCol = model1.getColumnCount();
                         Object [][] tableData = new Object [nRow] [nCol];
                         for (int i = 0; i < nRow; i++){
                             for (int j = 0; j < nCol; j++){
                             tableData [i][j] = model1.getValueAt (i,j);
                             testArea.append((String) tableData [i][j] + "\t");
                             }
                         }
                         testArea.append("\n");
                 
                 
                }
        }
            
        displayTeams.addActionListener(new MyActionListener());
        
        JButton goalSort = new JButton("Sort list by goals");
        goalSort.setBounds(370, 40, 200, 29);
        frame.getContentPane().add(goalSort);

        JButton winSort = new JButton("Sort list by most wins");
        winSort.setBounds(370, 74, 200, 29);
        frame.getContentPane().add(winSort);

        JButton randomMatch = new JButton("Generate random match");
        randomMatch.setBounds(370, 280, 200, 29);
        frame.getContentPane().add(randomMatch);
        
        JButton displayMatches = new JButton("Display all played matches");
        displayMatches.setBounds(370, 314, 200, 29);
        frame.getContentPane().add(displayMatches);

        JButton btnEnter = new JButton("Search for a match");
        btnEnter.setBounds(518, 404, 85, 39);
        frame.getContentPane().add(btnEnter);

        JScrollBar scrollBar = new JScrollBar();
        scrollBar.setBounds(320, 6, 15, 338);
        frame.getContentPane().add(scrollBar);
        
        textField = new JTextField();
        textField.setBounds(5, 410, 508, 28);
        frame.getContentPane().add(textField);
        textField.setColumns(10);
        
        JLabel lblMapGoesHere = new JLabel("List goes here");
        lblMapGoesHere.setBounds(342, 37, 263, 312);
        frame.getContentPane().add(lblMapGoesHere);
    }
}

标签: javaswing

解决方案


我重新编写了您的 GUI 以使用JTable.

这是修改后的 GUI 的样子。

足球图形用户界面

这是左键单击“显示所有团队”按钮后的样子。

足球 GUI 2

这是我对您的 GUI 所做的主要更改。

  1. 我通过调用该SwingUtilities invokeLater方法启动了 Java 应用程序。此方法确保在Event Dispatch Thread上创建和使用 Swing 组件。

  2. 我为我创建的两个使用了Swing 布局管理器。JPanelsJFrame 内容窗格使用默认的BorderLayout. 使用JTable JPanel默认值FlowLayout。使用JButton JPanel一个GridBagLayout. 您使用的固定布局不允许我调整JTextArea您正在使用的大小。

  3. 我用 aJTable来显示团队。我把JTableinJScrollPaneJScrollPane里面的 JPanel。

  4. 我在创建 GUI 之前创建了列和数据。通常,您要先创建应用程序模型,然后再创建 GUI。这是模型/视图/控制器模式的一个简单示例。

这是我使用的完整的可运行代码。

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class FootballGUI implements Runnable {

    private DefaultTableModel model;
    private JFrame frame;
    private JTable table;
    private String[][] data;

    // Launch the application.
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new FootballGUI());
    }

    public FootballGUI() {
        String[] columnNames = { "First Name", "Last Name", "Sport", 
                "# of Years", "Vegetarian" };
        this.model = new DefaultTableModel();

        for (String s : columnNames) {
            model.addColumn(s);
        }

        this.data = new String[][] { { "Kathy", "Smith", "Snowboarding", "5", "false" },
                { "John", "Doe", "Rowing", "3", "true" }, 
                { "Sue", "Black", "Knitting", "2", "false" },
                { "Jane", "White", "Speed reading", "20", "true" }, 
                { "Joe", "Brown", "Pool", "10", "false" } };
    }

    // Create the application.
    @Override
    public void run() {
        frame = new JFrame("Football GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createTablePanel(), BorderLayout.CENTER);
        frame.add(createButtonPanel(), BorderLayout.AFTER_LINE_ENDS);

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

    private JPanel createTablePanel() {
        JPanel panel = new JPanel();

        table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(scrollPane);

        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.weightx = 1.0d;

        JButton displayTeams = new JButton("Display all teams");
        displayTeams.addActionListener(new MyActionListener());
        panel.add(displayTeams, gbc);

        gbc.gridy++;
        JButton goalSort = new JButton("Sort list by goals");
        panel.add(goalSort, gbc);

        gbc.gridy++;
        JButton winSort = new JButton("Sort list by most wins");
        panel.add(winSort, gbc);

        gbc.gridy++;
        JButton randomMatch = new JButton("Generate random match");
        panel.add(randomMatch, gbc);

        gbc.gridy++;
        JButton displayMatches = new JButton("Display all played matches");
        panel.add(displayMatches, gbc);

        gbc.gridy++;
        JButton btnEnter = new JButton("Search for a match");
        panel.add(btnEnter, gbc);

        return panel;
    }

    public class MyActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            int count = model.getRowCount();
            for (int i = 0; i < count; i++) {
                model.removeRow(0);
            }
            
            for (int i = 0; i < data.length; i++) {
                model.addRow(data[i]);
            }
        }

    }
    
}

推荐阅读