JFrame标题为文本文件标题

时间:2017-05-11 10:24:02

标签: java swing

我想知道如何将帧标题添加为用户选择的任何文本文件的名称。

例如,如果我选择文本文件名lab3LargeData.txt,那么框架标题将是lab3LargeData.txt。

到目前为止,这是我的整个代码。我添加了评论以使其可读。

package GUIdesign;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TextAnalyzer extends Frame implements ActionListener {

    // ------------------------------------------
    // Declare class variables that are accessible from all methods in the class
    // ------------------------------------------
    JFrame frame;
    JTextField textField;
    JButton button, button2;
    JLabel label;
    JButton fileButton;
    JFileChooser fc = new JFileChooser();
    JTextArea textArea = new JTextArea();

    public TextAnalyzer() {
        JFrame frame = new JFrame(); // constructor

        // ------------------------------------------
        // Create a panel (container) to hold our components
        // ------------------------------------------
        JPanel panel = new JPanel();
        panel.setBackground(Color.black);
        panel.setLayout(new BorderLayout());
        frame.getContentPane().add(panel);

        // ------------------------------------------
        // adding buttons
        // ------------------------------------------
        button = new JButton("Pick a file");
        button.setPreferredSize(new Dimension(100, 30));
        button.addActionListener(this);
        panel.add(button, BorderLayout.PAGE_START);

        // ------------------------------------------
        // creating a text area
        // ------------------------------------------
        textArea = new JTextArea();
        textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(false);
        panel.add(textArea);

        // ------------------------------------------
        // creating scroll
        // ------------------------------------------
        JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        panel.add(scroll, BorderLayout.CENTER);
        JPanel statusPanel = new JPanel();

        // ------------------------------------------
        // creating status bar (fix later with file title and file size)
        // ------------------------------------------
        statusPanel.setBorder((Border) new BevelBorder(BevelBorder.LOWERED));
        frame.add(statusPanel, BorderLayout.SOUTH);
        statusPanel.setPreferredSize(new Dimension(frame.getWidth(), 16));
        statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
        JLabel statusLabel = new JLabel("status");
        statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
        statusPanel.add(statusLabel);

        // ------------------------------------------
        // Setting up the frame
        // ------------------------------------------

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // ability to
                                                                // close frame
        frame.getContentPane().add(panel);
        frame.setSize(400, 300); // size of the frame
        frame.setVisible(true); // make the frame visible // everything must be
                                // done before this statement
        // frame.setTitle(); // title of the frame
        frame.setLocationRelativeTo(null);
    }

    public static void main(String args[]) {
        TextAnalyzer demo = new TextAnalyzer();
        System.out.println(demo);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        // ------------------------------------------
        // getting the text from text field
        // ------------------------------------------

        int returnVal = fc.showOpenDialog(frame);

        // ------------------------------------------
        // If file was really selected, do something with it
        // ------------------------------------------
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            // ------------------------------------------
            // Get the file the user selected
            // ------------------------------------------
            File file = fc.getSelectedFile();
            System.out.println("name of file" + file.getName());
            String name = file.getName();

            // ------------------------------------------
            // String builder
            // ------------------------------------------

            StringBuilder sb = new StringBuilder();
            // ------------------------------------------
            // Create a scanner to the file
            // ------------------------------------------

            Scanner input;
            try {
                input = new Scanner(file);

                // ------------------------------------------
                // read text from file
                // ------------------------------------------
                while (input.hasNext()) {
                    sb.append(input.nextLine());
                    sb.append("\n");
                }
                System.out.println(input);
                input.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            textArea.setText(sb.toString());
            // ------------------------------------------
            // Do something with the file path (display it, use it to open,
            // etc.)
            // ------------------------------------------
            System.out.println(file.getPath());

        } else {
            System.out.println("No file was selected");
        }

    }

}

我试过这样做,但我知道这是不正确的。只是用它来玩代码。

if (returnVal == JFileChooser.APPROVE_OPTION) {
        // ------------------------------------------
        // Get the file the user selected
        // ------------------------------------------
        File file = fc.getSelectedFile();
        System.out.println("name of file" + file.getName());
        String name = file.getName();
        frame.setTitle(name);// error right here

2 个答案:

答案 0 :(得分:4)

您的变量框架未初始化:您正在构造函数中初始化局部变量。

答案 1 :(得分:0)

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.Border;

     /**
     *
     * @author Salinda
     */

    public class TextAnalyzer extends JFrame implements ActionListener {

// ------------------------------------------
// Declare class variables that are accessible from all methods in the class
// ------------------------------------------

public JFrame myf;
JTextField textField;
JButton button, button2;
JLabel label;
JButton fileButton;
JFileChooser fc = new JFileChooser();
JTextArea textArea = new JTextArea();

public TextAnalyzer() {

   myf = new JFrame(); // constructor

    // ------------------------------------------
    // Create a panel (container) to hold our components
    // ------------------------------------------
    JPanel panel = new JPanel();
    panel.setBackground(Color.black);
    panel.setLayout(new BorderLayout());
    myf.getContentPane().add(panel);

    // ------------------------------------------
    // adding buttons
    // ------------------------------------------
    button = new JButton("Pick a file");
    button.setPreferredSize(new Dimension(100, 30));
    button.addActionListener(this);
    panel.add(button, BorderLayout.PAGE_START);

    // ------------------------------------------
    // creating a text area
    // ------------------------------------------
    textArea = new JTextArea();
    textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
    textArea.setEditable(false);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(false);
    panel.add(textArea);

    // ------------------------------------------
    // creating scroll
    // ------------------------------------------
    JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    panel.add(scroll, BorderLayout.CENTER);
    JPanel statusPanel = new JPanel();

    // ------------------------------------------
    // creating status bar (fix later with file title and file size)
    // ------------------------------------------
    statusPanel.setBorder((Border) new BevelBorder(BevelBorder.LOWERED));
    myf.add(statusPanel, BorderLayout.SOUTH);
    statusPanel.setPreferredSize(new Dimension(myf.getWidth(), 16));
    statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
    JLabel statusLabel = new JLabel("status");
    statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
    statusPanel.add(statusLabel);

    // ------------------------------------------
    // Setting up the frame
    // ------------------------------------------
    myf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // ability to
    // close frame
    myf.getContentPane().add(panel);
    myf.setSize(400, 300); // size of the frame
    myf.setVisible(true); // make the frame visible // everything must be

    myf.setLocationRelativeTo(null);
}

public static void main(String args[]) {
    TextAnalyzer demo = new TextAnalyzer();
    System.out.println(demo);
}

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    // ------------------------------------------
    // getting the text from text field
    // ------------------------------------------

    int returnVal = fc.showOpenDialog(this);

    // ------------------------------------------
    // If file was really selected, do something with it
    // ------------------------------------------
    if (returnVal == fc.APPROVE_OPTION) {
        // ------------------------------------------
        // Get the file the user selected
        // ------------------------------------------
        File file = fc.getSelectedFile();
        System.out.println("name of file" + file.getName());
        String name = file.getName();

       myf.setTitle(name.toLowerCase());


        // ------------------------------------------
        // String builder
        // ------------------------------------------
        StringBuilder sb = new StringBuilder();
        // ------------------------------------------
        // Create a scanner to the file
        // ------------------------------------------

        Scanner input;
        try {
            input = new Scanner(file);

            // ------------------------------------------
            // read text from file
            // ------------------------------------------
            while (input.hasNext()) {
                sb.append(input.nextLine());
                sb.append("\n");
            }
            System.out.println(input);
            input.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        textArea.setText(sb.toString());
        // ------------------------------------------
        // Do something with the file path (display it, use it to open,
        // etc.)
        // ------------------------------------------
        System.out.println(file.getPath());

    } else {
        System.out.println("No file was selected");
    }

}

    }