java彈出式菜單

來源:互聯網
上載者:User

JPopupMenu的執行看起來有一些彆扭:我們必須調用enableEvents()方法並選擇滑鼠事件代替利用事件接收器。它可能增加一個滑鼠接收器但MouseEvent從isPopupTrigger()處不會返回真值——它不知道將啟用一個快顯功能表。另外,當我們嘗試接收器方法時,它的行為令人不可思議,這或許是按一下滑鼠活動引起的。在下面的程式例子裡一些事件產生了這種彈出行為:
 

//: Popup.java// Creating popup menus with Swingpackage c13.swing;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Popup extends JPanel {  JPopupMenu popup = new JPopupMenu();  JTextField t = new JTextField(10);  public Popup() {    add(t);    ActionListener al = new ActionListener() {      public void actionPerformed(ActionEvent e){        t.setText(          ((JMenuItem)e.getSource()).getText());      }    };    JMenuItem m = new JMenuItem("Hither");    m.addActionListener(al);    popup.add(m);    m = new JMenuItem("Yon");    m.addActionListener(al);    popup.add(m);    m = new JMenuItem("Afar");    m.addActionListener(al);    popup.add(m);    popup.addSeparator();    m = new JMenuItem("Stay Here");    m.addActionListener(al);    popup.add(m);    PopupListener pl = new PopupListener();    addMouseListener(pl);    t.addMouseListener(pl);  }  class PopupListener extends MouseAdapter {    public void mousePressed(MouseEvent e) {      maybeShowPopup(e);    }    public void mouseReleased(MouseEvent e) {      maybeShowPopup(e);    }    private void maybeShowPopup(MouseEvent e) {      if(e.isPopupTrigger()) {        popup.show(          e.getComponent(), e.getX(), e.getY());      }    }  }  public static void main(String args[]) {    Show.inFrame(new Popup(),200,150);  }} ///:~

相同的ActionListener被加入每個JMenuItem中,使其能從功能表標籤中取出文字,並將文字插入JTextField。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.