4

次のコードを見てください

WizardPanel.java

package wizardGUI;

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

public class WizardPanel extends JDialog
{
    private JPanel cardPanel, buttonPanel;
    private JButton next,previous;
    private CardLayout c1;

    private FileSelector fileSelector;
    private DelemeterSelector delemeterSelector;

    private int count = 1;

    public WizardPanel()
    {
        //Intializing instance variables
        fileSelector = FileSelector.getInstance();
        delemeterSelector = DelemeterSelector.getInstance();

        cardPanel = new JPanel();
        c1 = new CardLayout();
        cardPanel.setLayout(c1);

        cardPanel.add(fileSelector,"1");
        cardPanel.add(delemeterSelector,"2");

        c1.show(cardPanel, "1");;


        buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        next = new JButton("Next");
        next.addActionListener(new NextButtonAction());
        previous = new JButton("Previous");

        buttonPanel.add(next);
        buttonPanel.add(previous);

        //Creating the GUI
        this.setLayout(new BorderLayout());
        this.add(cardPanel,"Center");
        this.add(buttonPanel,"South");

        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setResizable(true);
        this.pack();
        this.setVisible(true);

    }

    private class NextButtonAction implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {

                c1.show(cardPanel, "2");

        }
    }
}

FileSelector.java

package wizardGUI;

/*This is the first panel is wazard GUI. Using this window user can select the correct file
  which contains the data required to create the table
 */

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

public class FileSelector extends JPanel
{
    private JLabel fileName, description;
    private JTextField fileTxt;
    private JButton browse;

    private GridBagLayout gbl;
    private GridBagConstraints gbc;

    private static FileSelector instance = null;

    private FileSelector()
    {
        //Intializing instance variables
        fileName = new JLabel("File Name: ");
        description = new JLabel("Specify the source of the data");

        fileTxt = new JTextField(10);

        browse = new JButton("Browse");

        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        //Creating GUI
        this.setLayout(gbl);

        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.weightx = 0.0;
        gbc.weighty = 0.0;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(description,gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(0,10,0,0);
        this.add(locationPanel(),gbc);

        this.setBorder(BorderFactory.createEmptyBorder());
    }

    private JPanel locationPanel()
    {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        panel.add(fileName);
        panel.add(fileTxt);
        panel.add(browse);

        return panel;
    }

    public static FileSelector getInstance()
    {
        if(instance==null)
        {
            instance = new FileSelector();
        }

        return instance;
    }
}

DelemeterSelector.java

/*This is the second windows in wizard
This class is designed to let the user to select the delemeter to break information */

package wizardGUI;

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

public class DelemeterSelector extends JPanel
{
    private JLabel description;
    private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn;
    private JTextArea txtArea;
    private JScrollPane scroll;
    private ButtonGroup btnGroup;

    private GridBagLayout gbl;
    private GridBagConstraints gbc;

    private static DelemeterSelector instance = null;

    private DelemeterSelector()
    {
        //Initializing instance variables
        description = new JLabel("What delemeter separates your fields? Select the appropreiate delemeter");

        tabBtn = new JRadioButton("Tab");
        semicolanBtn = new JRadioButton("Semicolan");
        commaBtn = new JRadioButton("Comma");
        spaceBtn = new JRadioButton("Space");

        btnGroup = new ButtonGroup();
        btnGroup.add(tabBtn);
        btnGroup.add(semicolanBtn);
        btnGroup.add(commaBtn);
        btnGroup.add(spaceBtn);

        txtArea = new JTextArea(20,70);

        scroll = new JScrollPane(txtArea);

        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        this.setLayout(gbl);

        //Creating the GUI
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(20,0,0,0);
        this.add(description,gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(20,0,0,0);
        this.add(radioPanel(),gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.insets = new Insets(10,0,0,0);
        gbc.fill = GridBagConstraints.BOTH;
        this.add(scroll,gbc);
    }

    private JPanel radioPanel()
    {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        panel.add(tabBtn);
        panel.add(semicolanBtn);
        panel.add(commaBtn);
        panel.add(spaceBtn);

        panel.setBorder(BorderFactory.createTitledBorder("Choose the Delimeter that seperates your fields"));

        return panel;
    }

    public static DelemeterSelector getInstance()
    {
        if(instance == null)
        {
            instance = new DelemeterSelector();
        }

        return instance;
    }
}

Main.java

package wizardGUI

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

    public class Main extends JFrame
    {
        public Main()
        {
            new WizardPanel().setVisible(true);
        }

        public static void main(String[]args)
        {
            try
            {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                new Main();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }

ここでは、「次へ」と「前へ」の 2 つのボタンしかなく、「WizardPanel」の「南」に表示され、他の JPanel が中央にあるため、すべての JPanel に共通です。

では、「FileSelector」を見てみましょう。参照ボタンを使用してファイルを選択したと思います。

この情報を次のパネルに送信するにはどうすればよいでしょうか。これは「DelemeterSelector」を意味しますか?. 別のクラスにある「次へ」と「前へ」の 2 つの「共通」ボタンしかありません。その「次へ」または「前へ」ボタンのactionListener内にビジネスロジック(「FileSelector」から選択されたファイルを取得して「DelemeterSelector」に送信する)を書くことは良い考えではないと思います。別のクラスにアクセスしてデータを取得し、次の JPanel (次のクラス) に送信する必要があるためです。より多くの JPanel が存在するため、これは非常に難しく、確実に失敗します。

一般的なものではなく、すべての JPanel に「次へ」および「前へ」ボタンを追加することを考えました。しかし、CardLayout への参照が欠落しているため、問題はあるパネルから別のパネルに移動しています。

このウィザードで、あるクラスから別のクラスにデータを渡す正確で効率的な方法を見つけるのを手伝ってください。ありがとう。

PS:

「次へ」ボタンのアクションクラスで条件チェックを行いたくなく、すべてのアクションを保持させます。例については、次のサンプル コード スニペットを参照してください。

//NON TESTED, NON COMPILED EXAMPLE CODE.
private class NextButtonAction implements ActionListener
{
         public void actionPerformed(ActionEvent ae)
         {

              if(fileSelector.isVisible(true))
              {
                  //Access FileSelector
                  // Get the Data
                  // send data into delemeter class
               }
               else if(delemeterSelector.isVisible(true))
               {
                  //Access delemeterSelector
                  // Get the Data
                  // send data into other class
               }
                else if(SOME_OTHER_CLASS.isVisible(true))
               {
                  //Access delemeterSelector
                  // Get the Data
                  // send data into other class
               }
       }
}
4

1 に答える 1

5

昼休みが終わったので、サンプルコードを投稿するだけですが、一日の終わりまでに説明するために戻ってきます。

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;

public class MainGui {
   public MainGui() {
      new WizardPanel().setVisible(true);
   }

   public static void main(String[] args) {
      try {
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         new MainGui();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

class WizardPanel extends JDialog {
   private JPanel cardPanel, buttonPanel;
   private JButton next, previous;
   private CardLayout c1;
   private SimpleModel simpleModel = new SimpleModel();

   private FileSelector fileSelector;
   private DelemeterSelector delemeterSelector;

   private int count = 1;

   public WizardPanel() {
      fileSelector = FileSelector.getInstance();
      delemeterSelector = DelemeterSelector.getInstance();

      fileSelector.setModel(simpleModel); //!!
      delemeterSelector.setModel(simpleModel); //!!

      cardPanel = new JPanel();
      c1 = new CardLayout();
      cardPanel.setLayout(c1);

      cardPanel.add(fileSelector, "1");
      cardPanel.add(delemeterSelector, "2");

      c1.show(cardPanel, "1");

      buttonPanel = new JPanel();
      buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

      next = new JButton("Next");
      next.addActionListener(new NextButtonAction());
      previous = new JButton("Previous");

      buttonPanel.add(next);
      buttonPanel.add(previous);

      // Creating the GUI
      this.setLayout(new BorderLayout());
      this.add(cardPanel, "Center");
      this.add(buttonPanel, "South");

      this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      this.setResizable(true);
      this.pack();
      this.setVisible(true);

   }

   private class NextButtonAction implements ActionListener {
      public void actionPerformed(ActionEvent ae) {

         // c1.show(cardPanel, "2");
         c1.next(cardPanel); //!!

      }
   }
}

class FileSelector extends JPanel {
   private JLabel fileName, description;
   private JTextField fileTxt;
   private JButton browse;

   private GridBagLayout gbl;
   private GridBagConstraints gbc;
   private SimpleModel simpleModel;

   private static FileSelector instance = null;

   private FileSelector() {
      // Intializing instance variables
      fileName = new JLabel("File Name: ");
      description = new JLabel("Specify the source of the data");

      fileTxt = new JTextField(10);

      browse = new JButton("Browse");
      browse.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            if (simpleModel != null) {
               simpleModel.setFileText(fileTxt.getText());
            }
         }
      });

      gbl = new GridBagLayout();
      gbc = new GridBagConstraints();

      // Creating GUI
      this.setLayout(gbl);

      gbc.gridx = 1;
      gbc.gridy = 1;
      gbc.weightx = 0.0;
      gbc.weighty = 0.0;
      gbc.fill = GridBagConstraints.BOTH;
      this.add(description, gbc);

      gbc.gridx = 1;
      gbc.gridy = 2;
      gbc.weightx = 1.0;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.insets = new Insets(0, 10, 0, 0);
      this.add(locationPanel(), gbc);

      this.setBorder(BorderFactory.createEmptyBorder());
   }

   public void setModel(SimpleModel simpleModel) {
      this.simpleModel = simpleModel;
   }

   private JPanel locationPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new FlowLayout());

      panel.add(fileName);
      panel.add(fileTxt);
      panel.add(browse);

      return panel;
   }

   public static FileSelector getInstance() {
      if (instance == null) {
         instance = new FileSelector();
      }

      return instance;
   }
}

class DelemeterSelector extends JPanel {
   private JLabel description;
   private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn;
   private JTextArea txtArea;
   private JScrollPane scroll;
   private ButtonGroup btnGroup;

   private GridBagLayout gbl;
   private GridBagConstraints gbc;
   private SimpleModel simpleModel;

   private static DelemeterSelector instance = null;

   private DelemeterSelector() {
      description = new JLabel(
            "What delemeter separates your fields? Select the appropreiate delemeter");

      tabBtn = new JRadioButton("Tab");
      semicolanBtn = new JRadioButton("Semicolan");
      commaBtn = new JRadioButton("Comma");
      spaceBtn = new JRadioButton("Space");

      btnGroup = new ButtonGroup();
      btnGroup.add(tabBtn);
      btnGroup.add(semicolanBtn);
      btnGroup.add(commaBtn);
      btnGroup.add(spaceBtn);

      txtArea = new JTextArea(20, 70);

      scroll = new JScrollPane(txtArea);

      gbl = new GridBagLayout();
      gbc = new GridBagConstraints();

      this.setLayout(gbl);

      // Creating the GUI
      gbc.gridx = 1;
      gbc.gridy = 1;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.insets = new Insets(20, 0, 0, 0);
      this.add(description, gbc);

      gbc.gridx = 1;
      gbc.gridy = 2;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.insets = new Insets(20, 0, 0, 0);
      this.add(radioPanel(), gbc);

      gbc.gridx = 1;
      gbc.gridy = 3;
      gbc.insets = new Insets(10, 0, 0, 0);
      gbc.fill = GridBagConstraints.BOTH;
      this.add(scroll, gbc);
   }

   private JPanel radioPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new FlowLayout());

      panel.add(tabBtn);
      panel.add(semicolanBtn);
      panel.add(commaBtn);
      panel.add(spaceBtn);

      panel.setBorder(BorderFactory
            .createTitledBorder("Choose the Delimeter that seperates your fields"));

      return panel;
   }

   //!!
   public void setModel(final SimpleModel simpleModel) {
      this.simpleModel = simpleModel;
      simpleModel.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent evt) {
            if (SimpleModel.FILE_TEXT.equals(evt.getPropertyName())) {
               txtArea.append("File Text: " + simpleModel.getFileText() + "\n");
            }         
         }
      });
   }

   public static DelemeterSelector getInstance() {
      if (instance == null) {
         instance = new DelemeterSelector();
      }

      return instance;
   }
}

class SimpleModel {
   public static final String FILE_TEXT = "file text";
   private SwingPropertyChangeSupport pcSupport = 
      new SwingPropertyChangeSupport(this);
   private String fileText;

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.removePropertyChangeListener(listener);
   }

   public void setFileText(String fileText) {
      String oldValue = this.fileText;
      String newValue = fileText;
      this.fileText = fileText;
      pcSupport.firePropertyChange(FILE_TEXT, oldValue , newValue);

   }

   public String getFileText() {
      return fileText;
   }

}

コードの説明を編集します。

これは、モデルとビューにすぎないため、 M odel- View - CコントローラーまたはMVCデザインパターンを大幅に簡略化したものです。このモデルは、GUIが機能するデータとロジックを保持しており、基本的にはプログラムの「頭脳」ですが、GUIは情報の単なる表示にすぎません。

ここでのモデルは非常に単純で、fileTextと呼ばれる1つの文字列フィールドのみを保持します。このフィールドにはセッターとゲッターがあり、このフィールドで最も興味深いのは、このフィールドが変更されたかどうかを知りたいリスナーに通知するようにセッターが配線されていることです。PropertyChangeSupportを使用し、PropertyChangeListenersを許可するこのプロセスは、fileTextフィールドが「バインドされた」プロパティであることを意味します。

両方のJPanelには、同じSimpleModelオブジェクトへの参照を保持するフィールドがあり、このモデルはsetterメソッドsetModel(...)を介して設定されます。

  fileSelector.setModel(simpleModel); // !!
  delemeterSelector.setModel(simpleModel); // !!

JButtonが押された場合、FileSelectorオブジェクトにfileTextフィールドを設定させます。

  browse.addActionListener(new ActionListener() {

     @Override
     public void actionPerformed(ActionEvent e) {
        if (simpleModel != null) {
           simpleModel.setFileText(fileTxt.getText());
        }
     }
  });

DelemeterSelectorクラスにPropertyChangeListenerをモデルに追加して、fileTextフィールドの値が変更されるたびに通知され、適切と思われる場合に応答できるようにします。

public void setModel(final SimpleModel simpleModel) {
  this.simpleModel = simpleModel;
  simpleModel.addPropertyChangeListener(new PropertyChangeListener() {

     @Override
     public void propertyChange(PropertyChangeEvent evt) {
        if (SimpleModel.FILE_TEXT.equals(evt.getPropertyName())) {
           txtArea.append("File Text: " + simpleModel.getFileText() + "\n");
        }
     }
  });
}

モデルクラスは、GUIが保持する情報をどのように処理するかを認識していないことに注意してください。これは、「結合」がかなり緩いことを意味するため、良いことです。

于 2012-11-21T18:03:39.187 に答える