简体   繁体   中英

How can I insert my JTable into a panel?

I am trying to insert a newly created JTable into a panel I have also created but am having no luck. On top of this I am also trying to create a table that is edited based on a button being pressed where the button reads and stores the user input and then fills in the correct columns and was not sure if I have gone about this the right way.

Code is as follows:

public class resultTable extends JPanel {

    public void mainTable() {
        GridLayout mainLayout = (new GridLayout(1, 0));
        String[] columnNames = { "NAME", "GRADE" };
        Object[][] data = { { nameField.getText(), gradeField.getText() } };
        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
    }
}

public class myBottomPanel extends JPanel {

    public myBottomPanel()
    {
        setBorder(BorderFactory.createTitledBorder("Students/Results"));
        setOpaque(false);
        setPreferredSize(new Dimension(0, 100));
        add(resultField);
        resultField.setAlignmentX(LEFT_ALIGNMENT);
        add(resultTable);
    }
}

public class buttonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
        String studentName;
        int studentMark;

        if (event.getSource() == addEntry) {
            studentName = nameField.getText();
            String intMark = gradeField.getText();
            studentMark = Integer.parseInt(intMark);
            System.out.println(studentName);
            System.out.println(studentMark);
        }
    }
}
}

If you want the table to be scrollable and visible, make sure the table is added as a view of a JScrollPane

// Create the Scroll panel and add the table (view)
JScrollPane jsp = new JScrollPane(table)
....
// Add the Scroll Panel to the main panel
myBottomPanel.add(jsp)

Then, add the JScrollpane to a panel and the table should be visible and scrollable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM