简体   繁体   中英

How can I make my JTable appear on button click?

The following code works, but only after the Display Values and the resize button is pushed. It does not appear until after I push both the Display Values and the resize button is pushed. How do I make it appear when only the Display Values button is pushed?

     public class myClass extends JFrame{
      String[] colNames = {"Item Name",
                    "Department",
                    "Original Price",
                    "Sales Price"};
     Object[][] input = {
     {"Kathy", "Smith",
     new Double(10), new Integer(5)},
     {"John", "Doe",
      new Double(10), new Integer(3)},
     {"Sue", "Black",
     new Double(10), new Integer(2)},
     {"Jane", "White",
      new Double(10), new Integer(20)},
     {"Joe", "Brown",
     new Double(10), new Integer(10)}
    };

    //display values
    JButton buttonDisplay = new JButton();
    buttonDisplay.setText("Display Values");
    container.add(buttonDisplay);        


    buttonDisplay.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {

            JTable jt = new JTable( input, colNames );
            JScrollPane pane = new JScrollPane( jt );
            jt.setPreferredScrollableViewportSize(
            new Dimension(200,200));
            pane.add(jt);
            container.add( pane );
            container.add(jt);
           /*Must use a JTextBox or JTable to display all the stored values for:
            * 
            * Item name 
                Department
                Original price
                Sale price 
            */
        }
    });

You only need to add the scrollpane, not both the scrollpane and the table. So remove the

container.add(jt);

line. Further, if you add something to a Container which is already visible, you should invalidate the Container as explained in the javadoc. Adding

container.revalidate();
container.repaint();

should make the table visible.

Try calling pack() after you add the new component. This will resize your JFrame to fit everything. This is what I assume your "resize button" is doing.

public void actionPerformed(ActionEvent evt) {
    // ... your other code ...
    container.pack();
}

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