2012-01-27 38 views
0

如何關閉當前幀(Frame1)並打開已創建的新幀(Frame2),並通過單擊按鈕將數據從frame1傳遞到frame2?按鈕提交時的擺動方式

+1

您能否詳細說明您的問題。什麼情況? – MrWaqasAhmed 2012-01-27 09:53:50

+0

@MWWaqasAhmed優秀的問題。 +1 – 2012-01-27 12:37:35

回答

2

達到這一目的的最佳方式,是通過@Andrew湯普森十分告訴你。 另一種完成方式是代碼中描述的問題的動機。在你創建新的JFrame的對象時,你必須將其他類中需要的東西作爲參數傳遞給另一個類,或者你可以簡單地傳遞這個對象(通過這個,你可以一次性傳遞所有對象)類)

的一點幫助的樣本代碼:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class TwoFramesExample 
{ 
    public JFrame frame; 
    private JPanel panel; 
    private JButton button; 
    private JTextField tfield; 
    private SecondFrame secondFrame; 

    public TwoFramesExample() 
    { 
     frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationRelativeTo(null); 

     panel = new JPanel(); 
     panel.setLayout(new BorderLayout()); 

     tfield = new JTextField(10); 
     tfield.setBackground(Color.BLACK); 
     tfield.setForeground(Color.WHITE); 

     button = new JButton("NEXT"); 
     button.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       // Here we are passing the contents of the JTextField to another class 
       // so that it can be shown on the label of the other JFrame. 
       secondFrame = new SecondFrame(tfield.getText());     
       frame.dispose(); 
      } 
     }); 

     frame.setContentPane(panel); 
     panel.add(tfield, BorderLayout.CENTER); 
     panel.add(button, BorderLayout.PAGE_END); 

     frame.pack(); 
     frame.setVisible(true); 
    } 

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

class SecondFrame 
{ 
    private JFrame frame; 
    private JPanel panel; 
    private JLabel label; 
    private JButton button; 
    private TwoFramesExample firstFrame; 

    public SecondFrame(String text) 
    { 
     frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationRelativeTo(null); 

     panel = new JPanel(); 
     panel.setLayout(new BorderLayout()); 

     label = new JLabel(text); 
     button = new JButton("BACK"); 
     button.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       firstFrame = new TwoFramesExample(); 
       frame.dispose(); 
      } 
     }); 

     frame.setContentPane(panel); 
     panel.add(label, BorderLayout.CENTER); 
     panel.add(button, BorderLayout.PAGE_END); 

     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

希望這是一些幫助。

Regards

+0

+1。 'frame.setLocationRelativeTo(null);'另請參見['setLocationByPlatform(true)'](http://stackoverflow.com/a/7143398/418556)。適合這種情況。 ;) – 2012-01-27 11:29:58

+0

@AndrewThompson:謝謝,正是我在找的東西,因爲我剛剛從你的答案的某個地方找到了關於這個東西的地方:-)問候 – 2012-01-27 11:33:25