2013-07-15 53 views
1

下面是我可以在一个框架上移动矩形的简单代码的一部分。当我尝试在框架上添加按钮和文本字段时,这些组件不可见,或者看不到矩形。我也尝试在JPanel上添加它们,然后在框架上添加面板。组件是可见的,但矩形不是。有什么建议么?无法添加JFrame和JTextField

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(); 
} 
    } 
    } 

回答

3
  • JFrame默认从未反应以KeyEvent,意味着frame.setFocusable(true);

  • 必须setFocusable(true)JPanel,然后KeyEventsKeyListener被触发一个期望的事件(一个或多个)


1

要添加组件到框架,您必须获取框架的容器,然后将组件添加到容器。

例如一个范例程序

import javax.swing.*; 
import java.awt.*; 

public class Test 
{ 
JFrame f; 
Container c; 
JButton btn; 
JTextField tf; 
public Test() //constructor 
{ 

f=new JFrame("Swah!"); 
f.setBounds(50,50,300,300); //position and dimension of frame 

c=f.getContentPane();// getting container of the frame 
c.setLayout(new FlowLayout()); //if you do not use layout then only one 
//component will be visible to you. 

btn=new JButton("OK"); 
tf=new JTextField(20); 

c.add(btn); 
c.add(tf); 

f.setVisible(true); 
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); 
} 

public static void main(String []val) 
{ 
Test tobj=new Test(); 
} 

} 

可以根据你输出使用布局,有喜欢的FlowLayout,GridLayout的和的GridBagLayout布局。

希望这对你有所帮助。