我是一个编程新手,并且已经成功地使用这个网站来学习和克服障碍。在我提出我的新问题之前,让我首先感谢所有给予如此巨大帮助的人。
我正在做我的第一个项目,并解决了阻止程序运行的小问题。但是,问题的解决方案是通过猜测找到的,我非常想知道为什么。这应该是一个可变范围问题。这是程序的一个片段?
public class AlladinLamp {
JMenuBar jmBar;
JComboBox runners, raceDiv, days, months;
JButton horseList, ok, clear;
JTextField[] jtxt;
JTextField raceName;
JTextArea message;
String status;
JDialog dialog;
JPanel table, data, jp, middle;
JFrame jfr;
String[] hNam ; // string array holding horse names
int[] hNum, hVal;
int reducedFNH, id, vp, day, month, fnh, dv; // fnh is the number of horses in the
race
Processes processes;
GridBagLayout gbLayout;
GridBagConstraints gbc;
...
public AlladinLamp()
{
...
public ActionListener horseListActionListener = new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
Toolkit myKit = dialog.getToolkit();
Dimension dialSize = myKit.getScreenSize();
dialog.setLocation( dialSize.width/2, dialSize.height/4 );
dialog.setSize( 260, 380 );
dialog.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
jp.setLayout( gbLayout );
jtxt = new JTextField[ fnh ]; <--- array of textfields for the horse names
JLabel label;
String str;
for( int i = 0; i < fnh; i++ )
{
gbc.gridx = 0;
gbc.gridy = i;
str = new Integer( i+1 ) + ".";
label = new JLabel( str );
jp.add( label, gbc );
gbc.gridx = 1;
gbc.gridy = i;
gbc.ipady = 4;
gbc.insets = new Insets(4,0,0,0);
jtxt[i] = new JTextField(15);
jp.add( jtxt[i], gbc );
}
JPanel buttonPanel = new JPanel();
ok = new JButton( "OK" );
ok.addActionListener( okActionListener );
buttonPanel.add( ok );
clear = new JButton ( "CLEAR" );
clear.addActionListener( clearActionListener );
buttonPanel.add( clear );
JScrollPane jscr = new JScrollPane( jp );
dialog.add( jscr, BorderLayout.CENTER );
dialog.add( buttonPanel, BorderLayout.SOUTH );
dialog.setVisible( true );
}
};
...
public ActionListener okActionListener = new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
hNam = new String[ fnh ];
hNum = new int[ fnh ];
hVal = new int[ fnh ];
for( int i = 0; i < fnh; i++ )
{
hNam[i] = jtxt[i].getText();
hNum[i] = reduce( i + 1 );
hVal[i] = nameValue( hNam[i] );
}
System.out.println( Arrays.toString(hNam) );
System.out.println( Arrays.toString(hVal) );
setID( hNam );
dialog.setVisible( false );
}
};
...
该程序基本上是一个接受多种输入的 GUI。horselist 按钮的侦听器构建了一个 jDialog,它接受比赛中马名的输入。
OK 按钮的侦听器从文本字段中检索这些名称并将它们存储在 hNam 数组中。现在,当我将初始化 hNam、hVal 和 hNum 的前三行移动到构造函数中时,我得到一个源自下一条语句的 ArrayIndexOutOfBounds 异常hNam[i] = jtxt[i].getText();
为什么呢???