Console.java 2.0 KB

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