GUI& BorderLayout的

时间:2017-02-11 20:57:24

标签: java swing layout-manager border-layout

我在Java中阅读了Head First这本书,我无法弄清楚为什么他们没有正确显示这些项目。代码是,

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class QuizCardBuilder {

  private JTextArea question;
  private JTextArea answer;
  private JFrame frame;

public static void main(String[] args) {
    QuizCardBuilder card = new QuizCardBuilder();
    card.go();
}

public void go(){
    frame = new JFrame("Quiz Card Builder");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel =new JPanel();


    question = new JTextArea(10,20);
    question.setLineWrap(true);
    question.setWrapStyleWord(true);
    question.setFont(new Font("Serif", Font.ITALIC, 16));

    JScrollPane scrollPane = new JScrollPane(question);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    answer = new JTextArea(10,20);
    answer.setLineWrap(true);
    answer.setWrapStyleWord(true);
    answer.setFont(new Font("Calibri", Font.BOLD, 21));

    JScrollPane qScroll = new JScrollPane(answer);
    qScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    qScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    JButton nextBtn = new JButton("Next Card");

    JLabel qLabel = new JLabel("Question:");
    JLabel aLabel = new JLabel("Answer:");

    panel.add(qLabel);
    panel.add(scrollPane);
    panel.add(aLabel);
    panel.add(qScroll);
    panel.add(nextBtn);

    JMenuBar menuBar=new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenuItem newMenuItem = new JMenuItem("New");
    JMenuItem saveMenuItem = new JMenuItem("Save");

    fileMenu.add(newMenuItem);
    fileMenu.add(saveMenuItem);
    menuBar.add(fileMenu);
    frame.setJMenuBar(menuBar); 
    frame.getContentPane().add(panel, BorderLayout.CENTER);
    frame.setSize(500, 600);
    frame.setVisible(true);

}
}

我应该使用GridLayout吗?还有其他问题,我不明白?

1 个答案:

答案 0 :(得分:2)

您可以将panel的布局设置为BoxLayout,允许组件垂直对齐:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));