我想把一些组件放在一个叫 "T "的东西里面。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个单词添加到滚动窗格中,这样你就可以在滚动窗格中滚动了。
我今天刚开始学习GUIs
所以首先要从 摇摆教程. 有大量的演示代码可以下载并测试和修改。
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 );