Console.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package ui.view;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.FlowLayout;
  5. import javax.swing.Box;
  6. import javax.swing.ImageIcon;
  7. import javax.swing.JButton;
  8. import javax.swing.JPanel;
  9. import javax.swing.JScrollPane;
  10. import javax.swing.JTextArea;
  11. import javax.swing.JToolBar;
  12. import javax.swing.text.DefaultCaret;
  13. import utility.Util;
  14. /**
  15. * Little new swing object to print data to a console.
  16. * @author tom
  17. *
  18. */
  19. public class Console extends JPanel {
  20. private JTextArea textArea = new JTextArea();
  21. private JScrollPane scrollPane;
  22. public Console() {
  23. super();
  24. this.setLayout(new BorderLayout());
  25. textArea.setEditable(false);
  26. DefaultCaret caret = (DefaultCaret)textArea.getCaret();
  27. caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  28. scrollPane = new JScrollPane(textArea);
  29. this.add(scrollPane, BorderLayout.CENTER);
  30. JToolBar toolBar = new JToolBar();
  31. toolBar.setFloatable(false);
  32. JButton clearButton = new JButton("", new ImageIcon(Util.loadImage("/Button_Images/Clear.png", 24, 24)));
  33. clearButton.setToolTipText("Clear Console");
  34. clearButton.addActionListener(actionEvent -> clear());
  35. toolBar.add(clearButton);
  36. toolBar.add(Box.createHorizontalGlue());
  37. JButton topButton = new JButton("", new ImageIcon(Util.loadImage("/Button_Images/Top.png", 24, 24)));
  38. topButton.setToolTipText("Scroll to top");
  39. topButton.addActionListener(actionEvent -> scrollToTop());
  40. toolBar.add(topButton);
  41. JButton botButton = new JButton("", new ImageIcon(Util.loadImage("/Button_Images/Bottom.png", 24, 24)));
  42. botButton.setToolTipText("Scroll to bottom");
  43. botButton.addActionListener(actionEvent -> scrollToBottom());
  44. toolBar.add(botButton);
  45. scrollPane.setColumnHeaderView(toolBar);
  46. }
  47. private void scrollToTop() {
  48. textArea.setCaretPosition(0);
  49. }
  50. private void scrollToBottom() {
  51. textArea.setCaretPosition(textArea.getDocument().getLength());
  52. }
  53. public void clear() {
  54. textArea.setText("");
  55. }
  56. public void print(String message) {
  57. textArea.append(message);
  58. }
  59. public void println(String message) {
  60. textArea.append(message + "\n");
  61. }
  62. }