我需要在 jtextfield 旁边的 jcombobox 旁边构建一个 jlabel。JTextfield 必须只接受数字。jtextfield 中的文本应该存储在一个字符串中,并且选择的元素也应该存储在不同的字符串中。如果我可以添加一个 jbutton 以便在单击按钮时解析所有选择,那将是理想的。我目前正在使用这个未完成的代码,但它不会工作。有人可以建议所需的补充吗?提前致谢
public class constraints {
private static JTextField tField;
private MyDocumentFilter documentFilter;
private JLabel amountLabel;
private static String amountString = "Select Quantity (in ktones): ";
public static String str = "" ;
private void displayGUI()
{
JFrame frame = new JFrame("Constraints");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
amountLabel = new JLabel(amountString);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
tField = new JTextField(10);
amountLabel.setLabelFor(tField);
String[] petStrings = { "Less", "Equal", "More"};
JComboBox petList = new JComboBox(petStrings) ;
petList.setSelectedIndex(3);
petList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JComboBox cb = (JComboBox)event.getSource();
String petName = (String)cb.getSelectedItem();
System.out.println("petName");
}
});
((AbstractDocument)tField.getDocument()).setDocumentFilter(
new MyDocumentFilter());
contentPane.add(amountLabel);
contentPane.add(petList);
contentPane.add(tField);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
new constraints().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class MyDocumentFilter extends DocumentFilter
{
@Override
public void insertString(DocumentFilter.FilterBypass fp
, int offset, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;
for (int i = 0; i < len; i++)
{
if (!Character.isDigit(string.charAt(i)))
{
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.insertString(fp, offset, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}
@Override
public void replace(DocumentFilter.FilterBypass fp, int offset
, int length, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;
for (int i = 0; i < len; i++)
{
if (!Character.isDigit(string.charAt(i)))
{
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.replace(fp, offset, length, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}
}