我遇到以下问题:
package keyz;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class KeyPractise extends JFrame{
public static int x;
public static int z;
public static float hue;
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame window = new JFrame("Color Square");
KeyPractise content = new KeyPractise((window.getWidth() / 2), window.getHeight() / 2);
window.setContentPane(content);
window.setSize(600,600);
window.setLocation(400,400);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
content.requestFocusInWindow();
content.setBackground(Color.WHITE);
}
public KeyPractise (int xx, int zz){
xx = x;
zz = z;
Listener listener = new Listener();
addKeyListener(listener);
}
private class Listener implements KeyListener{
@Override
public void keyPressed(KeyEvent evt) {
// TODO Auto-generated method stub
int key = evt.getKeyCode();
if (key == KeyEvent.VK_UP){
if ((hue + 0.00392) < 1.00000){
hue += 0.00392;
}
if ((hue + 0.00392) >= 1.00000){
hue -= hue;
}
repaint();
}
}//keyPressed
@Override
public void keyReleased(KeyEvent evt) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent evt) {
// TODO Auto-generated method stub
}
public void paintComponent(Graphics g) {
g.setColor(Color.getHSBColor(hue, 1.0F, 1.0F));
g.fillRect(x, z, 50, 50);
}
}
}
我得到了这个例外:
线程中的异常&#34; main&#34; java.lang.IllegalArgumentException:向容器添加窗口
我认为问题在于我正在为容器添加一个窗口。&#34; 如果是这样,可以采取哪种其他方式来避免这种情况?
另外,我被告知将setBackground(Color);
方法添加到KeyPractise
对象构造函数然后将super.paintComponent(g);
添加到paintComponent()
而不是我所做的是正确的样式。但是当我这样做时,我在Eclipse中遇到了这个错误:
对于Object
类型,未定义paintComponent(Graphics)方法
在主子程序中使用content.setBackground()
是不是很糟糕?
谢谢!
答案 0 :(得分:0)
我已经改变了以下行
public class KeyPractise extends JFrame{
到
public class KeyPractise extends Container{
现在正在运作...... 请检查