简体   繁体   中英

Cannot add JFrame and JTextField

Here's part of my simple code where I can move rectangle on a frame. When I try to add button and text field on frame, these components are not visible or I can't see rectangle. I also tried adding them first on JPanel and then adding panel on frame. Components were visible but rectangle wasn't. Any suggestions?

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 by default never to react to KeyEvent , meaning frame.setFocusable(true);

  • have to setFocusable(true) for JPanel , then KeyEvents from KeyListener are firing an desired event(s)


To add components to the frame you have to get the Container of the frame then you add the components to the container.

for example a sample program

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

}

you can use layouts according to you output, there are layouts like Flowlayout,GridLayout and GridBagLayout.

Hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM