按钮不会显示在FlowLayout中

时间:2014-10-10 21:43:00

标签: java button user-interface layout

我正在上课。想法是显示图像和上/下对比度。这是一个例子。我能够使图像出现,并且像示例中的图像上方出现灰色条,但我的按钮不在那里。我不知道如何通过FlowLayout正确地做到这一点,或者如果我需要使用另一个布局。我是GUI的新手,所以任何帮助都会受到赞赏!

enter image description here

这就是我的样子。我究竟做错了什么? enter image description here

import javax.imageio.ImageIO;
import javax.swing.*;

import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.applet.Applet;

/**
 * This class extends JPanel and can load an image to its
 * original size.
 *
 * @author Dahai Guo
 *
 */
class ImagePanel extends JPanel{
    private BufferedImage image;

    public ImagePanel(BufferedImage image){
        this.image=image;
    }

    /**
     * Draws the image.
     */
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(image,0,0,image.getWidth(),image.getHeight(),this);

    }
}

/**
 * Object of this class can load an image and enable the user
 * to increase and decrease the contrast of the image.
 *
 * Note this class can only deal with the contrast of gray levels
 *
 * @author Dahai Guo
 *
 */
public class HistgramEqualizerApp extends JFrame {

    int count=0;

    private FlowLayout myLayout;
    private BorderLayout borderLayout;
    private ImagePanel imagePanel;
    private JButton increaseContrastButton;
    private JButton decreaseContrastButton;
    private BufferedImage image;

    /**
     * Cummulative density function
     */
    private int [] cdf=new int[256];

    /**
     * The current largest gray level.
     */
    private int imageMaxGrayLevel=0;

    /**
     * The current smallest gray level.
     */
    private int imageMinGrayLevel=300;

    /**
     * The smallest nonzero cell in the CDF of gray level
     * of the image.
     */
    private int minCdfValue;

    /**
     * The largest gray level when the image is first loaded.
     */
    private int originalImageMaxGray;

    /**
     * The smallest gray level when the image is first loaded.
     */
    private int originalImageMinGray;

    private int MAX_GRAY_LEVEL=255;
    private int MIN_GRAY_LEVEL=0;


    /**
     * Sets up the GUI components and register the action listener for
     * the two buttons for increasing and decreasing contrast
     * @param filename the filename of the image
     * @throws IOException thrown when problems occurs when loading the image
     */
    public HistgramEqualizerApp(String filename)
        throws IOException{
        // insert your code

        try {
            image = ImageIO.read(new File(filename));
        } catch (IOException e) {
            System.err.println("Problem loading image.");
            System.exit(1);
        }
        // Display image to screen
        add(new JLabel(new ImageIcon(filename)));



        myLayout = new FlowLayout(FlowLayout.CENTER, 20, 40);
        setLayout(myLayout);                      

        // Buttons for contrast control
         increaseContrastButton = new JButton(">>");
         decreaseContrastButton = new JButton("<<");

        add(increaseContrastButton);
        increaseContrastButton.setVisible(true);

        add(decreaseContrastButton);    
        decreaseContrastButton.setVisible(true);


        //increaseContrastButton.addActionListener(this);
        //decreaseContrastButton.addActionListener(this);








    }

    /**
     * Calculates the current image's CDF.
     *
     * There are only 256 gray levels in consideration. The image is scanned
     * pixel by pixel. For each pixel, its gray level is the average of its rgb.
     * This gray level will be used to generate a histogram.
     *
     * When the histogram is ready,
     * CDF[i]=sum(histogram[0]+histogram[1]+...+histogram[i]).
     *
     * Note this method is also in charge of calculating the following instance variable:
     * <ul>
     * <li>imageMaxGrayLevel</li>
     * <li>imageMinGrayLevel</li>
     * <li>minCdfCell</li>
     * </ul>
     */
    private void findCdf(){

        // insert your code
    }

    /**
     * Finds the rgb of a pixel in image.
     *
     * @param image the source image
     * @param x horizontal coordinate
     * @param y vertical coordinate
     * @param rgb an array where the result is saved
     */
    private void getRGB(BufferedImage image, int x, int y, int[] rgb){
        int temp=image.getRGB(x,y);
        Color color=new Color(temp);
        rgb[0]=color.getRed();
        rgb[1]=color.getGreen();
        rgb[2]=color.getBlue();
    }

    /**
     * Sets the rgb values for a pixel of image
     *
     * @param image source image
     * @param x horizontal coordinate
     * @param y vertical coordinate
     * @param rgb the rgb values to set
     */
    private void setRGB(BufferedImage image, int x, int y, int[] rgb){
        Color color=new Color(rgb[0],rgb[1],rgb[2]);
        image.setRGB(x, y, color.getRGB());
    }

    /**
     * Inner class that handles the event on increaseContrastButton and
     * decreaseContrastButton.
     *
     * @author Dahai Guo
     *
     */
    private class ChangeConstrastListener implements ActionListener{

        /**
         * This variable decides how fast the contrast is changing.
         *
         * When increasing contrast, the largest/smallest gray level will
         * be increased/decreased STEP.
         *
         * When decreasing contrast, the largest/smallest gray level will
         * be decrease/increase STEP.
         */
        private int STEP=10;

        /**
         * Is the method that deals with both increaseContrastButton and
         * decreaseContrastButton.
         */
        @Override
        public void actionPerformed(ActionEvent e){

            // insert your code

            imagePanel.repaint();
        }


        /**
         * Changes the contrast for each pixel of the image which
         * is defined in the outer class.
         * @param maxGray
         * @param minGray
         */
        private void changeConstrast(int maxGray, int minGray){

            int width=image.getWidth();
            int height=image.getHeight();
            int rgb[]=new int[3];
            for(int i=0;i<width;i++){
                for(int j=0;j<height;j++){
                    equalize(i,j,maxGray,minGray);
                }
            }

            findCdf();
        }

        /**
         * Follows "Histogram Equalization" on Wikipedia.
         *
         * Changes the rgb for the pixel at (x,y) in the image.
         *
         * @param x horizontal coordinate
         * @param y vertical coordinate
         * @param max the new max gray level
         * @param min the new min gray level
         */
        private void equalize(int x, int y, int max, int min){

            // insert your code here

        }
    }

    public static void main(String args[])
        throws IOException{
        if(args.length!=1){
            System.err.println("Missing the path to an image file");
            System.err.println("Command: java HistogramEqualizer image_file");
            System.exit(1);
        }
        HistgramEqualizerApp histApp = new HistgramEqualizerApp(args[0]);

        histApp.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        histApp.setSize( 512, 400 ); // set frame size
        histApp.setVisible( true ); // display frame
        histApp.setResizable(true);
    }


}

2 个答案:

答案 0 :(得分:0)

以下是一种使其有效的方法:

public class HistgramEqualizerApp extends JFrame {

    private JButton increaseContrastButton = new JButton(">>");;
    private JButton decreaseContrastButton = new JButton("<<");;

    public HistgramEqualizerApp(String filename) throws IOException {

        JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 40));
        buttonsPanel.add(decreaseContrastButton);
        buttonsPanel.add(increaseContrastButton);
        getContentPane().add(new JLabel(new ImageIcon(filename)));
        getContentPane().add(buttonsPanel, BorderLayout.PAGE_START);
    }

    public static void main(String args[]) throws IOException {

        HistgramEqualizerApp histApp = new HistgramEqualizerApp(args[0]);
        histApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        histApp.pack();
        histApp.setVisible(true);
    }
}

答案 1 :(得分:0)

这是我的两分钱。

正如我之前所说:“你应该使用边框布局并将按钮添加到面板,然后将所述面板添加到主框架,然后将图像面板添加到中心。”

import java.awt.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class HistogramEqualizerApp extends JFrame {
    private ButtonPanel buttonPanel;
    private ImagePanel imagePanel;

    private JButton increaseContrastButton;
    private JButton decreaseContrastButton;
    private BufferedImage image;

    public HistgramEqualizerApp() {
        Container content = this.getContentPane();
        content.setLayout(new BorderLayout());

        // Buttons for contrast control
        increaseContrastButton = new JButton(">>");
        decreaseContrastButton = new JButton("<<");
        buttonPanel = new ButtonPanel(
                Arrays.asList(decreaseContrastButton, increaseContrastButton));
        content.add(buttonPanel, BorderLayout.NORTH);

        image = randomImage(80, 120, 4);
        imagePanel = new ImagePanel(image);
        content.add(imagePanel, BorderLayout.CENTER);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(512, 400);
        this.setResizable(true);
    }

    public static void main(String args[]) throws IOException {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                HistgramEqualizerApp histApp = new HistgramEqualizerApp();
                histApp.setVisible(true);
            }
        });
    }

    static class ImagePanel extends JPanel {
        private BufferedImage image;

        public ImagePanel(BufferedImage image) {
            this.image = image;
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);

        }
    }

    static class ButtonPanel extends JPanel {
        private List<JButton> buttons;

        public ButtonPanel(List<JButton> buttons) {
            this.setLayout(new FlowLayout());
            this.buttons = buttons;
            for (JButton button : buttons) {
                this.add(button);
            }
        }
    }

    public static BufferedImage randomImage(int rows, int cols, int pixelRatio) {
        int width = pixelRatio * cols, height = pixelRatio * rows;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = (Graphics2D) img.getGraphics();
        int x, y = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                x = i * pixelRatio;
                y = j * pixelRatio;
                if ((i * j) % 6 == 0) {
                    g.setColor(Color.GRAY);
                } else if ((i + j) % 5 == 0) {
                    g.setColor(Color.BLUE);
                } else {
                    g.setColor(Color.WHITE);
                }
                g.fillRect(y, x, pixelRatio, pixelRatio);
            }
        }
        g.dispose();

        return img;
    }
}