从其他java类调用变量

时间:2014-01-30 16:17:18

标签: java swing netbeans modal-dialog non-static

我有这个loginscreen类;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package program;
import java.sql.*;
import javax.swing.JOptionPane;

/**
 *
 * @author Lacrymae_Ev
 */
public class loginscreen extends javax.swing.JFrame {
    public String username;
    public String getUsername() {
       return username;
    }

    private String pwd;
    public String getPassword() {
       return pwd;
    }

    /**
     * Creates new form loginscreen
     */

    public loginscreen() {
        initComponents();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        Uname_Textfield = new javax.swing.JTextField();
        Password_PasswordField = new javax.swing.JPasswordField();
        Buton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        Buton.setText("Bağlan");
        Buton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(Buton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Buton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        


    private void ButonActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
       String username=Uname_Textfield.getText();
       String pwd= new String (Password_PasswordField.getPassword());
    try {  
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + username + ";" + "password=" + pwd + ";"; 
        Connection con = DriverManager.getConnection(connectionUrl);
        new ProgramPenceresi().setVisible(true);
        dispose();
        }
    catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Wrong username or passwordş!");   
        } 
    catch (ClassNotFoundException cE) {
            System.out.println("Class Not Found Exception: "+ cE.toString());
        }
    }                                     


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new loginscreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Buton;
    private javax.swing.JPasswordField Password_PasswordField;
    private javax.swing.JTextField Uname_Textfield;
    // End of variables declaration                   
}

我有其他课程;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package program;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;

/**
 *
 * @author Lacrymae_Ev
 */
public class cagbas extends javax.swing.JFrame {
    loginscreen logindetails = new loginscreen ();
    String uname = logindetails.getUsername();
    String pass = logindetails.getPassword();
    private static ResultSet rs;
    private static Statement stmt;
    private static Connection con;
    private static final String query = "select 'AICB',sum(dur) as dur,sum(tot)as tot from exampletable with(nolock)\n" +
"where date between '2013-07-01 00:00:00.000' and '2013-07-01 23:59:59.999'\n" +
"and id='013'";
    /**
     * Creates new form cagbas
     */
    public cagbas() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 try
 {     
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + uname + ";" + "password=" + pass + ";"; 
        Connection con = DriverManager.getConnection(connectionUrl);
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
 }
 catch(Exception ex)
 {    
    JOptionPane.showMessageDialog(null, ex.toString());
 } 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new cagbas().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}

但我在cagbas.java中遇到问题,因为当我启动这个类时,java返回错误以下;

problem

我理解我不能在main方法中使用非静态obj。但我如何使用第一个用户在我的程序中输入真实的用户名和密码?

2 个答案:

答案 0 :(得分:1)

我看到的一个问题是你的LoginScreen类是一个JFrame,而JFrame的行为是在显示时不会停止来自调用代码的程序流,所以即使你可以从这个对象中提取登录名和密码你的后期代码,在用户有时间输入任何内容之前,你会过早地提取它。

建议:

  • 最重要的是你正在尝试运行无法编译的代码。 从不这样做,因为这可以保证始终失败。相反,在尝试运行程序之前修复编译问题。
  • 您的LoginScreen应该是模式JDialog,不是 JFrame。
  • 您首先显示此窗口以获取用户的输入。
  • 这里的关键点是,因为它是一个模态JDialog,所以当显示对话框时,调用代码流就会停止。
  • 一旦处理完对话并且不再可见,调用代码就会恢复,这意味着一旦用户输入了数据或取消了对话框。
  • 那时,您可以通过调用getter方法从LoginScreen实例获取登录用户的名称和密码(最好是后者是作为char []获取的),并检查以确保它们不为空。即,LoginScreen应具有public String getUserName()方法和public char[] getPassword()方法。
  • 调用代码现在可以在数据库中使用此信息。
  • 是的,请学习Java命名约定,请通过让您的类名以大写字母和方法以及带小写字母的变量名开头来遵守它们。这将使人们更容易理解您的代码并帮助您,即志愿者在这里做得更好。

修改

另请注意,JOptionPane实际上只是一个模态JDialog,这也可以用于您的目的,也很容易。例如,在下面的示例代码中,我创建一个InputForm JPanel,然后将该JPanel放入JOptionPane:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class MainFoo extends JPanel {
   private static final int COLUMNS = 10;
   private JTextField userNameField = new JTextField(COLUMNS);
   private JTextField passwordField = new JTextField(COLUMNS);
   private InputForm inputForm = new InputForm();

   public MainFoo() {
      add(new JLabel("User Name:"));
      add(userNameField);
      add(Box.createHorizontalStrut(15));
      add(new JLabel("Password:"));
      add(passwordField);
      add(new JButton(new LogInAction("Log in", KeyEvent.VK_L)));
   }

   private class LogInAction extends AbstractAction {
      public LogInAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         int result = JOptionPane.showConfirmDialog(null, inputForm, "Input Form",
               JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
         if (result == JOptionPane.OK_OPTION) {
            userNameField.setText(inputForm.getUserName());


            // ***** never do this! ***** 
            // Never change a password into a String.
            // This is for demo purposes only.
            passwordField.setText(new String(inputForm.getPassword())); 
         }
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("MainFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new MainFoo());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}


@SuppressWarnings("serial")
class InputForm extends JPanel {
   private static final int COLUMNS = 10;
   private static final int GAP = 3;
   private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
   private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
   private JTextField userNameField = new JTextField(COLUMNS);
   private JPasswordField passwordField = new JPasswordField(COLUMNS);

   public InputForm() {
      setLayout(new GridBagLayout());
      addLabel("User Name:", 0);
      addTextField(userNameField, 0);

      addLabel("Password:", 1);
      addTextField(passwordField, 1);

   }

   public String getUserName() {
      return userNameField.getText();
   }

   public char[] getPassword() {
      return passwordField.getPassword();
   }


   private void addTextField(JTextField field, int row) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.gridx = 1;
      gbc.gridy = row;
      gbc.anchor = GridBagConstraints.EAST;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.insets = TEXTFIELD_INSETS;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      add(field, gbc);
   }

   private void addLabel(String text, int row) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.gridx = 0;
      gbc.gridy = row;
      gbc.anchor = GridBagConstraints.WEST;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.insets = LABEL_INSETS;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      add(new JLabel(text), gbc);
   }
}

答案 1 :(得分:0)

loginscreen类的所有实例都cagbas为全局是否真的是你的目标?我猜你想要将loginscreen logindetails定义为类变量,但是你想在cagbas类创建/初始化期间实例化它们。

这样的事情:

public class cagbas extends javax.swing.JFrame {
    loginscreen logindetails;
    String uname;
    String pass;
    ....
    public cagbas () {
       initComponents();
       logindetails = new loginscreen ();
       uname = logindetails.getUsername();
       pass = logindetails.getPassword();

一种风格的笔记,大写你的类名。

[编辑]
您无法访问uname中的main,因为main是静态的而uname不是。{1}}。在实例化Cagbas类之后将该分配移动到一个函数中 [/编辑]