程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> JComboBox的下拉框向上

JComboBox的下拉框向上

編輯:關於JAVA

最近學習SWING,改變JComboBox的的顯示方式,這裡是將JComboBox的下拉框向上顯示,以下為詳細代碼:

package kissJava.JComboBox;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.plaf.ComboBoxUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicComboBoxUI;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.ComboPopup;
public class PopupComboSample extends JFrame...{
   String labels[] = ...{ "Chardonnay", "Sauvignon", "Riesling", "Cabernet",
           "Zinfandel", "Merlot", "Pinot Noir", "Sauvignon Blanc",
           "Syrah", "Gewurztraminer" };
   JComboBox jcb = null;
  public PopupComboSample()...{
   this.setTitle("下拉框向上");
    this.setLayout(null);
     jcb = new JComboBox(labels);
     //setUI.......
     jcb.setUI((ComboBoxUI) MyComboBoxUI.createUI(jcb));
     jcb.setBounds(50, 150, 200, 20);
     this.add(jcb, null);
     setSize(300, 300);
     setVisible(true);
  }

   public static void main(String args[]) ...{

      new PopupComboSample();

   }
   static class MyComboBoxUI extends BasicComboBoxUI ...{
    int newsBarTitleWidth = 0;

     public static ComponentUI createUI(JComponent c) ...{
       return new MyComboBoxUI();
     }
     //改變箭頭的方向
     protected JButton createArrowButton() ...{
       JButton button = new BasicArrowButton(BasicArrowButton.NORTH);
       return button;
     }
     //改變comboBox的彈出方向
     protected ComboPopup createPopup() ...{
      BasicComboPopup popup = new BasicComboPopup(comboBox)...{
       public void show() ...{
          //大小按需要更改
           Dimension popupSize = new Dimension(200 - newsBarTitleWidth - 5, 17 * 5);
           scroller.setMaximumSize(popupSize);
           scroller.setPreferredSize(popupSize);
           scroller.setMinimumSize(popupSize);
           show(comboBox, newsBarTitleWidth, -17 * 5);//getPopupHeightForRowCount(10));
     }
   };
   popup.getAccessibleContext().setAccessibleParent(comboBox);
   return popup;
  }
   }
}

顯示效果為:

不過看圖的效果jcb的輸入框沒有線條顯示,看來得再改改,學習中。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved