Add a JScrollPane to a JFrame

谁说我不能喝 提交于 2019-12-11 04:06:38

问题


I have a question in relation to adding components to a Java frame.

I have a JPanel with two buttons and also a JScrollPane that has a JTable added to it. I am wanting to add both these to a JFrame.

I can add either the JPanel to the JFrame, or the JScrollPane to the JFrame and they display correctly. I am having trouble adding them both to the JFrame and displaying them both.

Is there something related to JFrames that do not allow this? Any help will be appreciated.

EDIT

The problem is not with the layout (at least I do not think that it is), the problem is that the ScrollPane is not displaying correctly. Here is an image to show what I mean:

http://canning.co.nz/Java/ScrollPane.png

Here is the code:

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    guiPanel.add(scrollPane, gbc);
    guiPanel.add(buttons, gbc);        

    guiFrame.add(guiPanel, BorderLayout.CENTER);
    guiFrame.setVisible(true);

回答1:


By Default, JFrame has Borderlayout. BorderLayout have five flags. When you will not specify any flag, It will add you component to frame with center flag. Center flag give all space to component which is added with center flag, if no other flag is specified with component. for more information on border layout, visit following link: http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

You can add both by using following statement:

JFrame frame = new JFrame();

frame.add(new JPanel(), BorderLayout.NORTH);

frame.add(new JScrollpane(), BorderLayout.CENTER);



回答2:


GridBagLayout is not good for this situation. With lesser code you can get desired Code.

JPanel pnlButton = new JPanel(new FlowLayout(FlowLayout.CENTER));
pnlButton.add(button1);
pnlButton.add(button2);

JFrame frame = new JFrame();
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(pnlButton, BorderLayout.PAGE_END);

If you want to go only with Gridbaglayout. Then you will have to set weightX, weightY, gridwidth and other properties like that

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx=1.0;
gbc.weighy=1.0;
gbc.fill = GridBagConstraints.BOTH;
guiPanel.add(scrollPane, gbc);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE
guiPanel.add(buttons, gbc);        
guiFrame.add(guiPanel, BorderLayout.CENTER);
guiFrame.setVisible(true);

Please try and let me know, if it does not work, I will send complete code with GridBaglayout.



来源:https://stackoverflow.com/questions/16505239/add-a-jscrollpane-to-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!