- How we can use JOptionPane to display a message dialog
- How to get user input through JOptionPane
- How to use a custom JPanel on the JOptionPane
- How to work on the user input data
Here goes the program
public class JOptionPaneExample
{
private double price;
private JTextField priceField;
private JLabel priceLabel;
public JOptionPaneExample()
{
priceField = new JTextField(10);
}
public void createAndDisplayGUI()
{
int selection = JOptionPane.showConfirmDialog(null, getPanel(), "Price Form : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (selection == JOptionPane.OK_OPTION) // if the use entered data and pressed OK
{
price = Double.valueOf(priceField.getText());
JOptionPane.showMessageDialog(null, "Price is : " + Double.toString(price), "Price : ", JOptionPane.PLAIN_MESSAGE);
}
else if (selection == JOptionPane.CANCEL_OPTION) // if the user pressed cancel button
{
// Do something here.
}
}
private JPanel getPanel()
{
JPanel basePanel = new JPanel();
basePanel.setOpaque(true);
basePanel.setBackground(Color.BLUE.darker());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
priceLabel = new JLabel("Enter Price : ");
centerPanel.add(priceLabel);
centerPanel.add(priceField);
basePanel.add(centerPanel);
return basePanel;
}
}
Don't forget to import and write the driver program yourself. Here's the output from the program
No comments:
Post a Comment