2013-06-03 4 views
0

У меня есть JPanel, у которого есть два Jbuttons. Цель состоит в том, что как только я нажимаю первый Jbutton («Вы предсказывали значение ...»), появляется еще одна JPanel, и я вижу другие созданные Jbuttons. Проблема в том, что когда я запускаю код, я вижу первую панель, но когда я нажимаю на кнопку, ничего не происходит. Было бы здорово, если бы вы могли мне помочь.Добавить ActionListener в JPanel

public class Main { 

    private static Component frame; 
    private static JFileChooser inputFile; 
    private static JFileChooser outputFile; 
    private static String fullpath; 
    private static String fullpath1; 
    private static String fullpath2; 
    private static String fullpath3; 

    public static void main(String args[]) throws FileNotFoundException, IOException { 

     try { 

      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.insets = new Insets(5, 5, 5, 5); 

      JButton nextPanel = new JButton("Do you have predicted values or residual errors?"); 
      JButton inputButton = new JButton("Browse predictor dataset"); 

      JPanel myPanel = new JPanel(new GridBagLayout()); //new panel 

      gbc.gridwidth = 1; 
      gbc.gridheight = 1; 
      gbc.gridx = 0; 
      gbc.gridy = 1; 
      gbc.anchor = (0 == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST; 
      gbc.fill = (0 == 0) ? GridBagConstraints.BOTH 
       : GridBagConstraints.HORIZONTAL; 
      gbc.weightx = (0 == 0) ? 0.1 : 0.1; 
      gbc.weighty = 1.0; 
      myPanel.add(nextPanel, gbc); 

      final JPanel myPanel1 = new JPanel(new GridBagLayout()); 
      myPanel.add(myPanel1);  

      nextPanel.addActionListener(new ActionListener(){ 
       public void actionPerformed(ActionEvent e){ 

        GridBagConstraints gbc1 = new GridBagConstraints(); 
      gbc1.insets = new Insets(5, 5, 5, 5); 
      JButton errorButton = new JButton("Browse residual error associated to each instance"); 
      JButton predictedButton = new JButton("Browse predicted value associated to each instance"); 
      gbc1.gridwidth = 1; 
      gbc1.gridheight = 1; 
      gbc1.gridx = 0; 
      gbc1.gridy = 1; 
      gbc1.anchor = (0 == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST; 
      gbc1.fill = (0 == 0) ? GridBagConstraints.BOTH 
       : GridBagConstraints.HORIZONTAL; 
      gbc1.weightx = (0 == 0) ? 0.1 : 0.1; 
      gbc1.weighty = 1.0; 
      myPanel1.add(errorButton, gbc1); 
       } 
      }); 

      gbc.gridwidth = 1; 
      gbc.gridheight = 1; 
      gbc.gridx = 0; 
      gbc.gridy = 9; 
      gbc.anchor = (0 == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST; 
      gbc.fill = (0 == 0) ? GridBagConstraints.BOTH 
       : GridBagConstraints.HORIZONTAL; 
      gbc.weightx = (0 == 0) ? 0.1 : 0.1; 
      gbc.weighty = 1.0; 
      myPanel.add(inputButton, gbc); 

      inputButton.addActionListener(new ActionListener() { 
       public void actionPerformed(ActionEvent e) { 
        JFileChooser inputFile = new JFileChooser(); 
        inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 
        if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
         File file1 = inputFile.getSelectedFile(); 
         String fullpathTemp = (String) file1.getAbsolutePath(); 
         fullpath = fullpathTemp; 
        } 
       } 
      }); 

      int result = JOptionPane.showConfirmDialog(null, myPanel, "CPM Program", JOptionPane.OK_CANCEL_OPTION); 


} catch (Exception e) { 
      System.err.println("Error: " + e.getMessage()); 
     } finally { 
     } 
    } 
} 
+3

Насколько я могу судить, вы никогда не добавляете 'myPanel1' в' myPanel' – MadProgrammer

+2

Вы также можете взглянуть на [Как использовать CardLayout] (http://docs.oracle.com/javase/tutorial /uiswing/layout/card.html) – MadProgrammer

+0

Спасибо за комментарий. Ты прав. Я редактировал код, но все же у нас есть проблема. – MTT

ответ

0

У вас есть две проблемы. Во-первых, вы должны использовать рамку JDialog для отображения mypanel1 - я не думаю, что вы можете просто отображать JPanel самостоятельно.

Итак, при нажатии этой опции создайте новый JDialog и добавьте к нему второй JPanel. Обязательно вызовите метод setVisible в поле JDialog.

Теперь у вас будет другая проблема. Созданный первый кадр (сообщение showConfirm) получит все actionEvents, и ваш JDialog не получит ни одного. И, поскольку вы передали null в качестве родительского фрейма для вашего JOption, ваш новый JDialog не сможет «запросить фокус» и, таким образом, не получит никаких actionEvents.

Итак, вам нужно будет реорганизовать свой код, чтобы убедиться, что любой новый JDialogBox, который был порожден, может запросить фокус.

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