Java
Создание диалоговых окон в Java
Создание диалоговых окон
4
#example
Пример 1: Создание простого диалогового окна с помощью JOptionPane
import javax.swing.JOptionPane; public class DialogExample { public static void main(String[] args) { // создаем диалоговое окно с сообщением JOptionPane.showMessageDialog(null, "Привет, мир!"); // создаем диалоговое окно с вопросом и получаем ответ пользователя int answer = JOptionPane.showConfirmDialog(null, "Вы довольны своей работой?"); if (answer == JOptionPane.YES_OPTION) { System.out.println("Отлично!"); } else if (answer == JOptionPane.NO_OPTION) { System.out.println("Жаль."); } else if (answer == JOptionPane.CANCEL_OPTION) { System.out.println("Ничего не могу сделать."); } // создаем диалоговое окно с полем для ввода текста и получаем введенный текст String input = JOptionPane.showInputDialog(null, "Введите ваше имя:"); System.out.println("Привет, " + input + "!"); } }
Пример 2: Создание своего диалогового окна с помощью JDialog
import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CustomDialog extends JDialog implements ActionListener { private JButton okButton; private JButton cancelButton; public CustomDialog(JFrame parent, String title) { super(parent, title, true); // установка размеров диалогового окна setPreferredSize(new Dimension(300, 150)); // установка компоновщика setLayout(new FlowLayout()); // добавление сообщения в диалоговое окно JLabel message = new JLabel("Вы уверены, что хотите выйти?"); add(message); // создание кнопок okButton = new JButton("Да"); cancelButton = new JButton("Нет"); // установка слушателей на кнопки okButton.addActionListener(this); cancelButton.addActionListener(this); // добавление кнопок в диалоговое окно add(okButton); add(cancelButton); // установка размеров окна под содержимое pack(); // установка позиции окна по центру экрана setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { // обработка нажатия на кнопку if (e.getSource() == okButton) { dispose(); // закрытие диалогового окна } else if (e.getSource() == cancelButton) { dispose(); // закрытие диалогового окна } } }
Пример 3: Создание диалогового окна с использованием JOptionPane и JDialog
import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class DialogExample2 implements ActionListener { private JButton showCustomButton; public static void main(String[] args) { new DialogExample2().createUI(); } public void createUI() { // создаем главное окно JFrame frame = new JFrame("Пример диалоговых окон"); // устанавливаем компоновщик frame.setLayout(new FlowLayout()); // добавляем кнопку для отображения своего диалогового окна showCustomButton = new JButton("Свой диалог"); showCustomButton.addActionListener(this); frame.add(showCustomButton); // добавляем кнопку для отображения диалогового окна с сообщением JButton showMessageDialogButton = new JButton("Сообщение"); showMessageDialogButton.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Привет, мир!")); frame.add(showMessageDialogButton); // добавляем кнопку для отображения диалогового окна с вопросом JButton showConfirmDialogButton = new JButton("Вопрос"); showConfirmDialogButton.addActionListener(e -> { int answer = JOptionPane.showConfirmDialog(frame, "Вы довольны своей работой?"); if (answer == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(frame, "Отлично!"); } else if (answer == JOptionPane.NO_OPTION) { JOptionPane.showMessageDialog(frame, "Жаль."); } else if (answer == JOptionPane.CANCEL_OPTION) { JOptionPane.showMessageDialog(frame, "Ничего не могу сделать."); } }); frame.add(showConfirmDialogButton); // установка параметров окна frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); // установка позиции по центру экрана frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // создание и отображение своего диалогового окна JDialog customDialog = new CustomDialog((JFrame) showCustomButton.getTopLevelAncestor(), "Свой диалог"); customDialog.setVisible(true); } }