पिछले दो दिनों से मैंने को समझने की कोशिश की है कि जावा ग्राफिक्स को कैसे संभालता है, लेकिन बस उस पर दुर्भाग्य से विफल रहा है। मेरी मुख्य समस्या यह समझ रही है कि कैसे और कब पेंट() (या नया पेंट कॉम्पोनेंट())/कॉल किया जाना चाहिए।पेंट()/paintComponent() कभी क्यों नहीं कहा जाता है?
निम्नलिखित कोड में मैंने यह देखने के लिए बनाया कि चीजें कब बनाई जाती हैं, पेंट कॉम्पोनेंट() को कभी भी नहीं कहा जाता है, जब तक कि मैं इसे मैन्युअल रूप से कॉल नहीं करता या JFrame.paintAll()/JFrame.paintComponents() पर कॉल करता हूं।
मैंने पेंट() विधि को पेंट कॉम्पोनेंट() को पेंट करने के लिए नाम दिया है ताकि उम्मीद की जा सके कि इसकी समस्या को ठीक नहीं किया जाएगा (यहां तक कि repaint() पर भी, लेकिन कोई भाग्य नहीं है।
package jpanelpaint;
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
public class ImageLoadTest extends JComponent {
ArrayList<Image> list;
public ImageLoadTest() {
list = new ArrayList<Image>();
try { //create the images (a deck of 4 cards)
for(String name : createImageFileNames(4)){
System.err.println(name);
list.add(ImageIO.read(new File(name)));
}
} catch (IOException e) { }
}
protected void paintComponent(Graphics g) {
int yOffset=0;
System.err.println("ImageLoadTest.paintComponent()");
for(Image img : list) {
g.drawImage(img, 0, yOffset, null);
yOffset+=20;
}
}
public static void main(String args[]) throws InterruptedException {
JFrame frame = new JFrame("Empty JFrame");
frame.setSize(new Dimension(1000, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Thread.sleep(1000);
frame.setTitle("Loading images");
ImageLoadTest ilt = new ImageLoadTest();
frame.add(ilt);
//update the screen
//DOESN'T WORK. only works if I call frame.paintAll(frame.getGraphics())
ilt.repaint();
frame.repaint();
Thread.sleep(1000);
frame.setTitle("Setting background");
ilt.setBackground(Color.BLACK);
//update the screen - DOESN'T WORK even if I call paintAll ..
ilt.repaint();
frame.repaint();
//have to call one of these to get anything to display
// ilt.paintComponent(frame.getGraphics()); //works
frame.paintComponents(frame.getGraphics()); //works
}
//PRIVATE HELPER FUNCTIONS
private String[] createImageFileNames(int count){
String[] fileNames = new String[count];
for(int i=0; i < count; i++)
fileNames[i] = "Cards" + File.separator + (i+1) + ".bmp";
return fileNames;
}
}
धन्यवाद, कोशिश करेंगे। लेकिन क्या मुझे वास्तव में काम करने के लिए अंत में सेटविज़िबल का उपयोग करना चाहिए? इसे जल्दी कॉल करने वाला बिंदु यह देखना था कि मुझे बाद में अतिरिक्त ग्राफिकल तत्व जोड़ने को कैसे संभालना चाहिए। लेकिन पूरी तरह से चलने योग्य चीज़ मेरे लिए नई थी; मैंने नहीं देखा है कि मैंने देखा है कि किसी भी ट्यूटोरियल में (जैसे this one)। – oligofren
[java.awt.EventQueue.'] 'invokeLater' का उपयोग करके यह मेरे लिए काम करता है। –
(हालांकि यह शायद एक बग को कवर कर रहा है। हालांकि 'add'' के लिए एपीआई दस्तावेज़ों में वर्णित 'add' के बाद आपको' पुनः सत्यापित 'करना चाहिए।) –