I had a desire to create something like that.
At first I tried to implement something along the lines suggested by Varun, but it turned out to be a bit messy, and I'm a little nervous when I start playing with ComponentUI objects (I would prefer to leave such a thing to L & F). If anyone has a good example of this, I would be interested to see it.
So, I tried the button approach ... and thought that I would share the code with the SO community:
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.plaf.basic.BasicInternalFrameUI; import javax.swing.plaf.metal.MetalComboBoxIcon; public class MockJComboBox extends JPanel { private boolean _isPoppedUp = false; public MockJComboBox(String label, final JComponent toShow) { setLayout(new BorderLayout()); JLabel jLabel = new JLabel(label); jLabel.setBackground(Color.WHITE); add(jLabel, BorderLayout.CENTER); Icon icon = new MetalComboBoxIcon(); final JInternalFrame popup = new JInternalFrame(null, false, false, false, false); final JPanel panel = new JPanel(new BorderLayout()); panel.add(new JScrollPane(toShow), BorderLayout.CENTER); if(!(System.getProperty("os.name").startsWith("Mac OS"))){ BasicInternalFrameUI ui = (BasicInternalFrameUI) popup.getUI(); ui.getNorthPane().setPreferredSize(new Dimension(0,0)); } popup.setBorder(null); popup.setContentPane(panel); popup.pack(); popup.setVisible(true); final JButton dropDownButton = new JButton(icon); dropDownButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { _isPoppedUp = !_isPoppedUp; Container parent = getParent(); if (_isPoppedUp) { popup.setLocation(panel.getX(), panel.getY() + panel.getHeight()); popup.setSize(panel.getWidth(), toShow.getHeight()); parent.add(popup); } else { parent.remove(popup); parent.repaint(); } } }); add(dropDownButton, BorderLayout.EAST); } public boolean isPoppedUp() { return _isPoppedUp; } }
If you noticed any errors or have any suggestions for improving this code, I would be grateful for your comments!
source share