2011-04-19 16 views
1

我有簡單地擴展JPanel並重寫的paintComponent方法作爲這樣的類:如何創建一個圖像面板並在NetBeans上使用它?

@Override 
public void paintComponent(Graphics g) 
{ 
    Image img = new ImageIcon("Images/Background1.jpg").getImage(); 
    g.drawImage(img, 0, 0, null); 
} 

我將其添加到在NetBeans托盤,但是,從UI編輯器沒有顯示的背景圖像既不也不當我運行該程序通過NetBeans。我究竟做錯了什麼?我很想在托盤上放置這個圖像面板。

回答

2

如果您繪製在位置的圖像(0,0),而不是縮放圖像以適合窗口,那麼有沒有理由這樣做的風俗畫。只需使用圖像創建ImageIcon並將圖像添加到JLabel並將標籤添加到框架。

做你的自定義繪畫的可能的問題是,你沒有給組件一個首選的大小,所以面板的大小是0,沒有什麼可以繪畫。

除非您在圖像上進行縮放或其他圖形功能,否則可以使用JLabel來簡化繪製和調整大小。

+0

@camickr:謝謝。 – mre 2011-04-19 23:49:32

+0

啊,尺寸問題可能是我會嘗試改變這一點。我使用面板的原因是我想在後面添加其他面板。 – Hans 2011-04-22 01:06:37

+1

@Hans,您也可以將組件添加到JLabel。只需設置標籤的佈局管理器即可。 – camickr 2011-04-22 03:46:31

1

請參閱從Chee K. Yap這個例子:

// MyPanel.java 
// -- continuing the example of EmptyFrame1.java 

/** 
* Our main goal is to add panels to a frame. 
* In swing, panels are extensions of JPanels, and the main 
* method we need to override is the "paintComponent" method: 
* 
* class MyPanel extends JPanel { 
* // override the paintComponent method 
* public void paintComponent(Graphics g) { 
*  super.paintComponent(g); // calls the default method first! 
*  g.drawString("Hello Panel!", 75, 100); // our own renderings... 
* } //paintComponent 
* } //class MyPanel 
* 
* A JFrame has several layers, but the main one for 
* adding components is called "content pane". 
* We need to get this pane: 
* Container contentPane = frame.getContentPane(); 
* Then add various components to it. In the present 
* example, we add a JPanel: 
* contentPane.add(new MyPanel()); 
**/ 

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

// text panel 

class textPanel extends JPanel { 
    // override the paintComponent method 
    public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.drawString("Hello Panel!", 75, 100); 
    } //paintComponent 
} //class textPanel 

class MyFrame extends JFrame { 
    public MyFrame(String s) { 
    // Frame Parameters 
    setTitle(s); 
    setSize(300,200); // default size is 0,0 
    setLocation(10,200); // default is 0,0 (top left corner) 

    // Window Listeners 
    addWindowListener(new WindowAdapter() { 
     public void windowClosing(WindowEvent e) { 
     dispose(); 
     System.exit(0); // exit is still needed after dispose()! 
     } //windowClosing 
    }); //addWindowLister 

    // Add Panels 
    Container contentPane = getContentPane(); 
    contentPane.add(new textPanel()); 
    contentPane.setBackground(Color.pink); 
    } //constructor MyFrame 
} //class MyFrame 

public class MyPanel { 
    public static void main(String[] args) { 
    JFrame f = new MyFrame("My Hello Panel!"); 
    f.setVisible(true); // equivalent to f.show()! 
    } //main 
} //class MyPanel 


/* NOTES: 
    WindowAdapter() is class that implements WindowListers 
    with null methods for all the 7 methods of WindowListeners! 
    It is found in java.awt.event.*. 
*/ 
相關問題