组件未显示在JScrollPane

时间:2017-03-01 09:11:01

标签: java jpanel jscrollpane gridbaglayout

我正在向使用JPanel的{​​{1}}添加组件。然后我将此GridBagLayout添加到JPanel,然后将其添加到带有标题边框的JScrollPane。但是,当我运行我的应用程序时,面板显示为空白 - 组件何处消失?

JPanel

如果我将public class Main { static JPanel surveyDetailsFieldsPane; static JScrollPane surveyDetailsScrollPane; static JPanel surveyDetailsTitledPane; static GridBagLayout detailsGBL; static JLabel lblJobName; static JTextField txtJobName; public static void main(String[] args) { JFrame f = new JFrame(); f.setMinimumSize(new Dimension(700, 300)); initComponents(); initFieldsPanel(); initScrollPane(); initTitledPane(); addComponentsToPanel(); surveyDetailsScrollPane.add(surveyDetailsFieldsPane); surveyDetailsTitledPane.add(surveyDetailsScrollPane); f.add(surveyDetailsTitledPane); f.setVisible(true); } private static void initComponents() { lblJobName = new JLabel("Job Name:"); txtJobName = new JTextField(20); } private static void initFieldsPanel() { surveyDetailsFieldsPane = new JPanel(); detailsGBL = new GridBagLayout(); surveyDetailsFieldsPane.setLayout(detailsGBL); } private static void initScrollPane() { surveyDetailsScrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } private static void initTitledPane() { surveyDetailsTitledPane = new JPanel(); surveyDetailsTitledPane.setLayout(new BorderLayout()); surveyDetailsTitledPane.setBorder(createTitledBorder("Survey Details")); } private static void addComponentsToPanel() { addComponentToSurveyDetailsGrid(lblJobName, 0, 0, 2, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.FIRST_LINE_START); addComponentToSurveyDetailsGrid(txtJobName, 2, 0, 8, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST); } private static void addComponentToSurveyDetailsGrid(Component component, int gridX, int gridY, int gridWidth, int gridHeight, int weightX, int weightY, int fill, int anchor) { GridBagConstraints constraint = new GridBagConstraints(); constraint.gridx = gridX; constraint.gridy = gridY; constraint.gridwidth = gridWidth; constraint.gridheight = gridHeight; constraint.weightx = weightX; constraint.weighty = weightY; constraint.fill = fill; constraint.anchor = anchor; constraint.insets = new Insets(5, 5, 5, 5); detailsGBL.setConstraints(component, constraint); surveyDetailsFieldsPane.add(component); } } 直接添加到surveyDetailsFieldsPane,我会看到组件显示为:

enter image description here

但是框架是空白的(除了垂直滚动条和标题边框):

enter image description here

请让我知道为什么我无法在JFrame中看到我的组件以及如何解决此问题。谢谢!

0 个答案:

没有答案