Console.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package holeg.ui.view.component;
  2. import holeg.preferences.ImagePreference;
  3. import holeg.ui.view.image.Import;
  4. import java.awt.BorderLayout;
  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. *
  16. * @author tom
  17. */
  18. public class Console extends JPanel {
  19. private final JTextArea textArea = new JTextArea();
  20. public Console() {
  21. super();
  22. this.setLayout(new BorderLayout());
  23. textArea.setEditable(false);
  24. DefaultCaret caret = (DefaultCaret) textArea.getCaret();
  25. caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  26. JScrollPane scrollPane = new JScrollPane(textArea);
  27. this.add(scrollPane, BorderLayout.CENTER);
  28. JToolBar toolBar = new JToolBar();
  29. toolBar.setFloatable(false);
  30. JButton clearButton = new JButton("",
  31. new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Clear, 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("",
  37. new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Top, 24, 24)));
  38. topButton.setToolTipText("Scroll to top");
  39. topButton.addActionListener(actionEvent -> scrollToTop());
  40. toolBar.add(topButton);
  41. JButton botButton = new JButton("",
  42. new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Bottom, 24, 24)));
  43. botButton.setToolTipText("Scroll to bottom");
  44. botButton.addActionListener(actionEvent -> scrollToBottom());
  45. toolBar.add(botButton);
  46. scrollPane.setColumnHeaderView(toolBar);
  47. }
  48. private void scrollToTop() {
  49. textArea.setCaretPosition(0);
  50. }
  51. private void scrollToBottom() {
  52. textArea.setCaretPosition(textArea.getDocument().getLength());
  53. }
  54. public void clear() {
  55. textArea.setText("");
  56. }
  57. public void print(String message) {
  58. textArea.append(message);
  59. }
  60. public void println(String message) {
  61. textArea.append(message + "\n");
  62. }
  63. }