package net.knarcraft.serverlauncher.userinterface; import net.knarcraft.serverlauncher.profile.Profile; import javax.swing.*; import javax.swing.text.DefaultCaret; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import static javax.swing.text.DefaultCaret.ALWAYS_UPDATE; /** * Acts as a single writable/readable tab * Has a box for user input, and a textArea for server output. * * @author Kristian Knarvik * @version 1.0.0 * @since 1.0.0 */ public class Console implements ActionListener, KeyListener { private final JTextField textInput; private final JTextArea textOutput; private final String name; private final JPanel panel; private final ArrayList commands = new ArrayList<>(); private int commandIndex; Console(JTabbedPane tab, String name) { this.name = name; panel = new JPanel(); tab.addTab(name, null, panel, null); panel.setLayout(new BorderLayout(0, 0)); textInput = new JTextField(); panel.add(textInput, BorderLayout.SOUTH); textInput.setColumns(10); textInput.addActionListener(this); textOutput = new JTextArea(); JScrollPane scroll = new JScrollPane(textOutput); panel.add(scroll, BorderLayout.CENTER); textOutput.setEditable(false); DefaultCaret caret = (DefaultCaret) textOutput.getCaret(); caret.setUpdatePolicy(ALWAYS_UPDATE); textOutput.setLineWrap(true); textInput.addKeyListener(this); } public JPanel getPanel() { return this.panel; } /** * Prints a string to the textArea. * * @param text The text to print */ public void output(String text) { this.textOutput.setText(this.textOutput.getText() + "\n" + text); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == textInput) { //Sends the command from the input to the server with the same name. java.lang.String text = textInput.getText(); Profile.getCurrent().sendCommand(this.name, text); commands.add(text); if (commands.size() > 25) { commands.remove(0); } commandIndex = commands.size(); textInput.setText(""); } } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { if (commands.size() > 0 && commandIndex > 0) { textInput.setText(commands.get(--commandIndex)); } } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { if (commands.size() > 0) { if (commandIndex == commands.size() - 1) { commandIndex++; textInput.setText(""); } else if (commandIndex >= 0 && commandIndex <= commands.size() - 1) { textInput.setText(commands.get(++commandIndex)); } } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }