Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class Main extends JFrame {
    JPanel topPanel;
    JTextPane tPane;
    JTextField tfield = new JTextField();
    int counter = 0;
    Color[] colours = { Color.RED, Color.BLUE, };

    private void createAndDisplayGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tPane = new JTextPane();
        JScrollPane scroller = new JScrollPane();
        scroller.setViewportView(tPane);

        tfield.addActionListener(e -> {
            counter++;
            if (counter == 8)
                counter = 0;
            String text = tfield.getText() + "\n";
            appendToPane(tPane, text, colours[counter]);
            tfield.selectAll();
        });

        getContentPane().add(scroller, BorderLayout.CENTER);
        getContentPane().add(tfield, BorderLayout.PAGE_END);

        setSize(200, 100);
        setVisible(true);
        tfield.requestFocusInWindow();
        tfield.setText("hi enter to start");
    }

    private void appendToPane(JTextPane tp, String msg, Color c) {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
        aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.replaceSelection(msg);
    }

    public static void main(String... args) {
        new Main().createAndDisplayGUI();
    }
}