Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Component;
import java.awt.Container;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JButton button = new JButton("Click me");
        button.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "save.dat"));
            final JTextField textField = getTexField(chooser);
            if (textField == null) {
                return;
            }
            String text = textField.getText();
            if (text == null) {
                return;
            }
            int index = text.lastIndexOf('.');
            if (index == -1) {
                return;
            }
            textField.setSelectionStart(0);
            textField.setSelectionEnd(index);

            chooser.showSaveDialog(button);

        });
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }

    private static JTextField getTexField(Container container) {
        for (int i = 0; i < container.getComponentCount(); i++) {
            Component child = container.getComponent(i);
            if (child instanceof JTextField) {
                return (JTextField) child;
            } else if (child instanceof Container) {
                JTextField field = getTexField((Container) child);
                if (field != null) {
                    return field;
                }
            }
        }
        return null;
    }
}