我希望每次更改滑块位置时重新绘制显示的图像。
我已经将JSlider变量的每次更改添加到像素中。但我只是不知道如何重新绘制它。
package training;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.plaf.SliderUI;
import java.awt.Color;
import java.util.Arrays;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Training extends JPanel {
public BufferedImage image;
double maxw, maxh;
double w, h, ratio;
int warna, red, green, blue, abu, value;
int forT1, forT2;
int[][] bmpR;
int[][] bmpG;
int[][] bmpB;
int[][] alpha;
public Training () {
super();
try {
image = ImageIO.read(new File("src/training/V.jpg"));
}
catch (IOException e) {
//Not handled.
}
maxw = 750;
maxh = 600;
w = image.getWidth();
h = image.getHeight();
bmpR = new int[(int)w][(int)h];
bmpG = new int[(int)w][(int)h];
bmpB = new int[(int)w][(int)h];
if (w > h) {
if (w > maxw) {
ratio = maxw / w;
h = h * ratio; // Reset height to match scaled image
w = w * ratio;
}
}
if (w <= h) {
if (h > maxh) {
ratio = maxh / h;
w = w * ratio; // Reset height to match scaled image
h = h * ratio;
}
}
try {
for( int i = 0; i < w; i++ ) {
for( int j = 0; j < h; j++ ) {
Color c = new Color(image.getRGB(i, j));
bmpR [i][j] = c.getRed();
bmpG [i][j] = c.getGreen();
bmpB [i][j] = c.getBlue();
// alpha = c.getAlpha();
}
}
System.out.println(bmpB[40][40]);
}
catch (Exception e) {
System.out.println("Terjadi kesalahan saat mengambil data pixel");
e.printStackTrace();
return;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Image i = image.getScaledInstance((int)w, (int)h,Image.SCALE_SMOOTH);
g.drawImage(i, 20, 20, null);
}
public static void main(String[] args) {
final Training ns = new Training();
System.out.println("User dir: " + System.getProperty("user.dir"));
JFrame f = new JFrame("Window");
JPanel p = new Training();
f.setSize(1100, 600);
p.setSize(750, 600);
f.add(p);
JSlider Temp = new JSlider(-50, 50, 0);
Temp.setMajorTickSpacing(10);
Temp.setMinorTickSpacing(1);
Temp.addChangeListener(new ChangeListener () {
public void stateChanged(ChangeEvent evt) {
JSlider Temp = (JSlider) evt.getSource();
if (Temp.getValueIsAdjusting()) {
ns.value = Temp.getValue();
for(ns.forT1 = 0; ns.forT1 < ns.w; ns.forT1++ ) {
for(ns.forT2 = 0; ns.forT2 < ns.h; ns.forT2++ ) {
ns.bmpB[ns.forT1][ns.forT2] = ns.bmpB[ns.forT1][ns.forT2] - ns.value;
if (ns.bmpB[ns.forT1][ns.forT2] > 255) {
ns.bmpB[ns.forT1][ns.forT2] = 255;
}
if (ns.bmpB[ns.forT1][ns.forT2] < 0) {
ns.bmpB[ns.forT1][ns.forT2] = 0;
}
ns.bmpR[ns.forT1][ns.forT2] = ns.bmpR[ns.forT1][ns.forT2] + ns.value;
if (ns.bmpR[ns.forT1][ns.forT2] > 255) {
ns.bmpR[ns.forT1][ns.forT2] = 255;
}
if (ns.bmpR[ns.forT1][ns.forT2] < 0) {
ns.bmpR[ns.forT1][ns.forT2] = 0;
}
}
}
}
ns.repaint();
}
});
f.add(Temp, BorderLayout.EAST);
f.setVisible(true);
}
}
我是否错放了ChangeListener,还是应该在更改侦听器发生后放置paintComponent方法?
答案 0 :(得分:0)
代码的随机缩进使得很难确切地知道发生了什么,但我在repaint()
内的任何地方都没有看到ChangeListener
。您需要使用repaint()
来触发重新绘制组件。