在Java Swing中,当我将JScrollPane添加到我的面板时,没有任何内容出现



在后端使用Java工作了几年后,我最终在一个构建GUI的项目中工作,Java Swing让我发疯。

所以我正在用JScrollPane做一些测试,因为我有一个太大而无法放入屏幕的JPanel。在下面的示例中,我将几个按钮添加到 JPanel,然后使用 JPanel 创建一个 JScrollPane,但屏幕中没有显示任何内容。

import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestScrollPane extends JDialog {
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
TestScrollPane dialog = new TestScrollPane();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public TestScrollPane() {
setBounds(100, 100, 857, 541);
getContentPane().setLayout(null);
{
JPanel panel = new JPanel();
panel.setBounds(131, 167, 141, 221);
getContentPane().add(panel);
panel.setLayout(null);
{
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(0, 0, 115, 29);
panel.add(btnNewButton);
}
{
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(26, 192, 115, 29);
panel.add(btnNewButton_1);
}
JScrollPane jsp = new JScrollPane(panel);
getContentPane().add(jsp);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setBounds(0, 446, 835, 39);
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}       
}
}

我不明白为什么没有出现。我创建JPanel,添加按钮,以及JScrollPane,我添加到窗口中。我正在使用WindwBuilder Pro,这就是为什么代码看起来如此奇怪。

谢谢。

我已经改变了

getContentPane().setLayout(null);
panel.setLayout(null);

getContentPane().setLayout(new FlowLayout());
panel.setLayout(new FlowLayout());

现在我看到所有 4 个按钮。

如果不使用布局管理器,即使用setLayout(null)时,面板的组件必须由代码布局。大多数组件从维度 0 开始,因此不会显示。

在上面的代码中,缺少滚动窗格的位置和尺寸:jsp.setBounds(...)就像其他组件一样。

通常不建议自己布置组件,最好使用LayoutManager(例如GridBagLayout,BorderLayout,...(。

请参阅 Oracle 的教程:课程:在容器中布置组件

相关内容

最新更新