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 java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.LineBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
    static JTextPane textPane = new JTextPane();
    static int size = 20;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new AbstractAction("Update") {
            @Override
            public void actionPerformed(ActionEvent ae) {

                StyledDocument doc = (StyledDocument) textPane.getDocument();
                SimpleAttributeSet style = new SimpleAttributeSet();
                StyleConstants.setFontFamily(style, "Serif");
                StyleConstants.setFontSize(style, size++);
                try {
                    doc.insertString(doc.getLength(), " one two three", style);
                    Dimension d = textPane.getPreferredSize();
                    Rectangle r = textPane.modelToView(textPane.getDocument().getLength());
                    d.height = r.y + r.height;
                    textPane.setPreferredSize(d);
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
                frame.pack();
            }

        }));
        frame.add(buttonPanel, BorderLayout.NORTH);
        textPane.setText("this is a test.");
        textPane.setBorder(new LineBorder(Color.BLACK));

        frame.add(new JScrollPane(textPane));
        frame.pack();
        frame.setVisible(true);
    }
}