这是我可以在框架上移动矩形的简单代码的一部分。当我尝试在框架上添加按钮和文本字段时,这些组件不可见或我看不到矩形。我还尝试先添加它们JPanel
,然后在框架上添加面板。组件可见,但矩形不可见。有什么建议么?
public class Buffer extends JPanel implements KeyListener,ActionListener{
public static JFrame frame;
public static JButton button;
public static JTextField field;
public int x;
public int y;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x,y,20,20);
}
public static void main(String args[]){
Buffer z=new Buffer();
frame=new JFrame();
button=new JButton();
field=new JTextField();
frame.setLayout(new BorderLayout());
button.setPreferredSize(new Dimension(20,20));
button.setText("XY");
button.addActionListener(z);
field.setPreferredSize(new Dimension(100,20));
field.setEditable(false);
frame.setSize(500,500);
frame.setVisible(true);
frame.setFocusable(true);
frame.addKeyListener(z);
frame.setTitle("TEST");
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x=x+10;
repaint();
}
}
public void actionPerformed(ActionEvent e){
field.setText("X- "+x+" Y- "+y);
frame.requestFocusInWindow();
}
}
}