2012-08-12 32 views
2

請看下面的代碼。ComponentListener不工作

package normal; 

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

public class MainForm extends JFrame implements ComponentListener 
{ 
    private JTabbedPane tab; 

    private InsertForm insertForm; 
    private UpdateDeleteForm updateDelete; 
    private SearchForm searchForm; 

    public MainForm() 
    { 
     tab = new JTabbedPane(); 
     insertForm = new InsertForm(); 
     updateDelete = new UpdateDeleteForm(); 
     searchForm = new SearchForm(); 

     //Creating the main window 
     tab.add(insertForm,"Insert"); 
     tab.add(updateDelete,"Update/Delete"); 
     tab.add(searchForm,"Search"); 
     tab.addChangeListener(new TabChangeWork()); 

     getContentPane().add(tab); 




     // this.setSize(500,500); 
     this.setTitle("My Phone Book App"); 
     this.setResizable(false); 
     this.pack(); 
     this.validate(); 
     this.setLocationRelativeTo(null); 
     this.setVisible(true); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    } 

    @Override 
    public void componentResized(ComponentEvent e) { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 

    @Override 
    public void componentMoved(ComponentEvent e) 
    { 
     System.out.println("X Location: "+this.getX()); 
    } 

    @Override 
    public void componentShown(ComponentEvent e) { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 

    @Override 
    public void componentHidden(ComponentEvent e) { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 

    private class TabChangeWork implements ChangeListener 
    { 

     @Override 
     public void stateChanged(ChangeEvent e) 
     { 
      JTabbedPane tabSource = (JTabbedPane)e.getSource(); 

      int index = tabSource.getSelectedIndex(); 
      System.out.println("Tab Changed to: "+tabSource.getTitleAt(index)); 


      if(tabSource.getTitleAt(index).equals("Update/Delete")) 
      { 
       updateDelete.addNames(); 
      } 
     } 

    } 
} 

在這裏,ComponentListener工作不正常,因爲方法「ComponentMoved」內的動作沒有發生。我試圖獲取JFrame的新座標,如果這是移動。爲什麼它不起作用?請幫忙!!

回答

5

未註冊ComponentListener在代碼的任何地方......

做這樣的....

component_to_monitor.addComponentListener(this); 
+0

非常感謝幫助:)我真的很感激它.. – 2012-08-13 15:48:14

+0

很難相信我做了這樣一個錯誤:(...... – 2012-08-13 15:48:39

3

任何地方你都沒有撥打addComponentListener

如果你想與你的JFrame註冊這樣的監聽器,那麼你可以添加:

addComponentListener(this); 

,或者對於一個子組件,例如searchForm:

searchForm.addComponentListener(this); 
+0

感謝REPL。+1 – 2012-08-13 15:49:04

3

您的MainForm是一個ComponentListener。因此,它會監聽組件事件 - 但只有當你告訴它時,其中才能收聽。聽衆不會自動收聽任何內容。他們最初是聾啞人。

看看你想要監視的組件的移動,並用該組件的addComponentListner方法註冊主框架。 (像component.addComponentListener(this);

+0

謝謝你的回覆+1 – 2012-08-13 15:50:01