簡體   English   中英

為什么我在運行程序時無法檢索按鈕?

[英]Why can't I retrieve my buttons when I run my program?

因此,我的程序是用戶在運行時添加按鈕。 當他/她單擊“保存”按鈕時,程序將保存到文件中。 但是當我再次運行它時,按鈕消失了。 我嘗試使用XMLEncoder和XMLDecoder序列化按鈕,但是當我運行程序時,它沒有保存任何內容,因此又重新開始了。 如何正確序列化它,以便在啟動程序時出現按鈕? 任何幫助,將不勝感激。
這是我的代碼片段:

   public class saveButton
   {
   //JFrame and JPanels have been declared earlier

   class ClickListener implements ActionListener
   {
       public void actionPerformed(ActionEvent e)
       {
           str = JOptionPane.showInputDialog("What is the name of the new button?"); 
           JButton b = new JButton(str);
           frame.add(b);
           try
           {
               XMLEncoder encdr = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.ser")));
               encdr.writeObject(new JButton(str));
               encdr.close();
           }
           catch (IOException e)
           {
               e.printStackTrace();
           }
       }
   }

   ActionListener addButtonClicked = new ClickListener();
   b.addActionListener(addButtonClicked);

   class ClickListenerTwo implements ActionListener
   {
       public void actionPerformed(ActionEvent f)
       {
           try
           {
               XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("file.ser")));
               Object result = d.readObject();
               d.close();
           }
           catch (IOException decoder)
           {
               decoder.printStackTrace();
           }
       }

   } 

解碼對象后,需要適當地投射對象,然后將組件添加到容器中。

這是一個非常基本的示例,每次您單擊“ 隨機”按鈕時,都會在面板上生成隨機數量的按鈕。 單擊“ 保存”時 ,面板將保存到磁盤,而單擊“ 加載”時 ,它將從磁盤加載面板並將其重新應用到容器中

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private RandomButtonPane pane;

        public TestPane() {
            setLayout(new BorderLayout());

            JPanel actions = new JPanel();

            JButton random = new JButton("Random");
            JButton save = new JButton("Save");
            JButton load = new JButton("Load");

            actions.add(random);
            actions.add(save);
            actions.add(load);

            add(actions, BorderLayout.SOUTH);

            random.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (pane != null) {
                        remove(pane);
                    }

                    pane = new RandomButtonPane();
                    pane.randomise();
                    add(pane);

                    Window window = SwingUtilities.windowForComponent(TestPane.this);
                    window.pack();
                    window.setLocationRelativeTo(null);
                }
            });

            save.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (pane != null) {
                        try (OutputStream os = new FileOutputStream(new File("Save.dat"))) {
                            try (XMLEncoder encoder = new XMLEncoder(os)) {
                                encoder.writeObject(pane);
                                remove(pane);
                                pane = null;
                            }
                        } catch (IOException exp) {
                            exp.printStackTrace();
                        }
                    }
                }
            });

            load.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (pane != null) {
                        remove(pane);
                        pane = null;
                    }

                    try (InputStream is = new FileInputStream(new File("Save.dat"))) {
                        try (XMLDecoder decoder = new XMLDecoder(is)) {
                            Object value = decoder.readObject();
                            if (value instanceof RandomButtonPane) {
                                pane = (RandomButtonPane)value;
                                pane.revalidate();
                                add(pane);
                            }
                        }
                    } catch (IOException exp) {
                        exp.printStackTrace();
                    }
                    Window window = SwingUtilities.windowForComponent(TestPane.this);
                    window.pack();
                    window.setLocationRelativeTo(null);
                }
            });
        }

    }

    public static class RandomButtonPane extends JPanel {

        public RandomButtonPane() {
            setLayout(new GridBagLayout());
        }

        public void randomise() {
            int count = ((int) (Math.random() * 100)) + 1;
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            for (int index = 0; index < count; index++) {
                if (index % 10 == 0) {
                    gbc.gridx = 0;
                    gbc.gridy++;
                }
                add(new JButton(Integer.toString(index)), gbc);
                gbc.gridx++;
            }
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM