Jacob Fuchs
Jacob Fuchs

Reputation: 357

GUI & BorderLayout

I read the book Head First in Java and I cannot figure out why they are not shown correctly the items, vertically. The code is,

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);

}
}

Should I use GridLayout? There is other problem, which I do not understand?

Upvotes: 0

Views: 536

Answers (1)

badjr
badjr

Reputation: 2296

You could set the layout of panel to a BoxLayout, allowing the components to be aligned vertically:

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

Upvotes: 2

Related Questions