Not to long ago, while taking my final programming course for college, I created a calendar program to track the dates I have with my daughter. I have taken a class from that project and wrapped it in a sample package. The class allows you to create a Drop-down-like dialog. All you need to do is create your JDialog, instantiate the class, pass the JDialog into the class and then add the button to your JApplet.
Here is the JApplet code:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DropDownMenuExample extends JApplet {
@Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS));
containerPanel.setMaximumSize(new Dimension(1000, 1000));
containerPanel.setBackground(Color.lightGray);
CDropDownPanel cdp = new CDropDownPanel();
cdp.buttonCreate("Press Me");
cdp.createDropDownDialog(new JDialog());
containerPanel.add(cdp.get());
getContentPane().add(containerPanel);
}
});
} catch (Exception e) {
}
}
}
and here is the class code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
public class CDropDownPanel implements ActionListener {
JDialog mainDialog = new JDialog();
JButton buttonController = new JButton();
public void createDropDownDialog(JDialog newPanel) {
mainDialog = newPanel;
hideDialog();
}
//get the dropdown controller
public JButton get() {
return buttonController;
}
//create the button that controls the panel display.
public JButton buttonCreate(String s) {
jb.addActionListener(this);
buttonController = jb;
return buttonController;
}
//when the controlling button is pressed, display the dialog
@Override
public void actionPerformed(ActionEvent e) {
if (mainDialog.isVisible() == false) {
showDialog();
} else {
hideDialog();
}
}
//position the dialog in the proper place and display it
private void showDialog() {
int x = (int) buttonController.getLocationOnScreen().getX();
int y = (int) buttonController.getLocationOnScreen().getY();
y = y + buttonController.getHeight();
mainDialog.setLocation(x, y);
mainDialog.setVisible(true);
mainDialog.pack();
}
//hide the dialog
private void hideDialog() {
mainDialog.setVisible(false);
}
}
No related posts.