gpt4 book ai didi

java - 异常不起作用(不显示 JOptionPane 消息)

转载 作者:行者123 更新时间:2023-12-01 09:36:51 27 4
gpt4 key购买 nike

我有一个字符串,它从 jtextfield 获取数据,然后我将此数据子串为三个字符串中的 3 个字母(字符串第一个、第二个、第三个)

try {
String text,first,second,third,result;
Swing get = new Swing();
text = get.getMyText();
first = text.substring(0,1);
second = text.substring(1,2);
third = text.substring(2,3);
result = first + third + second;
if(text.isEmpty) {
throw new Exception();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Empty","....",JOptionPane.ERROR_MESSAGE);
}

我从系统收到这条奇怪的消息,而不是 JOptionPane 消息:

Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

我想念这里的任何线索吗?

供您引用,我也尝试了以下方法,但仍然出现相同的错误

if(first.isEmpty() || second.isEmpty() || third.isEmpty()) {
// my message
}

我的 Swing 类如下:

public class Swing {

// second line of the frame

private static JFrame window; // creating the frame
private static JTextField text;
// setting the frame
/**
* @wbp.parser.entryPoint
*/
public void Run() {

window = new JFrame("Tool");
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(new Color(230, 230, 250));
window.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
window.getContentPane().isOpaque();

window.getContentPane().setLayout(null);

// the textfield
text = new JTextField();
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setForeground(Color.BLUE);
text.setFont(new Font("David", Font.PLAIN, 20));
text.setColumns(10);
text.setBounds(504, 11, 149, 20);
window.getContentPane().add(text);

// adding the button from the other class (MyBtn)
MyBtn addBTN = new MyBtn();
window.getContentPane().add(addBTN.run());

// setting the frame
window.setVisible(true);
window.setSize(750, 500);
window.setLocationRelativeTo(null);
}

// preparing the getters for the input
public String getText() {
return text.getText();
}

最佳答案

在尝试从中提取子字符串之前,您需要测试文本是否为空,因为我打赌您可能会尝试从空字符串中获取子字符串,因此您'重新看到运行时异常。

我敢打赌,您的 Swing 类是一个 GUI,可能是一个 JFrame,您正在创建一个不显示的 Swing 对象并尝试从中提取文本,并且由于它不显示,因此用户还没有在文本字段中输入任何数据。也许您想从完全独立且唯一显示的 Swing 对象中提取文本。但同样,这只是一个猜测。如果我是对的,那么您将需要在需要的地方传递对可视化 GUI 组件的引用,而不是创建不必要的新组件。

还有catch (exception e) {是什么类?您的意思是要大写 Exception 吗?

<小时/>

类似于:

// get should be set with a valid reference to the displayed
// Swing object. Don't create a **new** Swing object
// Swing get = new Swing(); // no!

String text = get.getMyText().trim();

if (text.isEmpty() || text.length() < 4) {
// show error message in JOptionPane
} else {
String text,first,second,third,result;
first = text.substring(0,1);
second = text.substring(1,2);
third = text.substring(2,3);
result = first + third + second;
}

关于java - 异常不起作用(不显示 JOptionPane 消息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38818354/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com