如何在Java应用程序关闭时更改jButton文本并保存?

时间:2015-03-21 12:27:08

标签: java netbeans jbutton

如何在Java应用程序关闭时更改jButton文本并保存?

我想在运行时更改jButton的名称,然后保存这些新值以备将来使用,是否可能?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以尝试在单击按钮对象后对其进行序列化,然后插入代码(在main方法中)以初始化序列化文件中的按钮。我修改了一些代码来说明这一点。希望能帮助到你!

import javax.swing.*;
import java.awt.*;

import java.io.*;
import java.nio.file.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class ButtonFrame extends JFrame 
{
    public static JButton bChange ; //button that appears in window
    public static JTextField bText ; //text field that appears in window

    // constructor for ButtonFrame
    ButtonFrame(String title, JButton button) 
    {
        super( title );                     // invoke the JFrame constructor
        setLayout( new FlowLayout() );      // set the layout manager

        //initialize textfield
        bText = new JTextField(40);
        bText.setText("place new button name here and click button");
        add(bText);

        //initialize button in window with text from file
        bChange = new JButton(button.getText()); 
        add( bChange );            

        //add event listener to button to change text of button in window
        bChange.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                bChange.setText(bText.getText());


                //save the new button text to file
                try {
                    FileOutputStream fileOut =
                            new FileOutputStream("button.ser");
                    ObjectOutputStream out = new ObjectOutputStream(fileOut);
                    out.writeObject(bChange);
                    out.close();
                    fileOut.close();
                } catch(Exception ex){

                }
            }
        });
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 
    }
}

public class ButtonDemo 
{
public static JButton jB = null;

    public static void main ( String[] args )
    {
        try
        {
            //check serialized file exists
            Path path = Paths.get("button.ser");

            if (Files.notExists(path)) {
                //create file
                FileOutputStream fileOut =
                    new FileOutputStream("button.ser");
                ObjectOutputStream out = new ObjectOutputStream(fileOut);
                out.writeObject(new JButton("Click Me!"));
                out.close();
                fileOut.close();
            }

            //initailize button from file 
            FileInputStream fileIn = new FileInputStream("button.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            jB = (JButton) in.readObject();
            in.close();
            fileIn.close();
        }catch(Exception i)
        {
        }
        ButtonFrame frm = new ButtonFrame("Button Demo", jB);

        frm.setSize( 400, 200 );     
        frm.setVisible( true );   
    }
}