主要就是重载JComboBox里的firePopupMenuWillBecomeVisible方法,使其改变它的弹出行为
下面为示例代码:
MainFrame.java
package com.futuredial.MyApplet;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;
public class MainFrame extends JApplet
{
JComboBoxEx box;
public MainFrame()
{
}
public void init()
{
box = new JComboBoxEx();
Container c = getContentPane();
c.setLayout(null);
Rectangle rc = c.getBounds();
box.setBounds(new Rectangle(0, rc.height-30, 100, rc.height+10));
box.addItem("1");
box.addItem("2");
box.addItem("3");
box.addItem("4");
add(box);
}
}
重新派生出来的JComboBoxEx.java
package com.futuredial.MyApplet;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class JComboBoxEx extends JComboBox
{
public JComboBoxEx()
{
super();
}
public void firePopupMenuWillBecomeVisible()
{
int maxHight = 0;
BasicComboPopup comboPopup = (BasicComboPopup)getUI().getAccessibleChild(this, 0);
maxHight = comboPopup.getHeight();
if (maxHight == 0)
{
maxHight = comboPopup.getPreferredSize().height;
}
comboPopup.setLocation(getLocationOnScreen().x, getLocationOnScreen().y - maxHight);
super.firePopupMenuWillBecomeVisible();
}
}
本文介绍如何通过重写JComboBox的firePopupMenuWillBecomeVisible方法来实现自定义的下拉菜单显示位置。示例代码展示了如何创建一个继承自JComboBox的新类,并在其中覆盖原有方法以调整下拉菜单的位置。
584

被折叠的 条评论
为什么被折叠?



