java - JScrollPane 组件不出现
问题描述
我试图将一些组件放入 aJScrollPane
但每次启动程序时它们都不会出现。我今天刚开始学习 GUI,所以我想我错过了一些小东西,但无论我在哪里上网,我都找不到答案。唯一出现的就是它JScrollPane
自己。
class MainFrame extends JFrame{
public MainFrame(String title){
//Main Frame Stuff
super(title);
setSize(655, 480);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
//Layout
FlowLayout flow = new FlowLayout();
setLayout(flow);
//Components
JButton spam_button = new JButton("Print");
JLabel label = new JLabel("What do you want to print?",
JLabel.LEFT);
JTextField user_input = new JTextField("Type Here", 20);
//Scroll Pane
JScrollPane scroll_pane = new JScrollPane(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll_pane.setPreferredSize(new Dimension(640, 390));
//Adding to Scroll
scroll_pane.add(label);
scroll_pane.add(user_input);
scroll_pane.add(spam_button);
//Adding to the Main Frame
add(scroll_pane);
//Visibility
setVisible(true);
}
}
该程序的重点是打印您键入的任何内容 100 次,但我还没有做到这一点,因为我一直被这个滚动问题所困扰。当我最终将内容显示在滚动窗格中时JPanel
,我会将这三个组件移动到滚动窗格上方,然后将 100 个单词添加到滚动窗格中,以便您可以滚动浏览它。
解决方案
我今天才开始学习 GUI
所以首先要从 Swing 教程开始。有大量的演示代码可供下载、测试和修改。
scroll_pane.add(label);
scroll_pane.add(user_input);
scroll_pane.add(spam_button);
JScrollPane 不像 JPanel:
- 您不会将组件直接添加到滚动面板。您将组件添加到
viewport
滚动窗格 - 只能将单个组件添加到视口。
所以你的代码应该是这样的:
JPanel panel = new JPanel();
panel.add(label);
panel.add(user_input);
panel.add(spam_button);
scrollPane.setViewportView( panel );
推荐阅读
- c++ - 如何在类构造函数中初始化 pthread_t 变量
- ios - swift中的never和void返回类型有什么区别吗?实际上,从不返回类型有什么用?
- python - 从终端调用时,uvicorn 不工作
- android - 将 androidx.viewpager2 添加到 android.mk 文件
- node.js - web socket 无法在 Safari 中使用 nodejs 读取 http 生成的 cookie
- opengl - 由于OpenGL可以执行内置的背面剔除,它必须计算顶点法线;可以访问这些而不是将它们作为属性发送吗?
- asp.net-web-api - 如何通过 web api c# 从邮递员的表单数据中将图像添加到数据库
- azure - 在 Azure VM 中为 tcp 启用端口
- c++ - “Make”因 Clang 错误而失败 - 如何从 Clang 中获取错误?
- .net - 将 WCF 服务托管为 AZURE 应用服务 VS2019