如何创建一个图像面板并在NetBeans上使用它



我有一个类,它简单地扩展了JPanel并覆盖了paintComponent方法,如下所示:

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

我将其添加到NetBeans托盘中,但背景图像既不显示在UI编辑器上,也不显示在我通过NetBeans运行程序时。我做错了什么?我希望在托盘上有这个图像面板

如果你在位置(0,0)绘制图像,而不是缩放图像以适应窗口,那么就没有理由进行自定义绘制。只需使用图像创建ImageIcon,并将图像添加到JLabel中,并将标签添加到框架中。

进行自定义绘画的可能问题是,您没有给组件一个首选的大小,所以面板的大小是0,没有什么可以绘画。

除非你正在对图像进行缩放或其他图形功能,否则保持简单并使用JLabel,它将为你管理绘画和大小

参见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.*.
 */

相关内容

  • 没有找到相关文章

最新更新