0

can someone help me to know why the whole jtextfield is not visible when adding it to a jpanel that has a painted image icon? here is my code for the sample. thanks :) without typing anything on it, only part of it is visible.

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

public class GraphicsMain extends JFrame{

    Panel panel = new Panel();
    JTextField tf = new JTextField(10);

    public GraphicsMain() {
        tf.setBackground(Color.red);
        panel.setLayout(new FlowLayout());
        panel.add(tf);
        this.add(panel);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
    }

    public static void main(String[] args) {
        new GraphicsMain();
    }
}

class Panel extends JPanel{
    int pixel;
    Image image;

    public Panel() {
        //#1 create icon
        image = new ImageIcon("sample.png").getImage();
        this.setPreferredSize(new Dimension(250,250));
    }
    //#2 paint
    public void paint(Graphics g){
        Graphics g2d = (Graphics2D)g;
        g2d.drawImage(image, 0, 0, null);
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Bjay
  • 1

1 Answers1

1

You've broken the paint chain (responsibility).

Take a look at:

to get a better understand of how painting works and how you're suppose to use.

You "could" try and fix it by doing something like...

@Override
public void paint(Graphics g){
    super.paint(g);
    Graphics g2d = (Graphics2D)g;
    g2d.drawImage(image, 0, 0, this);
}

but this is just painting the image over the top of what was previously paint.

You "could" try and fix it by doing something like...

@Override
public void paint(Graphics g){
    Graphics g2d = (Graphics2D)g;
    g2d.drawImage(image, 0, 0, this);
    super.paint(g);
}

But now the image isn't getting painted (because part of the paint workflow is to fill the component with the background color of the component)

Instead, you need to inject your code into a different point in the paint process.

You should be using paintComponent, as it's primary responsibility is to "paint the component", this is called before the children are painted, so it's a great place for painting the background, for example...

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics g2d = (Graphics2D)g;
    g2d.drawImage(image, 0, 0, this);
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366