[英]How can I use two buttons instead of JOptionPane.showOptionDialog?
So it works correctly but it is a bit confusing I would like to remove JOptionPane.showOptionDialog and simply add 2 buttons so that it is not so confusing in the code.............所以它可以正常工作,但有点令人困惑我想删除 JOptionPane.showOptionDialog 并简单地添加 2 个按钮,这样它在代码中就不会那么混乱............
I have tried with JButtons but could not make it And more than anything that fulfills the function of throwing the result我已经尝试过使用 JButtons 但无法做到 最重要的是满足 function 的抛出结果
How can I use two buttons instead of JOptionPane.showOptionDialog?如何使用两个按钮而不是 JOptionPane.showOptionDialog?
float n, r;
int a = 1;
String input;
//Button content
Object[] options1 = {"°C -> °F", "°F -> °C", "Exit"};
int menu = JOptionPane.showOptionDialog(null, a + ". Select your conversion",
"Temperature scale selection",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options1, null);
//Button 2
if (menu == JOptionPane.YES_OPTION) {
//Celsius to Fahrenheit
input = JOptionPane.showInputDialog("Enter degrees Celsius: ");
n = Integer.parseInt(input);
r = ((9 * n) / 5) + 32;
JOptionPane.showMessageDialog(null, r + " Fahrenheit");
} else if (menu == JOptionPane.YES_NO_CANCEL_OPTION) { //Button 3
//Fahrenheit to Celsius
input = JOptionPane.showInputDialog("Enter degrees Fahrenheit ");
n = Integer.parseInt(input);
r = (n - 32) * 5 / 9;
JOptionPane.showMessageDialog(null, r + " Celsius");
}
If you want to add a couple of JButtons to just display, that in itself is a bit of a process.如果您想添加几个 JButton 来显示,这本身就是一个过程。 To get one to display, you're going to need a JFrame
and a JPanel
.要显示一个,您将需要一个JFrame
和一个JPanel
。 Once you have those two, you can add a new JButton
to your JPanel
.一旦你有了这两个,你就可以向你的JPanel
添加一个新的JButton
。 Adding multiple buttons and swing components requires the use of a layout for your JPanel
.添加多个按钮和 swing 组件需要使用JPanel
的布局。 You can read more about how to use JPanels , examples of using JPanels , and layout managers .您可以阅读有关如何使用 JPanel 、使用 JPanel 的示例和布局管理器的更多信息。
After you have your buttons displayed on your panel, you have to add an ActionListener
to each button so that it can perform the desired action.在面板上显示按钮后,您必须为每个按钮添加一个ActionListener
以便它可以执行所需的操作。 You can take a look at the JavaDocs or this thread for information on how to write one.您可以查看JavaDocs或此线程以获取有关如何编写的信息。
Getting buttons and other swing components basic functionality is a bit of a process, but it's the most basic way of achieving what you want.获取按钮和其他 swing 组件的基本功能是一个过程,但它是实现您想要的最基本的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.