已输入按键功能但无法正常运行
Keypressed function entered but not functioning correctly
我正在尝试将关键侦听器分配给在 for 循环中创建的按钮。出于某种原因,我无法让按钮在按键时更改背景颜色。正在到达 System.out.println("passed");
行,所以我不确定发生了什么。
很多意大利面条代码..请让我知道我还应该添加什么。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
public void addNotify() {
super.addNotify();
requestFocus();
}
// main rows of keys
public String rowOne[] = {
"~",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"h"
};
public String rowTwo[] = {
"Tab",
"Q",
"W",
"E",
"R",
"T",
"Y",
"U",
"I",
"O",
"P",
"[",
"]",
"\"
};
public String rowThree[] = {
"Caps",
"A",
"S",
"D",
"F",
"G",
"H",
"J",
"K",
"L",
":",
"'",
"Enter"
};
public String rowFour[] = {
"Shift",
"Z",
"X",
"C",
"V",
"B",
"N",
"M",
",",
".",
"?",
" ^"
};
public String rowFive[] = {
" ",
"<",
"v",
">"
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public String shiftless[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"=",
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
};
// Account for special chars
public String specialChars[] = {
"~",
"-",
"+",
"[",
"]",
"\",
";",
".",
"?"
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(1000, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 5));
top.add(context1);
top.add(context2);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
@Override
public void keyPressed(KeyEvent press) {
Object current = press.getKeyChar();
System.out.println("passed");
for (int i = 0; i < rowOne.length; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowTwo.length; i++) {
if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowThree.length; i++) {
if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFour.length; i++) {
if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFive.length; i++) {
if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.BLACK);
}
}
repaint();
} // !keyPressed(...)
// called when a button is released
@Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource();
for (int i = 0; i < 10; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
}
}
repaint();
} // !keyReleased(...)
@Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
编辑 1:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
public void addNotify() {
super.addNotify();
requestFocus();
}
// main rows of keys
public char rowOne[] = {
'~',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
'-',
'+',
'h'
};
public char rowTwo[] = {
//'Tab', TODO: Make these separate objects
'Q',
'W',
'E',
'R',
'T',
'Y',
'U',
'I',
'O',
'P',
'[',
']',
'\'
};
public char rowThree[] = {
//'Caps',
'A',
'S',
'D',
'F',
'G',
'H',
'J',
'K',
'L',
':',
'"',
//'Enter'
};
public char rowFour[] = {
//'Shift',
'Z',
'X',
'C',
'V',
'B',
'N',
'M',
',',
'.',
'?',
//' ^'
};
public char rowFive[] = {
//' ',
'<',
'v',
'>'
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public char shiftless[] = {
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
'-',
'=',
'q',
'w',
'e',
'r',
't',
'y',
'u',
'i',
'o',
'p',
'[',
']',
'\',
'a',
's',
'd',
'f',
'g',
'h',
'j',
'k',
'l',
';',
'z',
'x',
'c',
'v',
'b',
'n',
'm',
',',
'.',
'/'
};
// Account for special chars
public char specialChars[] = {
'~',
'-',
'+',
'[',
']',
'\',
';',
'.',
'?'
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(1000, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 5));
top.add(context1);
top.add(context2);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
@Override
public void keyPressed(KeyEvent press) {
char current = press.getKeyChar();
System.out.println("passed");
for (int i = 0; i < rowOne.length; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.BLACK);
}
}
// System.out.println(s1 == s2);
// System.out.println(s1.equals(s2));
for (int i = 0; i < rowTwo.length; i++) {
if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowThree.length; i++) {
if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFour.length; i++) {
if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFive.length; i++) {
if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.BLACK);
}
}
repaint();
} // !keyPressed(...)
// called when a button is released
@Override
public void keyReleased(KeyEvent release) {
char current = release.getSource();
for (int i = 0; i < 10; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
}
}
repaint();
} // !keyReleased(...)
@Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
您的逻辑的一个根本问题是 keyPressed
中的 if 语句永远不会为真,这就是打印语句有效但背景颜色没有变化的原因。 if (current == rowOne[i])
之类的 if 语句永远不会为真的原因是 current
的类型是 Object
,但你要给它赋值 press.getKeyChar()
,这是类型 char
。我猜这会导致 auto-boxing, meaning that the char
value then becomes a Character
object. As for rowOne[i]
, since the values in rowOne
are all of type String
, these are - like for current
- always objects and not primitives. Directly comparing objects with ==
only determines if the objects are the same object, meaning that you are comparing the references and not the value. To compare objects, you need to use a.equals(b)
to correctly compare the values of the objects (see "Difference between == and .equals() method in Java").
在您的情况下,这两个问题共同导致 if 语句无法按预期工作。我建议将 current
声明为 char
,并使您的数组包含 char
原语而不是 String
对象(例如 'A'
而不是 "A"
).在这种情况下,您可以使用 ==
直接比较两个 char
基元,这至少可以解决该问题。
希望这能引导您朝着正确的方向前进。
我正在尝试将关键侦听器分配给在 for 循环中创建的按钮。出于某种原因,我无法让按钮在按键时更改背景颜色。正在到达 System.out.println("passed");
行,所以我不确定发生了什么。
很多意大利面条代码..请让我知道我还应该添加什么。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
public void addNotify() {
super.addNotify();
requestFocus();
}
// main rows of keys
public String rowOne[] = {
"~",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"h"
};
public String rowTwo[] = {
"Tab",
"Q",
"W",
"E",
"R",
"T",
"Y",
"U",
"I",
"O",
"P",
"[",
"]",
"\"
};
public String rowThree[] = {
"Caps",
"A",
"S",
"D",
"F",
"G",
"H",
"J",
"K",
"L",
":",
"'",
"Enter"
};
public String rowFour[] = {
"Shift",
"Z",
"X",
"C",
"V",
"B",
"N",
"M",
",",
".",
"?",
" ^"
};
public String rowFive[] = {
" ",
"<",
"v",
">"
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public String shiftless[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"=",
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
};
// Account for special chars
public String specialChars[] = {
"~",
"-",
"+",
"[",
"]",
"\",
";",
".",
"?"
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(1000, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 5));
top.add(context1);
top.add(context2);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
@Override
public void keyPressed(KeyEvent press) {
Object current = press.getKeyChar();
System.out.println("passed");
for (int i = 0; i < rowOne.length; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowTwo.length; i++) {
if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowThree.length; i++) {
if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFour.length; i++) {
if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFive.length; i++) {
if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.BLACK);
}
}
repaint();
} // !keyPressed(...)
// called when a button is released
@Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource();
for (int i = 0; i < 10; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
}
}
repaint();
} // !keyReleased(...)
@Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
编辑 1:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
public void addNotify() {
super.addNotify();
requestFocus();
}
// main rows of keys
public char rowOne[] = {
'~',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
'-',
'+',
'h'
};
public char rowTwo[] = {
//'Tab', TODO: Make these separate objects
'Q',
'W',
'E',
'R',
'T',
'Y',
'U',
'I',
'O',
'P',
'[',
']',
'\'
};
public char rowThree[] = {
//'Caps',
'A',
'S',
'D',
'F',
'G',
'H',
'J',
'K',
'L',
':',
'"',
//'Enter'
};
public char rowFour[] = {
//'Shift',
'Z',
'X',
'C',
'V',
'B',
'N',
'M',
',',
'.',
'?',
//' ^'
};
public char rowFive[] = {
//' ',
'<',
'v',
'>'
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public char shiftless[] = {
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
'-',
'=',
'q',
'w',
'e',
'r',
't',
'y',
'u',
'i',
'o',
'p',
'[',
']',
'\',
'a',
's',
'd',
'f',
'g',
'h',
'j',
'k',
'l',
';',
'z',
'x',
'c',
'v',
'b',
'n',
'm',
',',
'.',
'/'
};
// Account for special chars
public char specialChars[] = {
'~',
'-',
'+',
'[',
']',
'\',
';',
'.',
'?'
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(1000, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 5));
top.add(context1);
top.add(context2);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
currentButton.addKeyListener(this);
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
@Override
public void keyPressed(KeyEvent press) {
char current = press.getKeyChar();
System.out.println("passed");
for (int i = 0; i < rowOne.length; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.BLACK);
}
}
// System.out.println(s1 == s2);
// System.out.println(s1.equals(s2));
for (int i = 0; i < rowTwo.length; i++) {
if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowThree.length; i++) {
if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFour.length; i++) {
if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.BLACK);
}
}
for (int i = 0; i < rowFive.length; i++) {
if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.BLACK);
}
}
repaint();
} // !keyPressed(...)
// called when a button is released
@Override
public void keyReleased(KeyEvent release) {
char current = release.getSource();
for (int i = 0; i < 10; i++) {
if (current == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
} else if (current == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
} else if (current == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
} else if (current == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
} else if (current == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
}
}
repaint();
} // !keyReleased(...)
@Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
您的逻辑的一个根本问题是 keyPressed
中的 if 语句永远不会为真,这就是打印语句有效但背景颜色没有变化的原因。 if (current == rowOne[i])
之类的 if 语句永远不会为真的原因是 current
的类型是 Object
,但你要给它赋值 press.getKeyChar()
,这是类型 char
。我猜这会导致 auto-boxing, meaning that the char
value then becomes a Character
object. As for rowOne[i]
, since the values in rowOne
are all of type String
, these are - like for current
- always objects and not primitives. Directly comparing objects with ==
only determines if the objects are the same object, meaning that you are comparing the references and not the value. To compare objects, you need to use a.equals(b)
to correctly compare the values of the objects (see "Difference between == and .equals() method in Java").
在您的情况下,这两个问题共同导致 if 语句无法按预期工作。我建议将 current
声明为 char
,并使您的数组包含 char
原语而不是 String
对象(例如 'A'
而不是 "A"
).在这种情况下,您可以使用 ==
直接比较两个 char
基元,这至少可以解决该问题。
希望这能引导您朝着正确的方向前进。