1

行。我有一个包含两个容器的大型机。一个包含我的类似向导的按钮,另一个包含 contentPane。我有几个类 Window1、Window2 等,我在我的大型机类中实例化它们,然后通过 cardLayout 来决定哪个 Window 类在 contentPane 中可见。

这些 Window 类中的每一个都需要与数据库的连接。目前我在窗口类中分别实例化一个数据库连接,但我想要某种形式的全局会话,从我通过我的 Window1 类(也称为登录类)到我关闭应用程序的那一刻起我就连接了,所以当我访问其他 Window 类时,我可以使用此会话读取和写入数据库。

我的 MainFrame 类:

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();
            }
        });
    }
} 

Window 类的示例:

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;
}

}

4

1 回答 1

2

我会使用单例模式。它基本上允许您拥有一个对象的一个​​实例,并且您可以在任何地方获取它。在此处了解更多信息: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;
  }
}
于 2012-03-22T12:20:28.090 回答