Console.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public class Console extends JPanel {
  17. private final JTextArea textArea = new JTextArea();
  18. public Console() {
  19. super();
  20. this.setLayout(new BorderLayout());
  21. textArea.setEditable(false);
  22. DefaultCaret caret = (DefaultCaret) textArea.getCaret();
  23. caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  24. JScrollPane scrollPane = new JScrollPane(textArea);
  25. this.add(scrollPane, BorderLayout.CENTER);
  26. JToolBar toolBar = new JToolBar();
  27. toolBar.setFloatable(false);
  28. JButton clearButton = new JButton("",
  29. new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Clear, 24, 24)));
  30. clearButton.setToolTipText("Clear Console");
  31. clearButton.addActionListener(actionEvent -> clear());
  32. toolBar.add(clearButton);
  33. toolBar.add(Box.createHorizontalGlue());
  34. JButton topButton = new JButton("",
  35. new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Top, 24, 24)));
  36. topButton.setToolTipText("Scroll to top");
  37. topButton.addActionListener(actionEvent -> scrollToTop());
  38. toolBar.add(topButton);
  39. JButton botButton = new JButton("",
  40. new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Bottom, 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. }