Console.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package holeg.ui.view.component;
  2. import java.awt.BorderLayout;
  3. import javax.swing.Box;
  4. import javax.swing.ImageIcon;
  5. import javax.swing.JButton;
  6. import javax.swing.JPanel;
  7. import javax.swing.JScrollPane;
  8. import javax.swing.JTextArea;
  9. import javax.swing.JToolBar;
  10. import javax.swing.text.DefaultCaret;
  11. import holeg.preferences.ImagePreference;
  12. import holeg.utility.image.Import;
  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(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("", new ImageIcon(Import.loadImage(ImagePreference.Button.Console.Top, 24, 24)));
  37. topButton.setToolTipText("Scroll to top");
  38. topButton.addActionListener(actionEvent -> scrollToTop());
  39. toolBar.add(topButton);
  40. JButton botButton = new JButton("", 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. }