我盯着我的小项目。

我有一个充满按钮的表格。按钮(示例#)是在运行时基于提供的资源添加的。请参见下面的示例:
java - Java Jscrollpane调整大小-LMLPHP

底层JFrame具有GridBox布局。第一行就是您所看到的,

button|button|textbox|button|button


第二行是简单的JScrollPane,其GridWidth和GridHeight设置为“ remainder”,有效地,应该填充窗口的其余部分,而无需添加到右侧的轻微填充。

这个JScrollPane包含另一个没有任何预设布局的JPanel,我用绝对值填充控件(此处为示例#0至#9的按钮)。当我缩小窗口时,面板会正确添加滚动条,使我可以滚动浏览这9个。请参见下文:

java - Java Jscrollpane调整大小-LMLPHP

不幸的是,当我手动添加另一个示例时,滚动条无法显示。该按钮超出了窗口边界的一半,但是我无法滚动到它。编辑:实际上,这10个以上的所有示例均无法正确显示。无论它们是沿着这10条创建的,还是以后在运行时添加的,或者由我自己添加的。看到:

java - Java Jscrollpane调整大小-LMLPHP

我怀疑滚动窗格或滚动窗格内部的面板有一些固定的边界,但我似乎找不到,问题出在哪里,我应该怎么做才能使程序正常工作。

提前致谢。

表单代码(删除了不必要的处理程序和不相关的方法)

如果看到TestCommonsButton,则它是扩展标准JButton的类,仅向其添加TestSuite类型属性。无论如何,目的都像标准的JButton一样

package forms;

import java.awt.Container;
import model.ModelConstants;
import java.awt.event.MouseEvent;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import model.*;

public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {

        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    backBtn = new javax.swing.JButton();
    runBtn = new javax.swing.JButton();
    headerTf = new javax.swing.JTextField();
    addBtn = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    mainPanel = new javax.swing.JPanel();
    detailsButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    java.awt.GridBagLayout layout = new java.awt.GridBagLayout();
    layout.columnWidths = new int[] {0, 6, 0, 6, 0, 6, 0, 6, 0};
    layout.rowHeights = new int[] {0, 15, 0};
    getContentPane().setLayout(layout);

    backBtn.setText("Back");
    backBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            backBtnActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    getContentPane().add(backBtn, gridBagConstraints);

    runBtn.setText("Run");
    runBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            runBtnActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    getContentPane().add(runBtn, gridBagConstraints);

    headerTf.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            headerTfActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.ipadx = 500;
    gridBagConstraints.weightx = 1.0;
    getContentPane().add(headerTf, gridBagConstraints);

    addBtn.setText("Add");
    addBtn.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            addBtnMouseClicked(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 8;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
    getContentPane().add(addBtn, gridBagConstraints);

    javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
    mainPanel.setLayout(mainPanelLayout);
    mainPanelLayout.setHorizontalGroup(
        mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 889, Short.MAX_VALUE)
    );
    mainPanelLayout.setVerticalGroup(
        mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 506, Short.MAX_VALUE)
    );

    jScrollPane2.setViewportView(mainPanel);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 7;
    gridBagConstraints.ipady = 200;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
    getContentPane().add(jScrollPane2, gridBagConstraints);

    detailsButton.setText("Details");
    detailsButton.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            detailsButtonMouseClicked(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 0;
    getContentPane().add(detailsButton, gridBagConstraints);

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



private void addBtnMouseClicked(java.awt.event.MouseEvent evt) {
    if (currentlySelected == null) {
        System.out.println("Adding Test Suite.");
        TestSuite ts = new TestSuite("Name Please");
        testSuites.add(ts);
        TestCommonButton tcb = new TestCommonButton(ts);
        mainPanel.add(tcb);
        new TestCommonsDetailsForm(ts).setVisible(true);

    } else {
        System.out.println("Attempting to add Test level" + (currentlySelected.getDepth() + 1));
    }
}

private void initTestSuites() {
    clearFrameButtons();
    headerTf.setText("Test Suites");
    headerTf.setEditable(false);
    int leftBound = ModelConstants.INIT_LEFT; //some padding
    int upperBound = ModelConstants.INIT_TOP; //some padding
    boolean top = true;
    for (TestSuite tc : testSuites) {
        TestCommonButton jb = new TestCommonButton(tc, tc.name);
        jb.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TestSuiteButtonMouseClicked(evt);
            }

        });
        mainPanel.add(jb);
        this.testCommonsButtons.add(jb);
        jb.setBounds(leftBound, upperBound, ModelConstants.TEST_SUITE_WIDTH, ModelConstants.TEST_SUITE_HEIGHT);
        if (top) {//we put button to top row, now put one below.
            upperBound += ModelConstants.TEST_SUITE_HEIGHT + ModelConstants.Y_MARGIN_BETWEEN_TESTS;
        }
        if (!top) {//we put button to bottom row. Return to top row and shift right.
            upperBound = ModelConstants.INIT_TOP;
            leftBound += ModelConstants.TEST_SUITE_WIDTH + ModelConstants.X_MARGIN_BETWEEN_TESTS;
        }

        top = !top;
    }

    revalidate();
    repaint();
}


/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Metal look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Metal (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Metal".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    MainFrame frame = new MainFrame();
    //Load TestSuites
    //TestingPurposes, replace with parser later.
    List<TestSuite> tss = new ArrayList();
    for (int i = 0; i < 10; i++) {
        tss.add(new TestSuite("Example#" + i));
    }

    //---------
    for (TestSuite ts : tss) {
        frame.testSuites.add(ts);
    }

    frame.initTestSuites();

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(() -> {
        frame.setVisible(true);
    });
}

private List<TestCommonButton> testCommonsButtons = new ArrayList<>();
private List<TestSuite> testSuites = new ArrayList<>();
private TestCommons currentlySelected = null;

// Variables declaration - do not modify
private javax.swing.JButton addBtn;
private javax.swing.JButton backBtn;
private javax.swing.JButton detailsButton;
private javax.swing.JTextField headerTf;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPanel mainPanel;
private javax.swing.JButton runBtn;
// End of variables declaration


}

最佳答案

javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);


您的mainPanel使用GroupLayout。 GroupLayout是最复杂的布局管理器之一,通常仅由IDE使用,因为它要求您设置垂直和水平约束。

在您的代码中使用:

mainPanel.add(tcb);


没有任何限制,因此布局管理器无法正常工作。

我从未使用过GroupLayout,因为约束对我来说太复杂了。因此,我建议您不要使用IDE生成表单。而是手动创建表单,以便您可以控制使用的布局管理器,然后可以根据需要使用适当的布局管理器(或使用不同布局管理器的嵌套面板)。

阅读有关Layout Managers的Swing教程中的部分,以获得更多信息和工作示例。

如果您想花时间学习如何使用GroupLayout,那么该教程确实提供了使用GroupLayout的示例。

关于java - Java Jscrollpane调整大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49364388/

10-10 02:29