主要就是重载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();
}
}