【发布时间】:2013-01-27 02:48:30
【问题描述】:
我的应用程序构造如下:
- 主窗口允许用户选择要解析的 CSV 文件
- 选择 CSV 文件后会出现 JOptionPane,并且 JOptionPane 包含一个带有各种选项的下拉菜单;每个都生成一个单独的窗口
- 目前,从菜单中进行选择并单击“确定”按钮后,JOptionPane 将关闭
我正在寻找一种方法来强制 JOptionPane 保持打开状态,以便用户可以根据需要选择不同的东西。我希望仅通过单击右上角的“X”来关闭 JOptionPane。如果使用 JOptionPane 不是最好的方法,我也愿意接受其他可能性来实现类似的结果。
这是我正在处理的相关代码块:
try
{
CSVReader reader = new CSVReader(new FileReader(filePath), ',');
// Reads the complete file into list of tokens.
List<String[]> rowsAsTokens = null;
try
{
rowsAsTokens = reader.readAll();
}
catch (IOException e1)
{
e1.printStackTrace();
}
String[] menuChoices = { "option 1", "option 2", "option 3" };
String graphSelection = (String) JOptionPane.showInputDialog(null,
"Choose from the following options...", "Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
menuChoices, // Array of menuChoices
menuChoices[0]); // Initial choice
String menuSelection = graphSelection;
// Condition if first item in drop-down is selected
if (menuSelection == menuChoices[0] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option1();
}
if (menuSelection == menuChoices[1] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option2();
}
if (menuSelection == menuChoices[2] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option3();
}
else if (graphSelection == null)
{
log.append("Cancelled." + newline);
}
}
【问题讨论】:
-
请发布您的代码。
-
将下拉菜单放在不同的 jframe 中而不是选项窗格中可能会更好,这将为您提供更多行为选项
-
我还注意到您正在使用
==比较Strings。这不是在Java中执行此操作的方法。您应该改用equals()方法:menuSelection.equals(menuChoice[0]) -
@Michael - 为什么优选 equals() 方法?
-
@THEDOCTOR 在
Java中,==表示法用于比较原语,例如int a = 4; int b = 4; return a == b;将导致TRUE。如果您尝试使用==比较两个Objects(如Strings),它将测试Objects 是否相同(或者,准确地说,它将测试reference是否相同) .例如String c = "Test"; String d = "Test"; return c == d;将导致False。但是return c.equals(d);将导致True。
标签: java swing user-interface drop-down-menu joptionpane