我正在创建一个简单的程序,它允许我通过按JButton向JTextField添加单个字符。在这个程序中,我有一个名为words的字符串数组,我有一个字符串名称word,它允许我从单词数组中随机选择单词。我正在使用for 循环来绘制JTextFields。JTextField 的数量取决于单词的长度
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Random;
public class secondTab extends JFrame
{
JTabbedPane Pane = new JTabbedPane();
JPanel second = new JPanel();
JButton guess1 = new JButton();
Random r = new Random();
JTextField Text[] = new JTextField[10];
JButton A = new JButton();
String words[] = {"JAVA" , "FLOAT" , "MAIN" , "STATIC", "FINAL", "PRIVATE" , "CHAR", "BOOLEAN" , "CASE"}; // An array to put the words
String word = words[r.nextInt(words.length)];
int i;
public static void main(String args[])
{
//construct frame
new secondTab().show();
}
public secondTab()
{
// code to build the form
setTitle("Adding Character");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
// position tabbed pane
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
Pane.setForeground(Color.YELLOW);
Pane.setBackground(Color.MAGENTA);
getContentPane().add(Pane, gridConstraints);
getContentPane().setLayout(new GridBagLayout());
second.setLayout(new GridBagLayout());
guess1.setText("New Word");
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
second.add(guess1, gridConstraints);
for( i = 1; i <=word.length(); i++)
{
Text[i] = new JTextField();
Text[i].setPreferredSize(new Dimension(80, 80));
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
second.add(Text[i]);
}
A.setText("A");
A.setPreferredSize(new Dimension(80, 80));
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
A.setHorizontalAlignment(SwingConstants.CENTER);
second.add(A, gridConstraints);
我有一个名为A的 JButton ,这个 JButton 有一些错误。我有一个名为choice的字符串,它只包含一个字符“Ä”。所以,我在我的 Jbutton 中添加了一些方法,它将字符串选择与单词 (上面随机选择的单词)进行比较。每当它在word中找到“A”时,它必须将 Jtextfield 中的“A”绘制到特定位置,但它不绘制......
A.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String choice = "A";
if (i < word.length() & i < choice.length())
{
if (word.charAt(i) == choice.charAt(i))
{
Text[i].setText(choice.charAt(i) + " ");
}
}
}
});
// Action Performed method for the JButton guess1
guess1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
new secondTab().show();
}
});
Pane.addTab("Game ", second);
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 *
(screenSize.height - getHeight())), getWidth(), getHeight());
}
}
请从 0.41 秒开始查看该视频http://www.youtube.com/watch?v=Tx5QsET9IWs 。我想做同样的事情...
谢谢....