JAVA 的GUI问题
1》为什么只有上下拉窗口面板2区的文本框才能显示出来?2》为什么键盘事件不执行?
3》编程要求在图片里,编程在下面已写好,希望各位大佬改改.
package javaapplication17;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Administrator
*/
public class W2 extends JFrame implements ActionListener, KeyListener,FocusListener{
JTextField t1;
JButton b1;
ActionListener t1t;
JTextField a[];
JPanel p2 ;
JLabel j1;
int m;
String str;
String s1;
W2() {
j1=new JLabel("拼写单词");
t1 = new JTextField(15);
// t1.setText(null);
//t1.addFocusListener(this);
b1 = new JButton("确定");
// b1.addFocusListener(this);
JPanel p1 = new JPanel();
p2 = new JPanel();
p1.add(t1);
p1.add(b1);
p2.add(j1);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.CENTER);
setVisible(true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
t1.addActionListener(this);
b1.addActionListener(this);
// p2.removeAll();//p2每次刷新布局
}
public void actionPerformed(ActionEvent e) {
if((JButtone.getSource()==b1){//文本框1得到监听*/
str = t1.getText();//得到文本框字符串
m = str.length();
getNew(str);
set2(get2(m));//
a[0].addFocusListener(this);
}
}
public void set2(JTextField[] a){
p2.removeAll();
//面板2上加文本框
for (int i = 0; i < a.length; i++) {
a[i].setVisible(true);
p2.add(a[i]);
t1.setText(null);
//a[0].addFocusListener(this);
}
}
public void getNew(String s) {//打乱字符串
String s1 = "";
StringBuffer s2 = new StringBuffer(s);
int m = s2.length();
for (int k = 0; k < m; k++) {
int t3 = (int) (Math.random() * s2.length());
char c = s2.charAt(t3);
s1 = s1 + c;//字符串并置
s2 = s2.deleteCharAt(t3);
}
this.s1 = s1;
}
public JTextField[] get2(int n) {//文本框设置
a = new JTextField[n];
for (int i = 0; i < n; i++) {
a[i]=new JTextField(2);
a[i].setText("" + s1.charAt(i));//setText参数类型为string,但charAt返回字符型,并置空的形成string
a[i].setEditable(false);
a[i].addKeyListener(this);
//a[0].addFocusListener(this);
}
return a;
}
public void focusGained(FocusEvent e){
}
public void focusLost(FocusEvent e){
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
JTextField c=(JTextField)(e.getSource());
int d=-1;
if((e.getKeyChar()+"").equals("←"+"")){
for(int k=0;k<a.length;k++){
if(a[0]==c){//第一个文本框不能再往左了,判别那个地方获得焦点;
d=k;
break;
}
}
if(d!=0){
String str=a[d].getText();
a[d].setText(a[d-1].getText());
a[d-1].setText(str);
a[d-1].requestFocus();
}
}else if((e.getKeyChar()+"").equals("→"+"")){
for(int k=0;k<a.length;k++){
if(a[0]==c){//第一个文本框不能再往左了,判别那个地方获得焦点;
d=k;
break;
}
}
if(d!=a.length-1){
String str=a[d].getText();
a[d].setText(a[d+1].getText());
a[d+1].setText(str);
a[d+1].requestFocus();
}
}
String s4="";
for(int i=0;i<a.length;i++){
String s5=a[i].getText();
s4=s4+s5;
}
if(s4.equals(s1)){
j1.setText("成功了");
for(int k=0;k<a.length;k++){
a[k].removeKeyListener(this);
a[k].removeFocusListener(this);
t1.requestFocus();
t1.setText(null);
}
t1.requestFocus();
t1.setText(null);
}
}
public void keyPressed(KeyEvent e) {
}
}