我们能否通过 Java 请求用户输入来从 JOptionPane 读取数据?
java 8object oriented programmingprogramming
是的,我们可以从 JOptionPane 读取数据。在这里,我们将在字符串变量 − 中获取 showInputDialog() 的结果
String input = JOptionPane.showInputDialog("Enter the C++ lessons you covered till now?");
获取结果后,我们将使用 parseInt() 将其转换为整数并将其显示在控制台 −
int res = Integer.parseInt(input); System.out.println("Lessons covered = "+res);
以下是通过请求用户输入来从 JOptionPane 读取数据的示例 −
示例
package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingDemo { public static void main(String[] args) throws Exception { ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png")); JLabel label = new JLabel(icon); JPanel panel = new JPanel(new GridBagLayout()); panel.add(label); panel.setOpaque(true); panel.setBackground(Color.ORANGE); JPanel textPanel = new JPanel(new GridLayout(10, 5)); for (int i = 0; i < 20; i++) { textPanel.add(new JLabel("Learn C++")); } JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(textPanel); panel2.add(panel, BorderLayout.EAST); JOptionPane.showMessageDialog(null, panel2, "Course",JOptionPane.DEFAULT_OPTION); String input = JOptionPane .showInputDialog("Enter the C++ lessons you covered till now?"); int res = Integer.parseInt(input); System.out.println("Lessons covered = "+res); } }
输出
单击上面的"确定"后,将要求用户输入,如下所示 −
现在,按下 ENTER 键后,上面添加的课程编号将显示在控制台中,如下所示−