编写一个java程序,当按键盘的r、g、b键时,分别设置窗体背景色为红、绿、蓝三种色
展开全部
import java.awt.Color;
import java.awt.Container;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDialog;
public class MyTest {
static JDialog dialog = new JDialog();
Container cp = new Container();
public static void main(String[] args) {
MyTest mytest = new MyTest();
dialog.setSize(300, 200);
dialog.setLocationRelativeTo(null);
dialog.setTitle("测试");
dialog.addKeyListener(mytest.new MyKeyListener());
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialog.dispose();
}
});
dialog.setVisible(true);
}
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
char key = e.getKeyChar();
cp = dialog.getContentPane();
cp.setLayout(null);
switch (key) {
case 'r':
cp.setBackground(Color.red);
break;
case 'g':
cp.setBackground(Color.green);
break;
case 'b':
cp.setBackground(Color.blue);
break;
}
System.out.println("你按了【" + key + "】键");
}
}
}
更多追问追答
追问
颜色没有变
追答
你在电脑上双击这个jar包,效果就是这样的。除非你有自己修改了代码,也有可能你键盘的模式为大写的,我代码没有判断大小写,你可以自己改。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询