简体   繁体   中英

paintComponent with graphics

I'm trying to create a JFrame with 1 image and a text box. I've managed to figure out the text box, but I can't figure the image painting. So far I have this:

public class Patcher extends JFrame {

private static final long serialVersionUID = -431324639043295668L;
private JPanel contentPane;

private static JTextArea textArea;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Patcher frame = new Patcher();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Patcher() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 319);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    textArea.setBackground(new Color(240, 240, 240));
    textArea.setText("123");
    contentPane.add(textArea, BorderLayout.SOUTH);

    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.NORTH);
    Image img = ImageIO.read(new URL(ClassLoader.getSystemResource("Icon_Entrey_21.png"), "img"));
    ImageObserver imgobs;
    panel.paintComponent(Graphics.drawImage(img, 0, 0, null));
    }
}

The idea is that I create a JPanel , declare an Image using a ClassLoader and try to draw it using paintComponent() method with Graphics as an argument. What am I doing wrong here?

Also I've tried creating a new Graphics() but that throws an error, as well.

  1. You should never explicitly call the paintComponent method of any component. If you want to do custom painting, then you would instead create a custom class that extends JPanel/JComponent and @Override the paintComponent method. See more at Performing Custom Painting

     JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(...); } // also override getPreferredSize() }; 
  2. The easiest, and probably more correct, solution is just to use a JLabel and an ImageIcon instead of trying to custom painting.

     Image img = ImageIO.read(new URL(ClassLoader.getSystemResource("Icon_Entrey_21.png"), "img")); JLabel panel = new JLabel(new ImageIcon(img)); contentPane.add(panel, BorderLayout.NORTH); 

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