JScrollPane 组件不出现
JScrollPane components do not appear
我试图将一些组件放入 JScrollPane
但每次我启动我的程序时它们都不会出现。我今天才开始学习 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 个单词添加到滚动窗格,以便您可以滚动浏览它。
I just started learning about GUIs today
所以首先要从 Swing tutorial 开始。有大量的demo代码可以下载测试修改。
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 );
我试图将一些组件放入 JScrollPane
但每次我启动我的程序时它们都不会出现。我今天才开始学习 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 个单词添加到滚动窗格,以便您可以滚动浏览它。
I just started learning about GUIs today
所以首先要从 Swing tutorial 开始。有大量的demo代码可以下载测试修改。
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 );