2015-07-11 5 views
0

Когда вы нажимаете кнопку «Поиск», он должен открыть класс MISControlPanel.java, но вместо этого он открывает окно, как вы видите на картинке. Это не должно быть пустым. Любые идеи, почему класс становится пустым? Я думаю, что это имеет какое-то отношение к инициализации «newWindow» к null (в противном случае это породило эту ошибку: «Локальная переменная newWindow, возможно, не была инициализирована»), поэтому я не уверен. enter image description hereОткрытие нового окна в Jframe

соответствующий фрагмент из кода ниже

MISControlPanel newWindow = null; 
        try { 
         newWindow = new MISControlPanel(); 
        } catch (IOException e3) { 
         // TODO Auto-generated catch block 
         e3.printStackTrace(); 
        } 
         newWindow.setVisible(true); 

кода Полного класса


 import java.awt.EventQueue; 

import javax.naming.InvalidNameException; 
import javax.naming.ldap.LdapName; 
import javax.swing.JFrame; 
import javax.swing.JButton; 

import java.awt.BorderLayout; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import java.awt.GridLayout; 

import javax.naming.ldap.LdapName; 
import javax.swing.JTextField; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 
import javax.swing.UIManager; 

import java.awt.Color; 
import java.awt.Font; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.Inet4Address; 
import java.net.UnknownHostException; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

import javax.swing.JTextArea; 
import javax.swing.JTable; 

public class MISSearch { 

    JFrame frame; 
    static JTextField textField; 
    private JTextField textField_1; 
    JLabel selectedComputerFromAD = new JLabel("testing"); 
    String sCurrentLine = null; 
    String CN = null; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 

     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        MISSearch window = new MISSearch(); 
       window.frame.setVisible(true); 


       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the application. 
    * 
    * @throws IOException 
    * 
    * @wbp.parser.entryPoint 
    */ 
    public MISSearch() throws IOException { 
     initialize(); 
    } 

    /** 
    * Initialize the contents of the frame. 
    * 
    * @throws IOException 
    */ 

    private void initialize() throws IOException { 
     frame = new JFrame(); 
     frame.getContentPane().setBackground(Color.LIGHT_GRAY); 
     frame.getContentPane().setForeground(Color.RED); 
     frame.setBounds(100, 100, 394, 111); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(null); 
     frame.setTitle("MIS Control Panel"); 
     frame.setResizable(false); 
     FileWriter fw = new FileWriter("C:\\Users\\anoc5f\\Desktop\\Output.txt"); 
     File tempFile = new File("myTempFile.txt"); 
     JButton searchComputerButton = new JButton("Search"); 
     searchComputerButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 

       MISControlPanel newWindow = null; 
       try { 
        newWindow = new MISControlPanel(); 
       } catch (IOException e3) { 
        // TODO Auto-generated catch block 
        e3.printStackTrace(); 
       } 
        newWindow.setVisible(true); 

        try { 
         new test(); 
        } catch (IOException e2) { 
         // TODO Auto-generated catch block 
         e2.printStackTrace(); 
        } 

       String line; 
       BufferedWriter bw = null; 
       BufferedWriter writer = null; 
       try { 
        writer = new BufferedWriter(new FileWriter(tempFile)); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 


       String s = null; 

       Process p = null; 
       /* 
       * try { // p = Runtime.getRuntime().exec(
       * "cmd /c start c:\\computerQuery.bat computerName"); } catch 
       * (IOException e1) { // TODO Auto-generated catch block 
       * e1.printStackTrace(); } 
       */ 
       try { 

        p = Runtime.getRuntime().exec("c:\\computerQuery.bat"); 

       } catch (IOException e1) { 

        // TODO Auto-generated catch block 

        e1.printStackTrace(); 

       } 
       StringBuffer sbuffer = new StringBuffer(); 
       BufferedReader in = new BufferedReader(new InputStreamReader(p 
         .getInputStream())); 

       try { 

        while ((line = in.readLine()) != null) { 

         System.out.println(line); 

         // textArea.append(line); 

         String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET"; 
         LdapName ldapName = new LdapName(dn); 
         String commonName = (String) ldapName.getRdn(
           ldapName.size() - 1).getValue(); 

        } 
        ComputerQuery.sendParam(); 

       } catch (IOException e1) { 

        // TODO Auto-generated catch block 

        e1.printStackTrace(); 

       } catch (InvalidNameException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } finally 

       { 
        try { 
         fw.close(); 

        } 

        catch (IOException e1) { 
         // TODO Auto-generated catch block 
         e1.printStackTrace(); 
        } 
       } 

       try { 

        in.close(); 

       } catch (IOException e1) { 

        // TODO Auto-generated catch block 

        e1.printStackTrace(); 

       } 

       ComputerQuery.sendParam(); 
     /* 
        SwingUtilities.invokeLater(new Runnable() { 
         public void run() { 
          testLabel.setText(CN); 
         } 
         }); 
      */ 
      } 
     }); 


     try (BufferedReader br = new BufferedReader(new FileReader(
       "resultofbatch.txt"))) { 

      final Pattern PATTERN = Pattern.compile("CN=([^,]+).*"); 
      try { 
       while ((sCurrentLine = br.readLine()) != null) { 

        String[] tokens = PATTERN.split(","); // This will return 
                  // you a array, 
                  // containing the 
                  // string array 
                  // splitted by what 
                  // you write inside 
                  // it. 
        // should be in your case the split, since they are 
        // seperated by "," 
        // System.out.println(sCurrentLine); 
        CN = sCurrentLine.split("CN=", -1)[1].split(",", -1)[0]; 

        System.out.println(CN); 

       } 

      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
     } catch (IOException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } 
     // SwingUtilities.invokeLater(updateCN()); 
     searchComputerButton.setBounds(269, 17, 89, 20); 
     frame.getContentPane().add(searchComputerButton); 

     textField = new JTextField(); 
     textField.setBounds(164, 17, 95, 20); 
     frame.getContentPane().add(textField); 
     textField.setColumns(10); 

     JLabel lblComputerName = new JLabel("Computer Name:"); 
     lblComputerName.setForeground(Color.BLACK); 
     lblComputerName.setFont(new Font("Tahoma", Font.BOLD, 14)); 
     lblComputerName.setBounds(41, 11, 124, 29); 
     frame.getContentPane().add(lblComputerName); 
     java.net.InetAddress localMachine = null; 
     try { 
      localMachine = java.net.InetAddress.getLocalHost(); 
     } catch (UnknownHostException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } 

     JLabel label = null; 
     JLabel lblOpid = new JLabel("Computer by OPID:"); 
     lblOpid.setFont(new Font("Tahoma", Font.BOLD, 14)); 
     lblOpid.setBounds(23, 46, 137, 20); 
     frame.getContentPane().add(lblOpid); 

     textField_1 = new JTextField(); 
     textField_1.setBounds(164, 48, 95, 20); 
     frame.getContentPane().add(textField_1); 
     textField_1.setColumns(10); 

     JButton btnNewButton_2 = new JButton("Search"); 
     btnNewButton_2.setBounds(269, 47, 89, 23); 
     frame.getContentPane().add(btnNewButton_2); 

    } 
    public void setVisible(boolean visible){ 
     frame.setVisible(true); 
    } 
    private void threadStart() { 
      SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 

         } 
      }); 
     } 

} 
+0

Я не получаю исключение NullPointerException. Я не получаю никаких ошибок, это просто не открывает класс должным образом. Он блистает. Я был вынужден инициализировать «newWindow», хотя я инициализирован нулем – user6680

+0

Метод 'setVisible()' должен быть добавлен в класс 'MISControlPanel', а не' MISSearch'. Я предполагаю, что это отдельные классы. –

ответ

1

Я думаю, это потому, что вы используете newWindow.setVisible(true); но ваш MISControlPanel не распространяется Window класса унаследовать setVisible() м ethod, но имеет поле JFrame, и вам нужно установить его видимым отдельно. Попробуйте добавить этот метод к MISControlPanel:

public void setVisible(boolean visible){ 
    frame.setVisible(visible); 
} 
+0

Я добавил метод, но я думаю, что он может попытаться расширить окно, потому что класс MISControlPanel все еще выглядит пустым. Я добавил полный код класса выше. Добавленный метод setVisible находится в нижней части класса. См. Код выше – user6680

+0

@ user6680 Но теперь нет класса MISControlPanel. Так как это работает без него? Вы только что изменили имена? –

+0

Класс MISControlPanel по-прежнему существует. Он находится в пакете по умолчанию с классом MISSearch выше. – user6680

Смежные вопросы