我有一个指定了 FlowLayout 的面板,其中充满了标签、文本字段和文本区域。框架不是那么宽,但是由于内部的所有组件,面板变得很高。我想将面板添加到 JScrollPane,这样我就可以在面板中垂直滚动。但是,当我将面板添加到滚动窗格并将滚动窗格添加到框架时,所有组件都彼此相邻并且水平滚动通过它们。这是代码:
public class Form {
JTextField jtfName = new JTextField(15);
JTextField jtfTitle = new JTextField(15);
JTextField jtfAuthor = new JTextField(15);
JTextArea jtaSetting = new JTextArea(5, 15);
JTextArea jtaMainChars = new JTextArea(5, 15);
JTextArea jtaConflict = new JTextArea(5, 15);
JTextArea jtaQuote = new JTextArea(5, 15);
JTextArea jtaMainCharShows = new JTextArea(5, 15);
JPanel jpnlName = new JPanel();
JPanel jpnlTitle = new JPanel();
JPanel jpnlAuthor = new JPanel();
Form() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Organizer");
jfrm.setLayout(new GridLayout(0,1));
// Give the frame an initial size.
jfrm.setSize(300, 300);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a panel.
JPanel jpnl = new JPanel();
// Create labels.
JLabel jlabName = new JLabel("Student Name:");
JLabel jlabTitle = new JLabel("Title:");
JLabel jlabAuthor = new JLabel("Author:");
JLabel jlabSetting = new JLabel("Setting (Time and Place):");
jlabSetting.setHorizontalAlignment(SwingUtilities.CENTER);
JLabel jlabMainChars = new JLabel("Main Characters:");
jlabMainChars.setHorizontalAlignment(SwingUtilities.CENTER);
JLabel jlabConflict = new JLabel("<html>Describe the major conflict of the<br>story in one well-written sentence:");
jlabConflict.setHorizontalAlignment(SwingUtilities.CENTER);
JLabel jlabQuote = new JLabel("<html>Find and write down a passage (quote<br>from the book that reveals a significant<br>personality trait of one of the main characters<br>and GIVE THE PAGE #:");
jlabQuote.setHorizontalAlignment(SwingUtilities.CENTER);
JLabel jlabMainCharShows = new JLabel("<html>Explain in your own words what the<br>passage (quote) shows about the main character.");
jlabMainCharShows.setHorizontalAlignment(SwingUtilities.CENTER);
// Add text fields to panel.
jpnlName.add(jlabName);
jpnlName.add(jtfName);
jpnlTitle.add(jlabTitle);
jpnlTitle.add(jtfTitle);
jpnlAuthor.add(jlabAuthor);
jpnlAuthor.add(jtfAuthor);
// Add components to main panel.
jpnl.add(jpnlName);
jpnl.add(jpnlTitle);
jpnl.add(jpnlAuthor);
jpnl.add(jlabSetting);
jpnl.add(jtaSetting);
jpnl.add(jlabMainChars);
jpnl.add(jtaMainChars);
jpnl.add(jlabConflict);
jpnl.add(jtaConflict);
jpnl.add(jlabQuote);
jpnl.add(jtaQuote);
jpnl.add(jlabMainCharShows);
jpnl.add(jtaMainCharShows);
// Add the panel to a scroll pane.
JScrollPane jspPanel = new JScrollPane(jpnl);
// Add the scroll pane to the frame.
jfrm.getContentPane().add(jspPanel);
// Display the frame.
jfrm.setVisible(true);
}
}