0
我的代碼將運行並編譯。如果您將鼠標懸停在JFrame內部的任何位置,它都可以工作,但是當您進入屏幕時,它只會有時會起作用,如果這樣做,它只會將RGB值視爲白色,有時也會顯示爲灰色。我不確定爲什麼每次我跳出盒子時都不起作用,爲什麼它不能在框架外獲得所有的RGB值,但是可以在裏面工作。有人可以看看嗎?懸停後,我附上了一個截圖,讓它在盒子外面呈現白色。謝謝!當在Swing組件生成事件屏幕上任意位置的光標下的RGB值
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class RGBValue {
public static void main(String[] args) throws Exception {
new RGBValue();
}
public RGBValue() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Get the RGB");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
try {
frame.add(new TestPane());
} catch (Exception ex) {
Logger.getLogger(RGBValue.class.getName()).log(Level.SEVERE, null, ex);
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
private JLabel label;
private JPanel fields;
private JTextField red;
private JTextField green;
private JTextField blue;
// private JTextArea RGB;
PointerInfo info = MouseInfo.getPointerInfo();
Point point = info.getLocation();
Robot robot = new Robot();
public TestPane() throws Exception {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
label = new JLabel();
try {
URL url = new URL("https://c6.staticflickr.com/2/1520/24330829813_944c817720_b.jpg");
img = ImageIO.read(url);
label.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
add(label, gbc);
fields = new JPanel();
fields.setBorder(new EmptyBorder(5, 5, 5, 5));
red = new JTextField(3);
green = new JTextField(3);
blue = new JTextField(3);
fields.add(red);
fields.add(green);
fields.add(blue);
add(fields, gbc);
robot.delay(2000);
label.addMouseMotionListener(new MouseAdapter() {
// @Override
public void mouseMoved(MouseEvent e) {
// while (true) {
//int packedInt = img.getRGB(e.getX(), e.getY());
// Color color = new Color(packedInt, true);
point = MouseInfo.getPointerInfo().getLocation();
Color color = robot.getPixelColor((int)point.getX(), (int)point.getY());
// RGB.setText(color.getBlue() + color.getRed() + color.getGreen());
red.setText(Integer.toString(color.getRed()));
green.setText(Integer.toString(color.getGreen()));
blue.setText(Integer.toString(color.getBlue()));
fields.setBackground(color);
}
});
}
}
}
雖然這是一個好主意,並且它確實在整個屏幕上進行了擴展,但它仍然只是有時需要RGB值。 – Millie
@Millie,'robot.delay(2000);' - 爲什麼你會有延遲?生成MouseEvent時將檢索像素。所以更新頻率由鼠標移動控制。 – camickr
考慮到這一點也不能解決它。我仍然不確定我要出錯的地方。 – Millie