I am making a small game and need to use text fields. I use double buffering and a high frame rate, so when I try to use JTextFields they are don't appear on the screen or appear flickering. I tried using regular TextFields and they worked fine, except that sometimes when the game starts the TextFields don't appear on the screen and I have to minimize and maximize the window so they can appear. Please help me either making the JTextFields working on that or the regular TextFields to appear all the times. I am currently using the regular TextFields but would like to use the JTextFields. Here's the code to demonstrate the problem, if you run it like that you can't even see the JTextField and if you uncoment the repaint line you can see it but with an awful flickering.
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class FieldIssue extends JPanel
{
private Graphics g;
private Graphics g2;
private BufferedImage offImg;
private JTextField txt;
public static void main(String argv[])
{
FieldIssue f = new FieldIssue();
}
public FieldIssue()
{
createScreen();
loop();
}
public void createScreen()
{
txt = new JTextField("Hello.",20);
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setSize(800,600);
frame.setResizable(false);
frame.setVisible(true);
g2 = frame.getGraphics();
offImg = new BufferedImage(800,600,BufferedImage.TYPE_INT_ARGB);
g = offImg.getGraphics();
panel.add(txt);
}
private void loop()
{
while(true)
{
draw();
try {Thread.sleep(10);} catch(InterruptedException e) {}
}
}
private void draw()
{
g.setColor(Color.WHITE);
g.fillRect(0, 0, 800, 600);
g.setColor(Color.BLACK);
g.fillOval((int)((System.currentTimeMillis()%8000)/10),
(int)((System.currentTimeMillis()%6000)/10),50,50);
g2.drawImage(offImg,0,0,this);
//txt.repaint();
}
}
Thank you for the help =).