1

我正在使用带有 netbeans 的 Java Swing 图形编辑器来制作我的项目……但是使用它会带来一些限制,例如我无法使用 java swing 选项将图像添加到 jpanel 中。所以我需要编写代码,实现一个新的 jPanel。

我的问题是无法编辑由 java swing 图形编辑器生成的代码,因此在我的主 JPanel 的构造函数中调用此函数之后,我正在执行它,而不是在 initComponents() 部分中添加新的 JPanel 代码。

但是我添加的任何代码都不能被“设计器”识别,这意味着在制作了我的编码对象后,我无法在“设计器”中使用它们,并且必须对所有内容进行编码,考虑到预览和移动有多容易,这很痛苦“设计器”工具中的元素。

我如何编写我想要的代码,但钢出现在“DEsigner”中?

提前谢谢

4

1 回答 1

2

JPanel以下是使用 NetBeans GUI 编辑器向图像添加图像的两种方法。下面的类ImagePanel是使用New JPanel Form命令创建的。

非设计者:第一种方式修改构造函数设置背景图片,类覆盖paintComponent()绘制图片。编辑器折叠内没有代码更改。

设计器:使用 GUI 设计器,第二种方法添加一个JLabel命名的imageLabel. 创建JLabel居中的代码Icon位于名为 的属性中Custom Creation Code,而以下两行位于Post-Creation Code.

package overflow;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class ImagePanel extends javax.swing.JPanel {

    private Image image;

    /** Creates new form ImagePanel */
    public ImagePanel(Image image) {
        this.image = image;
        this.setPreferredSize(new Dimension(
            image.getWidth(null), image.getHeight(null)));
        initComponents();
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        imageLabel = new JLabel(new ImageIcon("image2.jpg"), JLabel.CENTER);
        imageLabel.setHorizontalTextPosition(JLabel.CENTER);
        imageLabel.setVerticalTextPosition(JLabel.TOP);

        setLayout(new java.awt.GridLayout());

        imageLabel.setText("imageLabel");
        add(imageLabel);
    }// </editor-fold>


    // Variables declaration - do not modify
    private javax.swing.JLabel imageLabel;
    // End of variables declaration

}

这是显示面板的合适Main类和main()方法:

package overflow;

import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                try {
                    f.add(new ImagePanel(ImageIO.read(new File("image1.jpg"))));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                f.pack();
                f.setVisible(true);
            }
        });
    }
}

http://i41.tinypic.com/dmw4nl.png

于 2010-05-07T02:48:25.170 回答