Je développe une application de discussion dans Java Swing dans laquelle j'aimerais ajouter des smileys, peut-on m'aider avec cela? P>
5 Réponses :
Vous pouvez copier ces caractères Unicode et les utiliser: ☺ P>
dans les chaînes Java, ce sera "\ u263a" code> et "\ u263b" code>. p>.
N'y a-t-il pas de jar séparé pour cela?
@harishtps: pas de pot; juste une police avec le glyphe requis. Voici un exemple .
Voici un code simple que j'ai trouvé il y a longtemps sur le Web. Je n'aime pas vraiment que cela utilise un auditeur de calet. Vous devriez probablement utiliser un document DocumentListener ou un document de document. Mais cela vous donnera une idée de la manière dont vous pouvez utiliser une icône personnalisée pour représenter un smiley.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class Smiley
extends JFrame {
//autoreplacing :) with picture
JTextPane p = new JTextPane();
public Smiley() throws Exception {
p.setEditorKit(new StyledEditorKit());
getContentPane().add(p, BorderLayout.CENTER);
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setIcon(attrs, getImage());
p.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
StyledDocument doc = (StyledDocument) p.getDocument();
String text = doc.getText(0, p.getDocument().getLength());
int index = text.indexOf(":)");
int start = 0;
while (index > -1) {
Element el = doc.getCharacterElement(index);
if (StyleConstants.getIcon(el.getAttributes()) == null) {
doc.remove(index, 2);
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setIcon(attrs, getImage());
doc.insertString(index, ":)", attrs);
}
start = index + 2;
index = text.indexOf(":)", start);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
});
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 400);
}
public static void main(String[] args) throws Exception {
Smiley test11 = new Smiley();
test11.show();
}
protected ImageIcon getImage() {
BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.setColor(Color.red);
g.drawOval(0, 0, 14, 14);
g.drawLine(4, 9, 9, 9);
g.drawOval(4, 4, 1, 1);
g.drawOval(10, 4, 1, 1);
return new ImageIcon(bi);
}
}
Vous devriez accepter la réponse de Stanislavl car il est l'auteur original du code.
Autoreplace sourit du texte avec des images appropriées dans Jeditorpane h3>
Pour prendre en charge l'autoraplaçage, nous avons besoin d'un
jeditorpane code> avecstylededitorkit code> (ou classe d'extension) pour fournir des images dans le texte. Nous allons simplement ajouter unDocumentListener code> pour traiter les événements d'insertion de texte. Après avoir inséré, nous vérifions si le texte modifié contient une chaîne de sourires - le ":)". S'il contient, nous remplaçons le texte de sourire avec une image appropriée. P>L'exemple ne fournit qu'un seul support de sourire - la chaîne ":)" mais peut être facile à prolonger. P>
import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.*; import java.awt.image.BufferedImage; import java.awt.*; public class AutoreplaceSmiles extends JEditorPane { static ImageIcon SMILE_IMG=createImage(); public static void main(String[] args) { JFrame frame = new JFrame("Autoreplace :) with Smiles images example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final AutoreplaceSmiles app = new AutoreplaceSmiles(); app.setEditorKit(new StyledEditorKit()); app.initListener(); JScrollPane scroll = new JScrollPane(app); frame.getContentPane().add(scroll); frame.setSize(400, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } public AutoreplaceSmiles() { super(); } private void initListener() { getDocument().addDocumentListener(new DocumentListener(){ public void insertUpdate(DocumentEvent event) { final DocumentEvent e=event; SwingUtilities.invokeLater(new Runnable() { public void run() { if (e.getDocument() instanceof StyledDocument) { try { StyledDocument doc=(StyledDocument)e.getDocument(); int start= Utilities.getRowStart(AutoreplaceSmiles.this,Math.max(0,e.getOffset()-1)); int end=Utilities.getWordStart(AutoreplaceSmiles.this,e.getOffset()+e.getLength()); String text=doc.getText(start, end-start); int i=text.indexOf(":)"); while(i>=0) { final SimpleAttributeSet attrs=new SimpleAttributeSet( doc.getCharacterElement(start+i).getAttributes()); if (StyleConstants.getIcon(attrs)==null) { StyleConstants.setIcon(attrs, SMILE_IMG); doc.remove(start+i, 2); doc.insertString(start+i,":)", attrs); } i=text.indexOf(":)", i+2); } } catch (BadLocationException e1) { e1.printStackTrace(); } } } }); } public void removeUpdate(DocumentEvent e) { } public void changedUpdate(DocumentEvent e) { } }); } static ImageIcon createImage() { BufferedImage res=new BufferedImage(17, 17, BufferedImage.TYPE_INT_ARGB); Graphics g=res.getGraphics(); ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.yellow); g.fillOval(0,0,16,16); g.setColor(Color.black); g.drawOval(0,0,16,16); g.drawLine(4,5, 6,5); g.drawLine(4,6, 6,6); g.drawLine(11,5, 9,5); g.drawLine(11,6, 9,6); g.drawLine(4,10, 8,12); g.drawLine(8,12, 12,10); g.dispose(); return new ImageIcon(res); } }
Désolé Stanislavl, je ne me souviens pas d'où j'ai copié ce code de. J'ai ajouté la référence du site à ma copie de la source.
Merci. Je pense que votre code est légèrement différent. Une autre image et un autre déclencheur sont définis. Serait préférable de créer l'image une fois et de passer la référence plutôt que de le recréer cependant. Mais définitivement à la fois que cela fonctionne :)
import java.awt.*;
public class SmileyFace {
public static void main(String[] args){
Frame f = new Frame("Smile Face");
f.setSize(500, 500);
f.setVisible(true);
Graphics g;
g = f.getGraphics();
while (true)
{
g.setColor(Color.black);
g.drawOval(100, 100, 100, 100);
g.setColor(Color.blue);
g.fillOval(120, 130, 20, 20);
g.fillOval(160, 130, 20, 20);
g.setColor(Color.blue);
g.setColor(Color.red);
g.drawLine(130, 170, 135, 175);
g.drawLine(135, 175, 163, 175);
g.drawLine(163, 175, 168, 170);
g.setColor(Color.green);
g.drawString("Hello", 210, 190);
}
}
}
package com.bulletapp.dragontest;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Smiley extends JApplet
{
public static final int FACE_DIAMETER = 200;
public static final int X_FACE = 100;
public static final int Y_FACE = 50;
public static final int EYE_WIDTH = 10;
public static final int EYE_HEIGHT = 20;
public static final int X_RIGHT_EYE = 155;
public static final int Y_RIGHT_EYE = 95;
public static final int X_LEFT_EYE = 230;
public static final int Y_LEFT_EYE = Y_RIGHT_EYE;
public static final int Y_NOSE = 135;
public static final int MOUTH_WIDTH = 100;
public static final int MOUTH_HEIGHT = 50;
public static final int X_MOUTH = 150;
public static final int Y_MOUTH = 175;
public static final int MOUTH_DEGREES_SHOWN = 180;
public int noseDiameter = 10; // initial value of the nose's diameter
public int xNose = 195; // initial value of the nose's x-position
public int mouthStartAngle = 180; // initial start angle of the mouth's arc
public Color eyeColor = Color.BLACK; // initial eye color
public void paint(Graphics graphics)
{
// Draw face circle:
graphics.setColor(Color.YELLOW);
graphics.fillOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER);
graphics.setColor(Color.BLACK);
graphics.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER);
// Draw eyes:
graphics.setColor(eyeColor);
graphics.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT);
graphics.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT);
// Draw nose:
graphics.setColor(Color.BLACK);
graphics.fillOval(xNose, Y_NOSE, noseDiameter, noseDiameter);
// Draw mouth:
graphics.setColor(Color.RED);
graphics.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT,
mouthStartAngle, MOUTH_DEGREES_SHOWN);
}
public void modifyFace()
{
String inputString;
Scanner keyboard = new Scanner(System.in);
System.out.println("Which would you like to change?\nMOUTH, NOSE, or EYES");
inputString = keyboard.nextLine();
// your code goes here, you do not have to modify any code before this point
// you do not have to modify code after this point
}
public static void addAppletToFrame(JApplet applet)
{
JFrame frame = new JFrame("Smiley!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(400, 400);
applet.init();
applet.start();
frame.setVisible(true);
}
public static void main(String[] args)
{
Smiley smiley = new Smiley();
smiley.modifyFace();
addAppletToFrame(smiley);
}
}
Vous devrez être plus spécifique que cela ... à moins que vous n'êtes satisfait des solutions telles que
system.out.print (":-)"); code>.Okie, smileys collectifs comme dans Gtalk ou Yahoo Messagers?