2010-04-18 254 views
5

我知道這是非常簡單的問題,但我找不到解決方案。點擊按鈕時應該打開一個新窗口?

我有一個主要的揮杆對話框和其他揮杆對話框。主對話框有一個按鈕。 如何在點擊一個按鈕後打開另一個對話框?

編輯:

當我試試這個:

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) { 
     NewJDialog okno = new NewJDialog(); 
     okno.setVisible(true); 
    } 

我得到一個錯誤:

Cannot find symbol NewJDialog 

第二個窗口被命名爲NewJDialog ...

+1

添加一個ActionListener添加到按鈕(例如http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html),其中打開第二個對話框。 – Searles 2010-04-18 17:48:05

+1

關於編輯,您應該瞭解類名和成員名之間的區別,您還應該查看變量的範圍。在你的情況NewJDialog是一個類名稱,因爲這個類不存在,你會得到錯誤。 – Searles 2010-04-18 23:38:32

+0

@Searles:好點。該名稱讓人聯想到NetBeans GUI編輯器生​​成的名稱。一個相關的例子在這裏討論:http://stackoverflow.com/questions/2561480 – trashgod 2010-04-19 03:36:22

回答

6

你當然想看看How to Make Dialogs並查看JDialog API。這裏有一個簡短的例子來開始。你可以將它與你現在正在做的事情進行比較。

import java.awt.EventQueue; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.ButtonGroup; 
import javax.swing.JDialog; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JRadioButton; 

public class DialogTest extends JDialog implements ActionListener { 

    private static final String TITLE = "Season Test"; 

    private enum Season { 
     WINTER("Winter"), SPRING("Spring"), SUMMER("Summer"), FALL("Fall"); 
     private JRadioButton button; 
     private Season(String title) { 
      this.button = new JRadioButton(title); 
     } 
    } 

    private DialogTest(JFrame frame, String title) { 
     super(frame, title); 
     JPanel radioPanel = new JPanel(); 
     radioPanel.setLayout(new GridLayout(0, 1, 8, 8)); 
     ButtonGroup group = new ButtonGroup(); 
     for (Season s : Season.values()) { 
      group.add(s.button); 
      radioPanel.add(s.button); 
      s.button.addActionListener(this); 
     } 
     Season.SPRING.button.setSelected(true); 
     this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
     this.add(radioPanel); 
     this.pack(); 
     this.setLocationRelativeTo(frame); 
     this.setVisible(true); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     JRadioButton b = (JRadioButton) e.getSource(); 
     JOptionPane.showMessageDialog(null, "You chose: " + b.getText()); 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new DialogTest(null, TITLE); 
      } 
     }); 
    } 
} 
相關問題