Adding textfield to Graphics in java

瘦欲@ 提交于 2019-12-10 03:29:09

问题


Does anyone know how to add JTextField into Graphics name bufferstrategy.getDrawGraphics? Tryed to pain it into graphics, something like this:

private JTextField Input = new JTextField();
BufferStrategy bs = getBufferStrategy();

if (bs == null) {
    createBufferStrategy(3);
    return;
}

final Graphics gCommands = bs.getDrawGraphics();
Graphics gCC = bs.getDrawGraphics();
Input.requestFocus();
Input.paint(gCC);
Input.setBounds(800,250, 350,20);
Input.setBorder(BorderFactory.createLineBorder(Color.BLACK, 0));
Input.setEditable(true);
Input.setBackground(getBackground());
Input.setForeground(getForeground());
Input.addKeyListener(key);

But, eventhough it displayed, I could not edit it. Even the Input.setBounds(800,250, 350,20) did not work. This method that is written above, is being called inside a gameloop. Can anyone help me?


回答1:


Painting a component on a Graphics won't make it a "live" component. Components need to be added to a valid container that is attached to a native peer before they become live.

At the moment, the only thing you are doing is producing a "rubber stamp"/image of the component on the surface of the graphics context.

There are some tricks to this, as the painting process expects that the component is attached to a valid, native peer.

First, you must prepare the field...

Input.setBounds(800,250, 350,20);
Input.setBorder(BorderFactory.createLineBorder(Color.BLACK, 0));
Input.setEditable(true);
Input.setBackground(getBackground());
Input.setForeground(getForeground());

Then you need to paint it. The field will not automatically repaint, again, this has to do with the field not been attached to a native peer...

Input.printAll(gCC);

If you want a life component, you are going to have to add the component to the container. This may be problematic when using a buffer strategy...

Swing components are already double buffered.



来源:https://stackoverflow.com/questions/16656400/adding-textfield-to-graphics-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!