我正在开发一个简单的图像编辑程序来调整亮度/对比度。我的自定义 JPanel 仅用于显示加载的图像,但它导致下一列上的滑块和标签显示不正确。
import java.awt.*;
import javax.swing.*;
public class IMView extends JFrame implements Observer {
JButton selectIMGFolder = new JButton("Select Folder");
ImagePanel originalImage;
//Labels and sliders to control image
JLabel brightnessLabel = new JLabel("Brightness");
JSlider brightness = new JSlider(-255,255,0);
JLabel contrastLabel = new JLabel("Contrast");
JSlider contrastSlider = new JSlider(-255,255,0);
JLabel random = new JLabel("Random Test Label");
public IMView (){
super("Image manipulation");
JPanel mainJPanel = new JPanel();
mainJPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
originalImage = new ImagePanel();
//first column
gc.anchor = GridBagConstraints.LINE_START;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0;
gc.gridy = 0;
mainJPanel.add(selectIMGFolder, gc);
gc.gridx = 0;
gc.gridy = 1;
mainJPanel.add(originalImage, gc);
gc.gridx = 0;
gc.gridy = 2;
mainJPanel.add(random, gc);
//second column
//brightness
gc.gridx = 1;
gc.gridy = 0;
mainJPanel.add(brightnessLabel, gc);
gc.gridx = 1;
gc.gridy = 1;
mainJPanel.add(brightness, gc);
gc.gridx = 1;
gc.gridy = 2;
mainJPanel.add(contrastLabel, gc);
gc.weighty = 10;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.gridx = 1;
gc.gridy = 3;
mainJPanel.add(contrastSlider, gc);
this.add(mainJPanel);
this.setVisible(true);
this.setPreferredSize(new Dimension(800, 600));
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//other code
}
这是我的简单自定义面板:
public class ImagePanel extends JPanel {
Image image;
public ImagePanel(){
this.setPreferredSize(new Dimension(400,300));
}
//set image file some where
@Override
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.red);
g.fillRect(0, 0, 400,300);
if(image != null){
g.drawImage(image, 0,0, this);
}
}
}
下面是代码的结果(其中红色方块代表图像),我基本上希望将右侧的滑块和标签打包在一起。如果我不向其中添加自定义面板,mainJPanel
它似乎看起来像我想要的那样。