[英]Cannot add JFrame and JTextField
這是我的簡單代碼的一部分,我可以在框架上移動矩形。 當我嘗試在框架上添加按鈕和文本字段時,這些組件不可見或我看不到矩形。 我還嘗試首先在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
做出反應,這意味着frame.setFocusable(true);
必須為JPanel
設置setFocusable(true)
,然后KeyListener
KeyEvents
將觸發所需的事件
不要將KeyListener
用於Swing JComponent
,而是使用(最可伸縮,可設置的) KeyBindings
( 例如 )
對BorderLayout使用常量 ,只能看到一個JComponent
,放在第5個中。 區
要向框架添加組件,您必須獲取框架的Container,然后將組件添加到容器中。
例如一個示例程序
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這樣的布局。
希望這對你有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.