gpt4 book ai didi

java - JPanel 元素没有出现

转载 作者:行者123 更新时间:2023-11-30 07:16:24 25 4
gpt4 key购买 nike

我正在使用 Swing 库询问用户的邮政编码,但出现的只是一个框,没有文本框,也没有我添加的任何其他元素(参见代码)。此外,您可能需要知道我正在尝试在我的 public static void main(String[] args) 方法中获取 int AskZip()。

    private static int zip;
public static int AskZip() {
JFrame zaWindow = new JFrame("What Zipcode");
zaWindow.setSize(200, 300);
JPanel jp = new JPanel();
final JTextField tf = new JTextField("Enter Zip Here");
JLabel label = new JLabel();
JButton button = new JButton("Get Weather");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sZip = tf.getText();
int rZip = 0;
try {
if (sZip.length() != 5) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
rZip = Integer.parseInt(sZip);
}
} catch (NumberFormatException arg) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
}
zip = rZip;
}
});
label.setText("What is your zipcode?");
jp.add(label);
jp.add(tf);
jp.add(button);
zaWindow.add(jp);
return zip;
}

最佳答案

JFrame zaWindow..

这应该是模态对话框或 JOptionPane。例如。这个国家有 3 个州,每个州有 10 个邮政编码。

Enter Zip Code

import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeListener;

class ZipQuery {

public static void main(String[] args) {
Runnable r = new Runnable() {

@Override
public void run() {
ZipNumberModel znm = new ZipNumberModel();
JSpinner zip = new JSpinner(znm);

JOptionPane.showMessageDialog(null, zip, "Enter Zipcode", JOptionPane.QUESTION_MESSAGE);
System.out.println("User chose " + znm.getValue());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}

class ZipNumberModel extends SpinnerNumberModel {

private ArrayList<Integer> zipCodes;
private int index = 0;

ZipNumberModel() {
zipCodes = new ArrayList<Integer>();
int zip = 10000;
for (int jj = 1; jj < 4; jj++) {
for (int ii = jj * zip; ii < jj * zip + 10; ii++) {
zipCodes.add(new Integer(ii));
}
}
}

@Override
public Object getValue() {
return zipCodes.get(index);
}

@Override
public Object getNextValue() {
if (index < zipCodes.size()-1) {
index++;
} else {
index = 0;
}
return zipCodes.get(index);
}

@Override
public Object getPreviousValue() {
if (index > 0) {
index--;
} else {
index = zipCodes.size()-1;
}
return zipCodes.get(index);
}
}

关于java - JPanel 元素没有出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17006150/

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