这是我可以在框架上移动矩形的简单代码的一部分。当我尝试在框架上添加按钮和文本字段时,这些组件不可见或我看不到矩形。我还尝试先在 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();
}
}
}
最佳答案
<JFrame
默认情况下永远不会对KeyEvent
使用react,这意味着frame.setFocusable(true);
必须为
JPanel
setFocusable(true)
,然后KeyListener
的KeyEvents
会触发一个期望的事件
不要使用
KeyListener
对于Swing JComponent
,使用(最可调用、可设置)KeyBindings
相反(for example)use constant for BorderLayout ,只有一个
JComponent
可见,放在第 5 个中。领域
关于java - 无法添加 JFrame 和 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649885/