2014-10-10 2 views
0

Я делаю программу для класса. Идея заключается в отображении изображения и увеличении/уменьшении контраста. Вот пример. Я могу сделать изображение поднятым, и над изображением, как в примере, появляется серый бар, но моих кнопок нет. Я не уверен, как правильно это сделать через FlowLayout, или если мне нужно использовать другой макет. Я новичок в GUI, поэтому любая помощь будет оценена!Кнопки не отображаются в FlowLayout

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); 
    } 


} 
+0

Ваш код не соответствует. Отправьте сообщение [MCVE] (http://stackoverflow.com/help/mcve). – user1803551

+0

Я добавил полный код, извините! – user1765804

+0

M в MCVE для минимального, «полный код» - это точно противоположное. Зачем нам нужен весь этот код функциональности, чтобы проверить, почему кнопки не отображаются? Удалите все, что не важно для проблемы (и не просто удаляйте его так, чтобы код не компилировался). – user1803551

ответ

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); 
    } 
} 
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; 
    } 
} 
Смежные вопросы