将图像放在Java GUI中

时间:2017-01-26 15:11:40

标签: java swing user-interface imagej

我正在为学校项目创建Java UI。我有4个按钮和JFrame中的图像,我希望能够使用每个按钮在图像上执行任务。每次按下按钮,它都会使用按钮功能覆盖图像。我有按钮和功能,但我对如何将图像添加到JFrame无能为力。我是否使用Jpanel或画布将图像放到框架上。我使用了netbeans GUI构建器。这是压缩形式的代码

//import static NewJFrame.plotWidth;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageConverter;
import ij.process.ImageProcessor;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Polygon;


public class my_JframePlugin extends javax.swing.JFrame {

    static int plotWidth =400;
    static double angleInDegrees =  40;
    static double angle = (angleInDegrees/360.0)*2.0*Math.PI;
    static int polygonMultiplier = 100;
    static boolean oneToOne;
    double picsize;

    ImagePlus img = IJ.openImage();
    ImageProcessor imgP = img.getProcessor();
    int[] x,y;
    /**
     * Creates new form NewJFrame
     */
    public my_JframePlugin() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        canvas1 = new java.awt.Canvas();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 477, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 310, Short.MAX_VALUE)
        );

        jButton1.setText("FFT");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Inverse FFT");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("3D Plot");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Crop");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Add Image");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(108, 108, 108))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(56, 56, 56))
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        IJ.log("FFT clicked");
    }                                        


    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        //ImagePlus myimage = img;
        img = WindowManager.getCurrentImage();
         if (img==null)
                 {
                     //IJ.noImage();
                     IJ.log("No Image selected");
                     return;
                 }
         if (!showDialog())
                 return;
         if (img.getType()!=ImagePlus.GRAY8) 
         {
                 ImageProcessor ip = img.getProcessor();
                 ip = ip.crop(); // duplicate
                 img = new ImagePlus("temp", ip);
                  new ImageConverter(img).convertToGray8();
         }
         ImageProcessor plot = makeSurfacePlot(img.getProcessor()); 
         new ImagePlus("Surface Plot", plot).show();
         IJ.register(Surface_Plotter.class);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        IJ.log("Inverse FFT clicked");
    }                                        


    boolean showDialog() 
    {
            GenericDialog gd = new GenericDialog("Surface Plotter");
            gd.addNumericField("Width (pixels):", plotWidth, 0);
            gd.addNumericField("Angle (-90-90 degrees):", angleInDegrees, 0);
            gd.addNumericField("Polygon Multiplier (10-200%):", polygonMultiplier, 0);
            gd.addCheckbox("One Polygon Per Line", oneToOne);
            gd.showDialog();
            if (gd.wasCanceled())
                    return false;
            plotWidth = (int) gd.getNextNumber();
            angleInDegrees = gd.getNextNumber();
            polygonMultiplier = (int)gd.getNextNumber();
            oneToOne = gd.getNextBoolean();
            if (polygonMultiplier>400) polygonMultiplier = 400;
            if (polygonMultiplier<10) polygonMultiplier = 10;
            return true;
    }

    public ImageProcessor makeSurfacePlot(ImageProcessor ip) 
    {
            double angle = (angleInDegrees/360.0)*2.0*Math.PI;
            int polygons = (int)(plotWidth*(polygonMultiplier/100.0)/4);
            if (oneToOne)
                    polygons = ip.getHeight();
            double xinc = 0.8*plotWidth*Math.sin(angle)/polygons;
            double yinc = 0.8*plotWidth*Math.cos(angle)/polygons;
            boolean smooth = true;
            IJ.showProgress(0.01);
            ip.setInterpolate(true);
            ip = ip.resize(plotWidth, polygons);
            int width = ip.getWidth();
            int height = ip.getHeight();
            double min = ip.getMin();
            double max = ip.getMax();

            if (smooth)
                    ip.smooth();
            //new ImagePlus("Image", ip).show();

            int windowWidth =(int)(plotWidth+polygons*Math.abs(xinc) + 20.0);
            int windowHeight = (int)(255+polygons*yinc + 10.0);
            Image plot =IJ.getInstance().createImage(windowWidth, windowHeight);
            Graphics g = plot.getGraphics();
            g.setColor(Color.white);
            g.fillRect(0, 0, windowWidth, windowHeight);

            x = new int[width+2];
            y = new int[width+2];
            double xstart = 10.0;
            if (xinc<0.0)
                    xstart += Math.abs(xinc)*polygons;
            double ystart = 0.0;
            for (int row=0; row<height; row++) {
                    double[] profile = ip.getLine(0, row, width-1, row);
                    Polygon p = makePolygon(profile, xstart, ystart);
                    g.setColor(Color.white);
                    g.fillPolygon(p);
                    g.setColor(Color.black);
                    g.drawPolygon(p);
                    xstart += xinc;
                    ystart += yinc;
                    if ((row%5)==0) IJ.showProgress((double)row/height);
            }
            IJ.showProgress(1.0);

            ip = new ColorProcessor(plot);
            byte[] bytes = new byte[windowWidth*windowHeight];
            int[] ints =(int[]) ip.getPixels();
            for (int i=0; i<windowWidth*windowHeight; i++)
                    bytes[i] = (byte)ints[i];
            ip = new ByteProcessor(windowWidth,windowHeight, bytes, null);
            return ip;
    }

    Polygon makePolygon(double[] profile, double xstart, double ystart) {
            int width = profile.length;
            for (int i=0; i<width; i++) 
                    x[i] =(int)( xstart+i);
            for (int i=0; i<width; i++) 
                    y[i] =(int)(ystart+255.0-profile[i]);
            x[width] =(int)xstart+width-1;
            y[width] = (int)ystart+255;
            x[width+1] =(int)xstart;
            y[width+1] = (int)ystart+255;

            //for (int i=0; i<width; i++)
            //  IJ.write("dbg: "+i+"  "+profile[i]+"  "+x[i]+"  "+y[i]);

            return new Polygon(x, y, width+2);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(my_JframePlugin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private java.awt.Canvas canvas1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

我根本不知道如何将图像加载到框架上

1 个答案:

答案 0 :(得分:-1)

请参阅How to Use Icons上的Swing教程中的部分。

它向您展示了如何阅读Image并使用JLabelImage显示为Icon

本教程还将向您展示其他Swing基础知识。