使JTable动态调整

时间:2017-08-03 10:51:02

标签: java swing jtable jpanel layout-manager

我在Jpanel里面有一个表,表的大小是固定的,我想让它变得动态。如果我们最大化帧,表的大小应该增加

下面是代码

public class LogsAutomationUIFrame extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTable table;
    private JTextField fieldDownloadPath = new JTextField(30);
    JLabel lblNewLabel_4;
    JLabel lblNewLabel_3;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LogsAutomationUIFrame frame = new LogsAutomationUIFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    static DefaultTableModel model= new DefaultTableModel(0, 0);
    private JPasswordField passwordField;
    /**
     * Create the frame.
     */
    public LogsAutomationUIFrame() {
        JFrame frame = new JFrame();
        table = new JTable();
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        table.setAutoCreateRowSorter(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 783, 567);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblEnvironment = new JLabel("Environment");
        lblEnvironment.setBounds(10, 44, 81, 21);
        contentPane.add(lblEnvironment);

        /*textField = new JTextField();
        textField.setBounds(103, 44, 109, 20);
        contentPane.add(textField);*/
        //textField.setColumns(10);
        String[] choices = { "CHOICE 1","CHOICE 2", "CHOICE 3","CHOICE 4","CHOICE 5","CHOICE 6"};

        final JComboBox<String> cb = new JComboBox<String>();
        //ComboBoxModel<String[]> choice = new ComboBoxModel<String[]>();
        final File folder = new File("");
        File folderParent = new File(folder.getAbsolutePath());
        List<String> choiceVal =  listFilesForFolder(folderParent);
        //List<String> choiceVal = new ArrayList<String>();

        cb.setModel(new ToComboBoxModel(choiceVal));
       cb.setBounds(103, 44, 109, 20);
        cb.setVisible(true);
        contentPane.add(cb);

        JLabel Path = new JLabel("Path");
        Path.setBounds(10, 76, 46, 14);
        contentPane.add(Path);

        textField_1 = new JTextField();
        textField_1.setBounds(103, 73, 109, 20);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        JLabel lblNewLabel = new JLabel("Search String");
        lblNewLabel.setBounds(10, 101, 81, 21);
        contentPane.add(lblNewLabel);

        textField_2 = new JTextField();
        textField_2.setBounds(103, 101, 109, 20);
        contentPane.add(textField_2);
        textField_2.setColumns(10);

        JButton btnSearchString = new JButton("Search String");
        btnSearchString.setBounds(231, 103, 137, 23);
        btnSearchString.addActionListener(new ActionListener()
        {
              public void actionPerformed(ActionEvent e)
              {
                  try {
                  LogsAutomationServiceImpl serviceImpl = new LogsAutomationServiceImpl();


                  String searchEnvironment = cb.getSelectedItem().toString();
                  String searchPath = textField_1.getText();
                  String searchString = textField_2.getText();
                  /*Properties prop = LogsAutomationServiceImpl.getProperties();
                  lblNewLabel_4.setText(prop.getProperty("results_limit"));*/
                  //System.out.println("textField:::"+textField.getText());
                  String password = passwordField.getText();
                  model =  serviceImpl.setTableData(searchEnvironment, searchPath, searchString, lblNewLabel_3, lblNewLabel_4, password);
                  table.setModel(model);
                  resizeColumnWidth(table);
                  table.setRowHeight(50);
                  } catch (Exception excption) {
                      excption.printStackTrace();
                  }
              }
            });

        contentPane.add(btnSearchString);

        JLabel lblNewLabel_1 = new JLabel("Results Number");
        lblNewLabel_1.setBounds(10, 150, 101, 14);
        contentPane.add(lblNewLabel_1);

        JLabel lblNewLabel_2 = new JLabel("Results Limit");
        lblNewLabel_2.setBounds(10, 178, 81, 14);
        contentPane.add(lblNewLabel_2);

        lblNewLabel_3 = new JLabel();
        lblNewLabel_3.setBounds(103, 150, 60, 14);
        contentPane.add(lblNewLabel_3);

        lblNewLabel_4 = new JLabel();
        lblNewLabel_4.setBounds(103, 178, 60, 14);
        contentPane.add(lblNewLabel_4);


         Object[] columnNames = {"host", "folder", "file", "grepResult"};
         Object[][] data = {
                    {"Buy", "IBM", new Integer(1000), new Double(80.50)},
                    {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
                    {"Sell", "Apple", new Integer(3000), new Double(7.35)},
                    {"Buy", "Nortel", new Integer(4000), new Double(20.00)}
                };


        table.setModel(model);
       // table.setCellSelectionEnabled(true);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
             public void mouseClicked(java.awt.event.MouseEvent evt) {
                int row = table.rowAtPoint(evt.getPoint());
                int col = table.columnAtPoint(evt.getPoint());

                if (col == 2) {
                    System.out.println("row is :::"+ row+":::"+col+"::::"+table.getValueAt(row, col));
                    String fileName = table.getValueAt(row, col).toString();

                    String hostName = table.getValueAt(row, 0).toString();
                    String folderName = table.getValueAt(row, 1).toString();
                    Exec obj = new Exec();
                    String password = passwordField.getText();
                    obj.downloadFile(hostName, cb.getSelectedItem().toString(), fileName, folderName, password);
                }
             }
            });
        //table.getSelectionModel().addListSelectionListener(new CustomTableCellRenderer());
        //table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());
        table.setSize(this.WIDTH, this.HEIGHT);
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(10, 267, 650, 205);
        getContentPane().add(scrollPane);
        //scrollPane.setSize(this.WIDTH, this.HEIGHT);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(10, 212, 81, 14);
        contentPane.add(lblPassword);

        passwordField = new JPasswordField();
        passwordField.setBounds(103, 203, 109, 20);
        contentPane.add(passwordField);
        contentPane.setSize(this.WIDTH, this.HEIGHT);
        //frame.getContentPane().add(contentPane);


    }



    public static void resizeColumnWidth(JTable table) {

        final TableColumnModel columnModel = table.getColumnModel();
        for (int column = 0; column < table.getColumnCount(); column++) {
            int width = 15; // Min width
            for (int row = 0; row < table.getRowCount(); row++) {
                TableCellRenderer renderer = table.getCellRenderer(row, column);
                Component comp = table.prepareRenderer(renderer, row, column);
                width = Math.max(comp.getPreferredSize().width +1 , width);
            }
            if(width > 500)
                width=500;
            columnModel.getColumn(column).setPreferredWidth(width);

        }
    }

    class MyRenderer implements TableCellRenderer {
          public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
              boolean hasFocus, int row, int column) {
            JTextField editor = new JTextField();

            if (value != null)
              editor.setText(value.toString());
            editor.setBackground((row % 2 == 0) ? Color.white : Color.cyan);
            return editor;
          }
    }

    public static List<String> listFilesForFolder(final File folder) {
        List<String> fileNames = new ArrayList<String>();
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                if(fileEntry.getName().toString().contains(".properties"))  {
                    fileNames.add(fileEntry.getName());
                }

            }
        }
        return fileNames;
    }
}

我尝试了很多方法来查看堆栈溢出链接,例如将大小设置为&#34; this.widht&#34;和&#34; this.height&#34;他们都没有工作。

当我将Jpanel宽度设为&#34; this.width&#34;并启动应用程序的大小非常小 当我试图为滚动条数据添加相同的东西时没有显示

1 个答案:

答案 0 :(得分:0)

I would first add the JTable to a JScrollPane, then add this JScrollPane to a JPanel, having a LayoutManager like BorderLayout and then add the JPanel to the JFrame... something like this:

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());

JScrollPane scp = new JScrollPane(table);
panel.add(BorderLayout.CENTER,scp);

this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(BorderLayout.CENTER,panel);
this.pack();
this.setVisible(true);

As Sergiy mentioned, as soon, as there is a LayoutManger, it rocks...