I am trying to make a JTextArea vertically scrollable. I did some research and I'm pretty sure I'm using a LayoutManager, not adding JTextArea directly to the parent panel, and is setting the preferred size of both JTextArea and JScrollPane. Not sure what am I missing here... Here's the code:
public class ConsolePane extends JDialog {
private static final long serialVersionUID = -5034705087218383053L;
public static final Dimension CONSOLE_DIALOG_SIZE = new Dimension(400, 445);
public static final Dimension CONSOLE_LOG_SIZE = new Dimension(400, 400);
public static final Dimension CONSOLE_INPUT_SIZE = new Dimension(400, 25);
private static ConsolePane instance = new ConsolePane();
public static ConsolePane getInstance() {
return instance;
}
private JTextArea taLog;
private JTextField tfInput;
public ConsolePane() {
this.setTitle("Console");
JPanel contentPane = new JPanel();
this.setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
contentPane.add(createConsoleLog(), BorderLayout.CENTER);
contentPane.add(createConsoleInput(), BorderLayout.SOUTH);
contentPane.setPreferredSize(CONSOLE_DIALOG_SIZE);
}
private JComponent createConsoleLog() {
taLog = new JTextArea();
taLog.setLineWrap(true);
taLog.setPreferredSize(CONSOLE_LOG_SIZE);
((DefaultCaret) taLog.getCaret())
.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane container = new JScrollPane(taLog);
container
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
container
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
container.setPreferredSize(CONSOLE_LOG_SIZE);
return container;
}
private JComponent createConsoleInput() {
tfInput = new JTextField();
tfInput.setPreferredSize(CONSOLE_INPUT_SIZE);
tfInput.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
taLog.append(tfInput.getText() + "\r\n");
tfInput.setText("");
}
});
tfInput.requestFocus();
return tfInput;
}
public static void main(String[] args) {
ConsolePane.getInstance().pack();
ConsolePane.getInstance().setVisible(true);
}
}
Thx in advance!