2014-02-16 33 views
1

我的程序應該啓動第二個JFrame並在點擊該按鈕時打印語句,但它總是啓動三個JFrame並打印三條語句。我需要它只打印出一條語句並啓動一個Jframe。下面是代碼:如何在不啓動Java中的更多JFrame的情況下使用JFrame按鈕啓動第二個JFrame?

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

@SuppressWarnings("serial") 
public class Test extends JPanel implements ActionListener { 
    JButton button = new JButton(); 
    String buttonString = "Buttontext"; 

    public Test() { 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     button.setText("Buttontext"); 
     button.setCursor(Cursor.getDefaultCursor()); 
     button.setMargin(new Insets(0, 0, 0, 0)); 
     button.setBounds(700, 400, 100, 20); 
     button.setActionCommand(buttonString); 
     button.addActionListener(this); 
     this.add(button); 
    } 

    public static void createandshowGUI() { 
     JFrame frame = new JFrame("Frame"); 
     frame.getContentPane().setBackground(Color.white); 
     Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
     frame.setSize(dim.width, dim.height); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new Test()); 
     frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
     frame.setVisible(true); 
    } 

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

    public void actionPerformed(ActionEvent e) { 
     if (buttonString.equals(e.getActionCommand())) { 
      System.out.println("creating a new frame"); 
      newframe(); 
     } 
    } 

    public void newframe() { 
     JFrame frame2 = new JFrame(); 
     Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
     frame2.setSize(dim.width/2, dim.height/2); 
     frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame2.setExtendedState(JFrame.MAXIMIZED_BOTH); 
     frame2.setVisible(true); 
    } 
} 

回答

2

您不斷增加的ActionListenerbuttonpaintComponent(Graphics)方法。這意味着每次調用此方法時,都會向您的按鈕添加另一個ActionListener。因此,每次按下按鈕時,在按下按鈕之前調用該方法的次數相同。

0

如果你想創建多個窗口,使用JDesktopPane。根據需要添加JInternalFrame。這樣,您將擁有一個帶有子窗口的單一頂層窗口。

2

paintComponent()每當面板被要求畫自己時都會調用。這個請求發生的原因很多 - 包括重新繪製面板,如果另一個窗口已經移動到頂部,或者面板調整大小。 paintComponent()中的任何代碼應僅用於用於繪製組件。

因此,這不是button.addActionListener()的正確位置。實際上,您所有的button代碼(包括this.add(button))都應該發生在其他地方,可能是createandshowGUI。您的程序不需要覆蓋paintComponent()。您可以依靠JPanel來繪製所有已添加到其中的組件(實際上,super.paintComponent()就是這樣做的)。如果您在繪製面板時做了獨特的事情(例如,在面板中放置背景圖像),則只需要覆蓋paintComponent()。在你的情況下,你只需要添加按鈕到面板,你就完成了。