Java GUI: Confirm Dialogs Using Eclipse IDE

in #utopian-io6 years ago (edited)

What Will I Learn?

  • The user will learn about Confirm Dialog Box Method.
  • The user will learn how to use Confirm Dialogs to make better decisions.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

Intermediate.

Tutorial Contents

This method is a quick and easy way to get user input by asking a confirming question, like yes/no/cancel . The showConfirmDialog() can be called using the following combinations of parameters:

Component, Object
Component, Object, String, int
Component, Object, String, int, int
Component, Object, String, int, int, Icon

Component – The first parameter is a Component which determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used.

Object – The second parameter can be any Object. (In some older versions of Java you might get a compiler error when using primitive types directly)

String – The third parameter is a String placed as the title of the confirmDialog window.

int – The int that follows the String is the OptionType. The different OptionTypes for JOptionPane, are:

  • DEFAULT_OPTION
  • YES_NO_OPTION
  • YES_NO_CANCEL_OPTION
  • OK_CANCEL_OPTION

int – The next int is the MessageType. The different MessageTypes for JOptionPane, are:

  • ERROR_MESSAGE
  • INFORMATION_MESSAGE
  • WARNING_MESSAGE
  • QUESTION_MESSAGE
  • PLAIN_MESSAGE

Icon – The last parameter is an Icon that is displayed inside the dialog and overrides the default MessageTypeicon.

In this tutorial, we will create two classes;

  • Class 1: We will create two JList objects, Inventory and Foods list and a JButton object. Inventory list will contain items of two different categories; Foods list will be empty. The user will select an item from Inventory list to add to Foods list, when the button is clicked, a Confirmation message pops up asking the user to confirm decision. After confirmation, the items are added or left out.

  • Class 2: Contains main method for run instructions.

This tutorial is done in assumption that the user follows through previous tutorials and is familiar with the coding terms used therein, also, have basic Java programming knowledge.

1.png

2.png

3.png

CODE BLOCK

confirmDialog Class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class confirmDialog extends JFrame {
    private JPanel panel;
    private JButton toButton;
    private JLabel label1;
    private JLabel label2;
    private JList inventory;
    private JList foods;
    String[] list = {"Wire", "Fudge", "Toothbrush", "Ketchup", 
            "Telephone", "Bottle", "Burger", "Potato", 
            "Television", "Taco"};
    public confirmDialog() {
        super("Confirm Dialog Demo");
        setLayout(null);
        panel = new JPanel();
        panel.setBackground(Color.BLACK);
        getContentPane().setBackground(Color.ORANGE);
        add(panel);
        label1 = new JLabel("Inventory List");
        label1.setFont(new Font("Castellar", Font.BOLD, 15));
        label1.setBounds(30, 21, 200, 20);
        add(label1);
        inventory = new JList(list);
        inventory.setBackground(Color.YELLOW);
        inventory.setBounds(40, 55, 120, 190);
        add(inventory);
        toButton = new JButton("Add to Foods");
        toButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        int option = JOptionPane.showConfirmDialog(null, "Are you sure?", "Confirm Dialog Box", 
                                JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION)
                            foods.setListData(inventory.getSelectedValues());
                    }
                }
                );
        toButton.setBounds(170, 110, 110, 30);
        toButton.setBackground(Color.ORANGE);
        add(toButton);
        label2 = new JLabel("Foods List");
        label2.setFont(new Font("Castellar", Font.BOLD, 15));
        label2.setBounds(280, 21, 200, 20);
        add(label2);
        foods = new JList();
        foods.setBackground(Color.YELLOW);
        foods.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        foods.setBounds(290, 55, 120, 190);
        add(foods); 
    }
}
confirmMain Class
import javax.swing.JFrame;
public class confirmMain {
    public static void main (String args []) {
        confirmDialog confirm = new confirmDialog();
        confirm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        confirm.setSize(500, 350);
        confirm.setVisible(true);
    }
}

Output

ezgif.com-optimize.gif

confirmDialog Class

label1 = new JLabel("Inventory List");
label1.setFont(new Font("Castellar", Font.BOLD, 15));
label1.setBounds(30, 21, 200, 20);
add(label1);

A label to describe the Inventory List is created and the font name, type and size is also set using .setFont(), it appears at the top left corner of the screen which is done using .setBounds() and it’s added to the frame. Basically, this names the list.

inventory = new JList(list);
inventory.setBackground(Color.YELLOW);
inventory.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
inventory.setBounds(40, 55, 120, 190);
add(inventory);

This creates a JList object. Background color set to Yellow.

This is a MULTIPLE INTERVAL SELECTION list. This means that you can select multiple list items at once.

.setBounds() sets the location and the list is added to the frame.

toButton = new JButton("Add to Foods");
toButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure?", "Confirm Dialog Box", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION)
foods.setListData(inventory.getSelectedValues());
}
}
);
toButton.setBounds(170, 110, 110, 30);
toButton.setBackground(Color.ORANGE);
add(toButton);

This creates a JButton object with the tag “Add to Foods. This button adds the selected items to the Foods List.
An ActionListener is associated with the button, this interface listens for events so it can execute commands when clicked. For more on ActionListeners and EventHandlers, click my blog post here
In the Listener Interface, the .showConfirmDialog() method is used to make decisions. When the button is clicked, a pop up confirmation box appears asking the user to confirm his selection. The dialog has a “Yes” and “No” option.
If the Yes option is clicked, the Foods List is populated with the selected values from Inventory List. This is done using .setListData(inventory.getSelectedValues).
The button is set between the two lists and is added to the frame.

label2 = new JLabel("Foods List");
label2.setFont(new Font("Castellar", Font.BOLD, 15));
label2.setBounds(280, 21, 200, 20);
add(label2);

This creates a label to name the Foods List. The font name, type, size and location is set and is added to the frame.

foods = new JList();
foods.setBackground(Color.YELLOW);
foods.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
foods.setBounds(290, 55, 120, 190);
add(foods);

This creates a second JList object. Background color set to Yellow.

This is a MULTIPLE INTERVAL SELECTION list.

.setBounds() sets the location and the list is added to the frame.

This List is the destination of the selected values from Inventory list after the button is clicked.

confirmMain class

import javax.swing.JFrame;
public class confirmMain {
public static void main (String args []) {
confirmDialog confirm = new confirmDialog();
confirm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
confirm.setSize(500, 350);
confirm.setVisible(true);
    }
}

Main class containing main method with instructions on how the program runs.

An object of the Slider class is created. The slider class holds instructions for running the program.

The program Exit Mode is set. This will close the program when user clicks the “X” button on the frame.

Size of the window is set using inbuilt methods .setSize

Visibility setting is set, making the frame visible, the code .setVisible(true) is used.

ezgif.com-optimize.gif

4.png

5.png

6.png

7.png

The program is run and the two Lists is displayed; Inventory List is populated and Foods List is empty, multiple items are selected holding down the Ctrl button, when the “Add to Foods button” is clicked, a confirmation box pops up asking the user to confirm his decision. After confirmation, the items are added to the Foods List. If “No” is clicked, things remain as they were.

8.png

9.png

10.png

Source codes from Github.

You can get the codes at my GitHub Account if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

This post has received a 0.16 % upvote from @drotto thanks to: @banjo.