簡體   English   中英

帶圖形的paintComponent

[英]paintComponent with graphics

我正在嘗試創建一個包含1張圖片和一個文本框的JFrame 我設法弄清楚了文本框,但無法弄清楚圖像。 到目前為止,我有這個:

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

我的想法是創建一個JPanel ,使用ClassLoader聲明一個Image然后嘗試使用帶有Graphics作為參數的paintComponent()方法來繪制它。 我在這里做錯了什么?

我也嘗試創建一個new Graphics()但是也會引發錯誤。

  1. 您絕對不應顯式調用任何組件的paintComponent方法。 如果要進行自定義繪畫,則可以創建一個自定義類,該類擴展了JPanel/JComponent@Override paintComponent方法。 執行自定義繪畫中查看更多信息

     JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(...); } // also override getPreferredSize() }; 
  2. 最簡單且可能更正確的解決方案是僅使用JLabelImageIcon而不是嘗試自定義繪畫。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM