LabelSampleSaveText.java Source code

Java tutorial

Introduction

Here is the source code for LabelSampleSaveText.java

Source

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.io.FileWriter;
import java.io.IOException;

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

public class LabelSampleSaveText {
    public static void main(String args[]) {
        JFrame frame = new JFrame("Label Focus Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        JLabel label = new JLabel("Name: ");
        label.setDisplayedMnemonic(KeyEvent.VK_N);
        JTextField textField = new JTextField();
        label.setLabelFor(textField);
        panel.add(label, BorderLayout.WEST);
        panel.add(textField, BorderLayout.CENTER);
        frame.add(panel, BorderLayout.NORTH);
        frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
        frame.setSize(250, 150);
        frame.setVisible(true);

        textField.setText("your text");
        String filename = "test.txt";

        FileWriter writer = null;
        try {
            writer = new FileWriter(filename);
            textField.write(writer);
        } catch (IOException exception) {
            System.err.println("Save oops");
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException exception) {
                    System.err.println("Error closing writer");
                    exception.printStackTrace();
                }
            }
        }
    }
}