Я делаю программу для класса. Идея заключается в отображении изображения и увеличении/уменьшении контраста. Вот пример. Я могу сделать изображение поднятым, и над изображением, как в примере, появляется серый бар, но моих кнопок нет. Я не уверен, как правильно это сделать через FlowLayout, или если мне нужно использовать другой макет. Я новичок в GUI, поэтому любая помощь будет оценена!Кнопки не отображаются в FlowLayout
Это как мина выглядит. Что я делаю не так?
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);
}
}
Ваш код не соответствует. Отправьте сообщение [MCVE] (http://stackoverflow.com/help/mcve). – user1803551
Я добавил полный код, извините! – user1765804
M в MCVE для минимального, «полный код» - это точно противоположное. Зачем нам нужен весь этот код функциональности, чтобы проверить, почему кнопки не отображаются? Удалите все, что не важно для проблемы (и не просто удаляйте его так, чтобы код не компилировался). – user1803551