Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.FontMetrics;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 300);

        JPanel panel = new JPanel(new GridLayout(3, 1));
        JLabel label = new JLabel();
        JTextField tf = new JTextField();
        JButton b = new JButton("calc sting width");
        b.addActionListener(e -> {
            FontMetrics fm = label.getFontMetrics(label.getFont());
            String text = tf.getText();
            int textWidth = fm.stringWidth(text);
            label.setText("text width for \"" + text + "\": " + textWidth);
        });
        panel.add(label);
        panel.add(tf);
        panel.add(b);
        frame.setContentPane(panel);
        frame.setVisible(true);
    }

}