2012-03-22 5 views
1

私は2つのコンテナを含むメインフレームを持っています。 1つは私のウィザードのようなボタンともう1つはcontentPaneです。私はいくつかのクラスWindow1、Window2など私はどのWindowクラスをcontentPaneで表示するかを決定するcardLayoutを介して私のメインフレームクラスでインスタンス化し、次にtoogleを介して。Java、スイングアプリケーションでグローバルデータベースセッションを維持

これらのウィンドウクラスのそれぞれは、データベースへの接続が必要です。現在、私はウィンドウクラスのデータベース接続をseparetlyインスタンス化しますが、アプリケーションを終了するまで私がWindow1クラス(ログインクラスとも呼ばれます)を渡した瞬間から接続されているグローバルセッションのいくつかのフォームが必要です。他のWindowクラスにアクセスすると、このセッションを使用してデータベースに読み書きできます。

マイメインフレームクラス:ウィンドウクラスの

public class MainFrame { 
private static void createAndShowGUI() { 
    JFrame frame = new JFrame("Stackoverflowquestion"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationRelativeTo(null); 

    final JPanel contentPane = new JPanel(); 
    contentPane.setLayout(new CardLayout(5, 5)); 

    Database db = new Database(); 
    //Trying to make some kind of global database instance but fails 

    Window1 win1 = new Window1(); 
    contentPane.add(win1); 
    Window2 win2 = new Window2(); 
    contentPane.add(win2); 
    Window3 win3 = new Window3(); 
    contentPane.add(win3); 
    Window4 win4 = new Window4(); 
    contentPane.add(win4); 
    Window5 win5 = new Window5(); 
    contentPane.add(win5); 
    Window6 win6 = new Window6(); 
    contentPane.add(win6); 

    JPanel buttonPanel = new JPanel(); 
    final JButton previousButton = new JButton("< PREVIOUS"); 
    previousButton.setEnabled(false); 
    final JButton nextButton = new JButton("NEXT >"); 
    final JButton cancelButton = new JButton("CANCEL"); 
    buttonPanel.add(cancelButton); 
    buttonPanel.add(previousButton); 
    buttonPanel.add(nextButton);    

    nextButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      nextButton.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 
      Verifiable verifiable = null; 
      Component[] contents = contentPane.getComponents(); 
      for(Component component : contents) { 
       if(component.isVisible() && component instanceof Verifiable) { 
        verifiable = (Verifiable)component; 
       } 
      } 
      if(verifiable != null && verifiable.isDataValid()) { 
       CardLayout cardLayout = (CardLayout) contentPane.getLayout(); 
       cardLayout.next(contentPane); 
       previousButton.setEnabled(true); 
       nextButton.setCursor(Cursor.getDefaultCursor()); 

      } 
     } 
    }); 

    cancelButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      System.exit(0); 
       //Should close the database session 
     } 

    }); 

    frame.add(contentPane); 
    frame.add(buttonPanel, BorderLayout.PAGE_END); 
    frame.setSize(400, 400); 
    frame.setVisible(true); 
} 
    public static void main(String[] args) { 

     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 

例:

public class Window1 extends JPanel implements Verifiable { 

public static final String IDENTIFIER = "FIRST"; 

JTextField txtUsername = new JTextField(); 
JPasswordField txtPassword = new JPasswordField(); 

Database db = new Database(); 
    //As I said, I currently intantiate a database connection separetely which 
    //I want to get rid of 
public Window1() { 
    init(); 
} 

private void init() { 
    JLabel lblUsername = new JLabel("Username:", JLabel.CENTER); 
    lblUsername.setBounds(10, 91, 135, 77); 
    txtUsername = new JTextField(); 
    txtUsername.setBounds(155, 116, 188, 27); 

    JLabel lblPassword = new JLabel("Password:", JLabel.CENTER); 
    lblPassword.setBounds(0, 163, 149, 77); 
    txtPassword = new JPasswordField(); 
    txtPassword.setBounds(155, 188, 188, 27); 
    setLayout(null); 

    add(lblUsername); 
    add(txtUsername); 
    add(lblPassword); 
    add(txtPassword); 
    String title = "Log in"; 
    setBorder(BorderFactory.createTitledBorder(title)); 
} 

@Override 
public boolean isDataValid() { 
    String username = new String(txtUsername.getText()); 
    String password = new String(txtPassword.getPassword()); 

    try { 
     DatabaseConnection conn = db.getDatabaseConnection(username, password, "test", "test", "test"); 
     db.getTest(conn); 
     return true; 
     } catch (LoginFailedException e) { 
      JOptionPane.showMessageDialog(this, "Something went wrong", 
        "Error", JOptionPane.ERROR_MESSAGE); 
      return false; 
    } 
} 

@Override 
public String getIdentifier() { 
    return IDENTIFIER; 
} 

}

答えて

2

私はシングルトンパターンを使用します。基本的には、オブジェクトの1つのインスタンスを持つことができ、どこにでも置くことができます。ここをクリックしてください:http://en.wikipedia.org/wiki/Singleton_pattern

私の例では、希望のデータベースへの呼び出しを作成するために使用するデータベース接続があります。私は現在取り組んでいるプロジェクトでこれと全く同じことをやっています。それはここで素晴らしい:)

を作品例です:

public class DatabaseConnection { 

    private static DatabaseConnection instance; //note this is static 

    private DatabaseConnection() { //note this is private 
    } 

    public static DatabaseConnection getInstance() { //note this is static 
    if (instance == null) { 
     instance = new DatabaseConnection(); 
    } 
    return instance; 
    } 

また、ウィキペディアは、伝統的な方法(これを見た後、私はこれは私が今からやる方法だと思う)と呼ぶものを試みることができます。

public class DatabaseConnection { 
    private static final DatabaseConnection instance = new DatabaseConnection(); 

    // Private constructor prevents instantiation from other classes 
    private DatabaseConnection() { } 

    public static DatabaseConnection getInstance() { 
    return instance; 
    } 
} 
+0

ありがとうございました。私はシングルトンパターンについて少しは読んだことがあるが、私はそれを理解していない。私は現在のアプリケーションでそれを実装する方法をいくつかのコードで見せてもらえますか? –

+0

私はシングルトンパターンを使ってサンプルクラスで自分の答えを更新しました。基本的には、コンストラクタをprivateにして、それを作成できる唯一のクラスはそれ自身です。また、それ自身の型の 'instance'というグローバル変数もあります。次に、変数 'instance'を返す' public static Connection getInstance() 'メソッドがあります(nullの場合、最初に' instance = new Connection(); ')。こうすることで、データベースに1つの接続を持たせ、どこからでも渡すことなく、どこにでも接続できます。それは理にかなっていますか? – kentcdodds

+1

あなたのデータベースロジックはあなたのGUIから完全に分離しているべきです。あなたはこの質問をするときに私たちにあなたのGUIコードを与えるべきではありません:-)シングルトンのパターンはうまく動作します。私はちょうどあなたのデータベース接続の大部分を扱うcommons-dbcpをチェックしたいと思うかもしれません(接続プールを与えるcommons-poolingも使います)http://commons.apache.org/dbcp/ – Michael