الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

كيف أقوم بإدراج صورة كخلفية في جافا كلاس؟

بدأه aymane-tech في 12 مارس 2011 · 8 رد · 650 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم

قمت بانشاء برنامج محادثة -شات- وانتهيت منه والحمد لله

ولكي اضفي عليه بعض الحيوية و الديناميكية اردت أن أدرج صورة كخلفية للواجهة، لكني بحث طويلا دون جدوى، أتمنى أن ألقى جوابي عندكم

/* Imports the javax.swing package classes. */
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JDialog;
import javax.swing.JPasswordField;
import javax.swing.BorderFactory;
/*Imports the java.awt package classes.*/
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.FlowLayout;
import java.awt.Font;
/*Imports the javax.swing.event package classes.*/
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.JSeparator;
/* 
class ChatLogin - Creates the Chat Login window for the chat application.
      Method:
      - actionPerformed()
      - main()
*/
public class ChatLogin extends JDialog implements ActionListener
{
   JPanel panel;
   JPanel pane;
   /* Declares the objects of the JLabel class. */
   JLabel titleLabel;
   JLabel nameLabel;
   JLabel pwdLabel;
   JLabel ipLabel;
   /* Declares the objects of JTextField class */
   JTextField nameText;
   JPasswordField pwdText;
   JTextField ipText;   
   /*Declares the objects of the JButton class.*/
   JButton connect;
   JButton cancel;
   GridBagLayout gbl;
   GridBagConstraints gbc;
   int value;
   /* Defines the default constructor.*/
   public ChatLogin()
   {
      /*Sets the title of the Font dialog box.*/
      setTitle("Chat Login Window");
      /*Sets the size of Font dialog box.*/
      setSize(280, 170);
      /*Sets resizable button to FALSE.*/
      setResizable(false);
      /*Initializes the object of the GridBagLayout class*/
      gbl = new GridBagLayout();
      /* Sets the Layout. */
      getContentPane().setLayout(gbl);
      /*Creates an object of the GridBagConstraints class.*/
      gbc = new GridBagConstraints();
      /* 
         Initializes the title label object and adds it to the 1, 1, 2, 1 position with WEST
         alignment. 
      */
         gbc.gridx = 1;   
         gbc.gridy = 1;
         gbc.gridwidth = 2;
         gbc.gridheight = 1;
         gbc.anchor = GridBagConstraints.CENTER;
         pane = new JPanel();
      pane.setLayout(new FlowLayout());
      titleLabel = new JLabel("Chat Login Window");
      titleLabel.setFont(new Font("Verdana",Font.BOLD,20));
      pane.add(titleLabel);
      getContentPane().add(pane, gbc);
      gbc.gridx = 1;   
      gbc.gridy = 2;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      getContentPane().add(new JSeparator(), gbc);
      /* 
         Initializes the IP address label object and adds it to the 1, 3, 1, 1 position with
         EAST alignment 
      */   
      gbc.gridx = 1;   
      gbc.gridy = 3;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.EAST;
      ipLabel = new JLabel("Server IP: ");
      getContentPane().add(ipLabel, gbc);
      /* 
Initializes the IP address text field object and adds it to the 2, 3, 1, 1 position with WEST alignment 
      */
      gbc.gridx = 2;   
      gbc.gridy = 3;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      ipText = new JTextField("192.168.0.36", 15);
      ipText.setFont(new Font("Verdana",Font.PLAIN,12));
      getContentPane().add(ipText, gbc);
      gbc.gridx = 1;   
      gbc.gridy = 4;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      getContentPane().add(new JSeparator(), gbc);
      /* 
Initializes the user name label object and adds it to the 1, 5, 1, 1 position with EAST alignment. 
      */   
      gbc.gridx = 1;   
      gbc.gridy = 5;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.EAST;
      nameLabel = new JLabel("User Name: ");
      getContentPane().add(nameLabel, gbc);
      /* 
         Initializes the user name text field object and adds it to the 2, 5, 1, 1 position with
         WEST alignment. 
      */
      gbc.gridx = 2;   
      gbc.gridy = 5;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      nameText = new JTextField(15);
      nameText.setFont(new Font("Verdana",Font.PLAIN,12));
      getContentPane().add(nameText, gbc);
      gbc.gridx = 1;   
      gbc.gridy = 6;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      getContentPane().add(new JSeparator(), gbc);
      /* 
         Initializes the password label object and adds it to the 1, 7, 1, 1 position with EAST
         alignment. 
      */   
      gbc.gridx = 1;   
      gbc.gridy = 7;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.EAST;
      pwdLabel = new JLabel("Password: ");
      getContentPane().add(pwdLabel, gbc);
      /* 
         Initializes the password text field object and adds it to the 2, 7, 1, 1 position with
         WEST alignment. 
      */
      gbc.gridx = 2;   
      gbc.gridy = 7;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      pwdText = new JPasswordField(15);
      pwdText.setFont(new Font("Verdana",Font.PLAIN,12));
      pwdText.addActionListener(this);
      getContentPane().add(pwdText, gbc);
      gbc.gridx = 1;   
      gbc.gridy = 8;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      getContentPane().add(new JSeparator(), gbc);
      /* 
         Initializes the OK and Cancel button. Adds the button to the 2, 9, 1, 1 position with
         WEST alignment. 
      */
      gbc.gridx = 2;   
      gbc.gridy = 9;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.anchor = GridBagConstraints.WEST;
      panel = new JPanel();
      panel.setLayout(new FlowLayout(FlowLayout.LEFT));
      connect = new JButton("Connect");
      connect.addActionListener(this);
      cancel = new JButton("Cancel");
      cancel.addActionListener(this);
      panel.add(connect);
      panel.add(cancel);
      getContentPane().add(panel, gbc);

      addWindowListener(new WindowAdapter()
      {
         public void windowClosing(WindowEvent we)
         {
            System.exit(0);
         }
      });   
   }
   /*
actionPerformed() - This method is called when the user clicks the any button.
Parameters:	ae: Represents an object of the ActionEvent class that contains the details of the event.
   Return Value: NA
   */
   public void actionPerformed(ActionEvent ae)
   {
      if(ae.getSource() == connect)
      {
/*Creates an object of the ChatClient class.*/
         ChatClient tcc = new ChatClient();
/*Calls the con() method to connect to the server.*/
tcc.con(nameText.getText(), pwdText.getText(), ipText.getText());
         this.setVisible(false);               
      }
      else if(ae.getSource() == cancel)
      {
         System.exit(0);
      }
      else if(ae.getSource() == pwdText)
      {
         /*Creates an object of the ChatClient class.*/
         ChatClient tcc = new ChatClient();
         /*Calls the con() method to connect to the server.*/
         tcc.con(nameText.getText(), pwdText.getText(), ipText.getText());
         this.setVisible(false);               
         }
         }
         /*Main method.*/   
         public static void main(String args[])
         {
            try
            {
               /*Sets the window look and feel to the application.*/
               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            }
            catch(Exception e){}      
            ChatLogin cl = new ChatLogin();
            cl.show();
      }
}

ChatLogin.java File.txt

#2

انظرى هذا الموضوع

/index.php?showtopic=221658&st=0

Software Developer
Mahmoudkelany.com


 

#3

قمت بتجربته من قبل دون جدوى

#4
aymane-tech كتب:

قمت بتجربته من قبل دون جدوى

ارفقى هذه التجربه , لايضاح ما هو الخطأ

Software Developer
Mahmoudkelany.com


 

#5

ما معنى دون جدوى بالضبط؟

تحياتي

حزمة المحرك الإصدارة 0.8

أي أحد يجد أني ظلمته فليراسلني

وبإذن الله لو كان له حق سيأخذه

728x90.png

#6
علاء الصالحي كتب:

ما معنى دون جدوى بالضبط؟

تحياتي

يعنى مش شغاله

هذا اما اظن

لكن هذا ليس حلا

اتمنى ان ترفق الكود الذى لا جدوى فيه هذا

لان الاصل شغال كما هو فالموضوع

Software Developer
Mahmoudkelany.com


 

#7

يعني أني قمت بادراجه الكود الموجود في المنتدى في الكود الذي أعمل عليه لكن الخلفية لم تظهر

ردا على الأخ "علاء الصالحي" الذي كتب التعليق التالي : "يبدو أن الرجل لم يجربها أصلاً ويريد شيء يتماشى مع شيفرته" أقول له غفر الله لك، لأن بعض الظن اثم

أنا لم أكتب هذا السؤال إلا بعدما نفذت جميع محاولات بحثي، حتى أن أصدقائي نصحوني بأن أترك الجافا لما عانوه من صعوبة في التعامل مع هذه اللغة هم أيضا و استخدام لغة دوت نيت لكونها أسهل وأبسط في استخدامها

سوف أكون ممتنا إن وجدت الشيفرة التي تتماشى مع ما اصبو إليه، لكني لم أيأس من البحث ولو اضطررت إلى البحث بلغات أجنبية غير الإنجليزية والفرنسية.

وأنا أكتب هذه السطور وجدت هذه الشيفرة سأحاول أن أدمجها مع الكود الخاص بي وسأرى إن كان المتوافق أم لا :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
 *
 * @author Aymane
 */

public class JLabelImage extends JLabel {
    private Image icon;
    private String image;
    private String saveText = "";
    private String text = "";
    private int Halignement = 0;
    private int Valignement = 0;
    public static int LEFT = 2;
    public static int RIGHT = 4;
    public static int CENTER = 0;
    public static int TOP = 8;
    public static int BOTTOM = 16;
    public Color couleurText;
    ImageIcon imIcon;

    /**
     * Constructeur qui permet de faire gérer au Label un text
     * et une image. par défaut, le texte est aligné au centre
     * verticalement et horizontalement.
     * le booléean calculerCouleurDominante indique au label
     * de calculer la couleur dominante de l'image, et de régler
     * la couleur du texte en conséquence (pas encore vraiment au point)
     *
     * @param image
     * @param text
     * @param calculerCouleurDominante
     */
    public JLabelImage(String image, String text, boolean calculerCouleurDominante) {
	//this.setBorder(new LineBorder(Color.gray));
	setText(text);
	this.image = image;
	ImageIcon imIcon = new ImageIcon(image);
	icon = imIcon.getImage();
	if (calculerCouleurDominante) {
	    this.couleurText = getDominante();
	    setForeground(couleurText);
	}
    }

    /**
     * cf JLabelImage(String image, String text, boolean calculerCouleurDominante)
     *
     * @param image
     * @param text
     */
    public JLabelImage(String image, String text) {
	this(image, text, false);
    }

    /**
     * cf JLabelImage(String image, String text, boolean calculerCouleurDominante)
     *
     * @param image
     */

    public JLabelImage(String image) {
	this(image, "", false);
    }

    JLabelImage() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void paintComponent(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;
	//lissage du texte
	RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
		RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	g2.setRenderingHints(rh);

	//calculs de la largeur et de la hauteur du texte, et de la largeur du composant
	FontMetrics fm = getToolkit().getFontMetrics(this.getFont());
	int textWidth = fm.stringWidth(text);
	int textHeight = fm.getHeight();
	int labelWidth = this.getWidth();
	//si jamais le texte est plus large que le composant, on remplace
	//les lettres qui ne passent pas par deux points
	if ((labelWidth < fm.stringWidth(text))) {
	    StringBuffer temText = new StringBuffer(text);
	    while (labelWidth < fm.stringWidth(temText + "..")) {
		//suppression de l'exception si jamais la chaine est vide
		if (temText.length() != 0)
		    temText.delete(temText.length() - 1, temText.length());
		else
		    break;

	    }
	    this.changeText(temText + "..");
	    textWidth = fm.stringWidth(temText + "..");
	} else
	    this.changeText(saveText);

	super.paintComponent(g);
	//redimensionnement de l'image
	scale();
	//dessin de l'image de fond
	g.drawImage(icon, 0, 0, this);
	int x, y;
	//placement du texte en fonction de l'alignement choisi
	switch (Halignement) {
	//Centre
	case 0:
	    x = this.getWidth() / 2 - textWidth / 2;
	    break;
	//gauche
	case 2:
	    x = 0;
	    break;
	//droit
	case 4:
	    x = this.getWidth() - textWidth;
	    break;
	default:
	    x = this.getWidth() / 2;
	}
	switch (Valignement) {
	//centre
	case 0:
	    y = this.getHeight() / 2 + textHeight / 3;
	    break;
	//haut
	case 8:
	    y = textHeight;
	    break;
	//bas
	case 16:
	    y = this.getHeight() - 2;
	    break;
	default:
	    y = this.getHeight() / 2;
	}
	g.drawString(text, x, y);
    }

    /**
     * Fonction qui permet de redimensionner l'image en fonction de la taille du JLabel
     *
     */
    private void scale() {
	imIcon = new ImageIcon(image);
	icon = imIcon.getImage();
	BufferedImage buf = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
	Graphics2D g = buf.createGraphics();
	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	g.drawImage(icon, 0, 0, this.getWidth(), this.getHeight(), null);
	g.dispose();
	icon = buf;
    }

    @Override
    public void setHorizontalTextPosition(int align) {
	if (align != 0 && align != 2 && align != 4) {
	    try {
		throw new BadNumberException(align);

	    } catch (BadNumberException e) {
		System.exit(0);
	    }
	}
	Halignement = align;
    }

    @Override
    public void setVerticalTextPosition(int align) {

	if (align != 0 && align != 8 && align != 16) {
	    try {
		throw new BadNumberException(align);

	    } catch (BadNumberException e) {
		System.exit(0);
	    }
	}
	Valignement = align;
    }

    @Override
    public void setText(String text) {
	this.saveText = text;
	this.text = text;
    }

    private void changeText(String text) {
	this.text = text;
    }

    /**
     * Fonction qui calcule la couleur dominante de l'image de fond.
     * Il s'agit en fait juste d'une moyenne : les valeurs de rouge, vert
     * et bleu de chaque pixels sont additionnées puis divisés par le nombre
     * de pixels.
     * La couleur retournée est la couleur inverse de la couleur dominante
     *
     *
     * @return
     */
    private Color getDominante() {
	ImageIcon imIcon = new ImageIcon(image);
	int[] pixels = new int[imIcon.getIconWidth() * imIcon.getIconHeight()];
	PixelGrabber pg = new PixelGrabber(imIcon.getImage(), 0, 0, imIcon.getIconWidth(), imIcon.getIconHeight(),
		pixels, 0, imIcon.getIconWidth());
	try {
	    pg.grabPixels();
	} catch (InterruptedException e) {
	}
	int red = 0;
	int green = 0;
	int blue = 0;
	for (int i = 0; i < pixels.length; i++) {
	    int c = pixels;
	    red += (c & 0x00ff0000) >> 16;
	    green += (c & 0x0000ff00) >> 8;
	    blue += c & 0x000000ff;
	}

	int mr = red / pixels.length;
	int mg = green / pixels.length;
	int mb = blue / pixels.length;
	return (new Color(255 - mr, 255 - mg, 255 - mb));
    }

    public void staticSetInverseCouleurDominante() {
	setForeground(getDominante());
    }

    class BadNumberException extends Exception {
	int i;

	public BadNumberException(int i) {
	    this.i = i;
	}

        @Override
	public void printStackTrace() {
	    System.err.println(i + " ne peut pas etre utilise ici ;)");
	}

    }

    public static void main(String[] args) {
	JFrame frame = new JFrame();
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	JLabelImage label = new JLabelImage("bg.png", "le texte du label", true);
	label.setPreferredSize(new Dimension(300, 300));
	label.setHorizontalTextPosition(JLabelImage.CENTER);
	label.setVerticalTextPosition(JLabelImage.CENTER);
	label.setLayout(new BorderLayout());

	frame.add(label);
	frame.pack();
	frame.setVisible(true);
    }

}
#8

عندك مشكله فى كيفيه الحصول على الصوره

ثانى شىء وهو عمليه الـ scale للصوره فيها خطأ

مما يؤدى لعدم ظهور الصوره

شىء تانى اخر انا لا اعتقد ان عمليه الـ Scaling تقوم باى شىء

فهى فقط تقوم باعاقه الكود

حيث انه لا يتم من الاساس تغير الصوره (الكود يتكلم بذلك )

يعنى فى الصوره الاصليه تحصل على

this.getWidth(), this.getHeight()

وايضا فى الصوره المصغره

فبالتالى فى كلتا الحالتين واحد

يمكنك استخدام الداله

icon.getScaledInstance(width, height, hints);

ترجع لك صوره حسب الـ width , height معطاه

اعتقد ان الكود مخربط كتير

اما بالنسبه للكود الذى يعمل

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 *
 * @author Aymane
 */
public class JLabelImage extends JLabel {

	private Image icon;
	private String image;
	private String saveText = "";
	private String text = "";
	private int Halignement = 0;
	private int Valignement = 0;
	public static int LEFT = 2;
	public static int RIGHT = 4;
	public static int CENTER = 0;
	public static int TOP = 8;
	public static int BOTTOM = 16;
	public Color couleurText;
	ImageIcon imIcon;

	/**
 	* Constructeur qui permet de faire gérer au Label un text
 	* et une image. par défaut, le texte est aligné au centre
 	* verticalement et horizontalement.
 	* le booléean calculerCouleurDominante indique au label
 	* de calculer la couleur dominante de l'image, et de régler
 	* la couleur du texte en conséquence (pas encore vraiment au point)
 	*
 	* @param image
 	* @param text
 	* @param calculerCouleurDominante
 	*/
	public JLabelImage(String image, String text, boolean calculerCouleurDominante) {
    	//this.setBorder(new LineBorder(Color.gray));
    	setText(text);
    	this.image = image;
    	icon = new ImageIcon(getClass().getResource(image)).getImage();
    	if (calculerCouleurDominante) {
        	this.couleurText = getDominante();
        	setForeground(couleurText);
    	}
	}

	/**
 	* cf JLabelImage(String image, String text, boolean calculerCouleurDominante)
 	*
 	* @param image
 	* @param text
 	*/
	public JLabelImage(String image, String text) {
    	this(image, text, false);
	}

	/**
 	* cf JLabelImage(String image, String text, boolean calculerCouleurDominante)
 	*
 	* @param image
 	*/
	public JLabelImage(String image) {
    	this(image, "", false);
	}

	JLabelImage() {
    	throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void paintComponent(Graphics g) {
    	Graphics2D g2 = (Graphics2D) g;
    	//lissage du texte
    	RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
            	RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    	g2.setRenderingHints(rh);

    	//calculs de la largeur et de la hauteur du texte, et de la largeur du composant
    	FontMetrics fm = getToolkit().getFontMetrics(this.getFont());
    	int textWidth = fm.stringWidth(text);
    	int textHeight = fm.getHeight();
    	int labelWidth = this.getWidth();
    	//si jamais le texte est plus large que le composant, on remplace
    	//les lettres qui ne passent pas par deux points
    	if ((labelWidth < fm.stringWidth(text))) {
        	StringBuffer temText = new StringBuffer(text);
        	while (labelWidth < fm.stringWidth(temText + "..")) {
            	//suppression de l'exception si jamais la chaine est vide
            	if (temText.length() != 0) {
                	temText.delete(temText.length() - 1, temText.length());
            	} else {
                	break;
            	}

        	}
        	this.changeText(temText + "..");
        	textWidth = fm.stringWidth(temText + "..");
    	} else {
        	this.changeText(saveText);
    	}

    	super.paintComponent(g);
    	//redimensionnement de l'image
//    	scale();
    	//dessin de l'image de fond
    	g.drawImage(icon, 0, 0, this);
    	int x, y;
    	//placement du texte en fonction de l'alignement choisi
    	switch (Halignement) {
        	//Centre
        	case 0:
            	x = this.getWidth() / 2 - textWidth / 2;
            	break;
        	//gauche
        	case 2:
            	x = 0;
            	break;
        	//droit
        	case 4:
            	x = this.getWidth() - textWidth;
            	break;
        	default:
            	x = this.getWidth() / 2;
    	}
    	switch (Valignement) {
        	//centre
        	case 0:
            	y = this.getHeight() / 2 + textHeight / 3;
            	break;
        	//haut
        	case 8:
            	y = textHeight;
            	break;
        	//bas
        	case 16:
            	y = this.getHeight() - 2;
            	break;
        	default:
            	y = this.getHeight() / 2;
    	}
    	g.drawString(text, x, y);
	}

	/**
 	* Fonction qui permet de redimensionner l'image en fonction de la taille du JLabel
 	*
 	*/
	private void scale() {
    	imIcon = new ImageIcon(image);
    	icon = imIcon.getImage();
    	BufferedImage buf = new BufferedImage(this.getWidth(), this.getHeight(),
            	BufferedImage.TYPE_INT_ARGB);
    	Graphics2D g = buf.createGraphics();
    	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            	RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    	g.drawImage(icon, 0, 0, this.getWidth(), this.getHeight(), null);
    	g.dispose();
    	icon = buf;
	}

	@Override
	public void setHorizontalTextPosition(int align) {
    	if (align != 0 && align != 2 && align != 4) {
        	try {
            	throw new BadNumberException(align);

        	} catch (BadNumberException e) {
            	System.exit(0);
        	}
    	}
    	Halignement = align;
	}

	@Override
	public void setVerticalTextPosition(int align) {

    	if (align != 0 && align != 8 && align != 16) {
        	try {
            	throw new BadNumberException(align);

        	} catch (BadNumberException e) {
            	System.exit(0);
        	}
    	}
    	Valignement = align;
	}

	@Override
	public void setText(String text) {
    	this.saveText = text;
    	this.text = text;
	}

	private void changeText(String text) {
    	this.text = text;
	}

	/**
 	* Fonction qui calcule la couleur dominante de l'image de fond.
 	* Il s'agit en fait juste d'une moyenne : les valeurs de rouge, vert
 	* et bleu de chaque pixels sont additionnées puis divisés par le nombre
 	* de pixels.
 	* La couleur retournée est la couleur inverse de la couleur dominante
 	*
 	*
 	* @return
 	*/
	private Color getDominante() {
    	ImageIcon imIcon = new ImageIcon(image);
    	int[] pixels = new int[imIcon.getIconWidth() * imIcon.getIconHeight()];
    	PixelGrabber pg = new PixelGrabber(imIcon.getImage(), 0, 0, imIcon.getIconWidth(), imIcon.getIconHeight(),
            	pixels, 0, imIcon.getIconWidth());
    	try {
        	pg.grabPixels();
    	} catch (InterruptedException e) {
    	}
    	int red = 0;
    	int green = 0;
    	int blue = 0;
    	for (int i = 0; i < pixels.length; i++) {
        	int c = pixels;
        	red += (c & 0x00ff0000) >> 16;
        	green += (c & 0x0000ff00) >> 8;
        	blue += c & 0x000000ff;
    	}

    	int mr = red / pixels.length;
    	int mg = green / pixels.length;
    	int mb = blue / pixels.length;
    	return (new Color(255 - mr, 255 - mg, 255 - mb));
	}

	public void staticSetInverseCouleurDominante() {
    	setForeground(getDominante());
	}

	class BadNumberException extends Exception {

    	int i;

    	public BadNumberException(int i) {
        	this.i = i;
    	}

    	@Override
    	public void printStackTrace() {
        	System.err.println(i + " ne peut pas etre utilise ici ;)");
    	}
	}

	public static void main(String[] args) {
    	JFrame frame = new JFrame();
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	JLabelImage label = new JLabelImage("/images/image.jpg", "le texte du label", true);
    	label.setPreferredSize(new Dimension(300, 300));
    	label.setHorizontalTextPosition(JLabelImage.CENTER);
    	label.setVerticalTextPosition(JLabelImage.CENTER);
    	label.setLayout(new BorderLayout());

    	frame.add(label);
    	frame.pack();
    	frame.setVisible(true);
	}
}

بالتوفيق

Software Developer
Mahmoudkelany.com


 

#9

إذا كنت مستاء من ردي فهذا شأنك

لكني مستاء أكثر من طريقة ردك على من يريد المساعدة

لست هنا من أمس أو أول أمس

لي هنا سنين وأعرف الناس وأخبرهم

فأنت أحد اثنين

إما أنك لم تجرب الموضوع أصلاً كما قلت من قبل

أو أنك تستثقل من كتابة ما حصل معك

وفي كلا الحالتين أنت لدي في قائمة الحظر

تحياتي

حزمة المحرك الإصدارة 0.8

أي أحد يجد أني ظلمته فليراسلني

وبإذن الله لو كان له حق سيأخذه

728x90.png

مواضيع مشابهة

عدد الزوار حالياً

المتواجدون خلال آخر دقيقتين · يتحدّث كل ٣٠ ثانية

—الإجمالي—أعضاء مسجّلون—زوار بدون تسجيل

جارٍ التحقق من المتواجدين…