在下面的代码中,我已将JScrollPane
添加到通过JPanel
引用的帧中。但是,滚动条不会出现。代码有什么问题吗?
import java.awt.Component;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.tree.DefaultMutableTreeNode;
public class SampleSwing extends JFrame{
public static void main(String[] args) throws IOException{
new SampleSwing().go();
}
private void go() throws IOException {
JPanel a = new JPanel();
a.setLayout(new BoxLayout(a, BoxLayout.Y_AXIS));
JScrollPane pane1 = new JScrollPane(a);
pane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
pane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
getContentPane().add(pane1);
JButton but = new JButton("Hello");
but.setAlignmentX(Component.CENTER_ALIGNMENT);
a.add(but);
JEditorPane pane = new JEditorPane();
a.add(pane);
JComboBox list = new JComboBox(new String[]{"One", "Two"});
list.setAlignmentX(Component.CENTER_ALIGNMENT);
a.add(list);
DefaultMutableTreeNode node = new DefaultMutableTreeNode("One");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Two");
node.add(node1);
node1.add(new DefaultMutableTreeNode("Three"));
node1.add(new DefaultMutableTreeNode("Four"));
JTree tree = new JTree(node);
a.add(tree);
getContentPane().add(a);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
}
答案 0 :(得分:4)
您要将a及其JScrollPane添加到contentPane。不要因为添加了一个,你将它从滚动窗格中移除并覆盖滚动窗格。仅添加滚动窗格。