java - 如何在 JPanel 中启用溢出滚动条?

标签 java swing scrollbar

我不想以表格格式显示数据库中的数据,因此我尝试了您在代码中看到的方法。每次从数据库检索记录时,我都添加了新的 JPanel 容器,其中包含按钮和标签。但由于数据量很大,面板会溢出,但不会启用滚动选项。

我曾多次尝试使用 JScrollPane 但没有一种方法对我有帮助。

public class Test2 extends javax.swing.JFrame {

    private Connection con;
    private Statement st;
    private ResultSet rt;
    public int PageId = 8236;

    /**
     * Creates new form Test2
     */
    public Test2() {
        initComponents();

        this.setLocationRelativeTo(null);
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521","practice","perfect");
            st = con.createStatement();

            int height = 100;
            int width = sc.getWidth();
            int x = 0;
            int y = 0;

            ResultSet rs=st.executeQuery("select id, firstname || ' ' || lastname, salary from employee");
            while(rs.next()){
                JPanel g = new JPanel();
                g.setBounds(x, y, width, height);
                g.setBackground(Color.yellow);
                JLabel l = new JLabel(rs.getString(1));
                JLabel l1 = new JLabel(rs.getString(2));
                JLabel sal = new JLabel(rs.getString(3));
                JButton b = new JButton("View profile");
                b.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        JOptionPane.showMessageDialog(sc, "Clicked!!");
                    }
                });
                g.add(l);
                g.add(l1);
                g.add(b);
                sc.add(g);

                y += (height + 10);
            }
        }   
        catch(Exception e){
            JOptionPane.showMessageDialog(this, "Can't connect", "connection error", JOptionPane.ERROR_MESSAGE);
            System.out.println(e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        sc = new javax.swing.JPanel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        sc.setAutoscrolls(true);

        javax.swing.GroupLayout scLayout = new javax.swing.GroupLayout(sc);
        sc.setLayout(scLayout);
        scLayout.setHorizontalGroup(
            scLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 252, Short.MAX_VALUE)
        );
        scLayout.setVerticalGroup(
            scLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 483, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel sc;
    // End of variables declaration                   
}

最佳答案

I don't want to show data from the database in tabular format

为什么?根据您提供的代码,输出看起来很糟糕。您可以根据文本创建多个标签。这意味着每个标签的大小可以不同,这意味着多行上每个标签的布局将是随机且不对齐的。

如果您想在表格列中添加按钮,请查看:Table Button Column .

the panels are getting overflowed but no scroll option is getting enabled.

sc.setAutoscrolls(true);

这不是向组件添加滚动的方式。该组件需要添加到 JScrollPane 中:

JPanel scrollingPanel = new JPanel();
scrollingPanel.setLayout(...);
scrollingPanel.add(...);
scrollingPanel.add(...);

getContentPane.add(new JScrollPane(scrollingPanel), BorderLayout.CENTER);
pack();

注意,我从未使用过 SpringLayout。我建议您学习如何手动创建 GUI,这样您就不会依赖 IDE 来生成代码。代码会更容易理解和维护。

关于java - 如何在 JPanel 中启用溢出滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338088/

相关文章:

CSS在pre标签上显示垂直滚动条

apache-flex - 如何在Flex中控制Spark Datagrid的滚动器位置?

java - 从 getName() 的结果中刷新选项卡名称

java - 覆盖 Swing 类的 toString()

java - 根据字体和字符串项调整 JComboBox 的宽度

java - ListView 和线程安全的自定义适配器

ios - 表格 View 滚动的奇怪行为

java - 使用数组打印蛇图案

java - Intellij idea 13.1 如何检查正在运行的应用程序的VM选项

java - Hibernate 中用于自动递增 MySQL 主键的 Java 注释是什么 - @Id