PrintScreen image capturing - java

I need to write a program that I will create a runnable jar and distribute. The functions should be like below:
when double click the jar, it will open a window.
it will ask the path where to save the image files.
it will then ask whether to add any prefix / suffix / both on every image along with timestamp for unique name.
it will also ask what image format to use.
the app can be minimized and closed
it will take a full screenshot whenever PrintScreen is pressed and save.
Please provide a programme that is complete. I have gathered pieces but could not put them in one. Here is my code :-
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainClass
{
static String location = "";
static String prefix = "";
static String format = "";
static Date timestamp = new Date();
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
JFrame f = new JFrame("Text Field Examples");
f.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField("Enter Location To Save Image Files");
textField1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField1.setText("");
}
});
textField1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location = textField1.getText();
System.out.println(location);
}
});
f.getContentPane().add(textField1);
final JTextField textField2 = new JTextField("Enter Prefix or Leave Empty");
textField2.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField2.setText("");
}
});
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
prefix = textField2.getText();
System.out.println(prefix);
}
});
f.getContentPane().add(textField2);
String jlistData[] =
{
"GIF",
"PNG",
"JPG"
};
final JComboBox jlist = new JComboBox<String>( jlistData );
jlist.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
format = jlist.getSelectedItem().toString();
System.out.println(format);
}
});
f.getContentPane().add(jlist);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
try
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
RenderedImage image = (RenderedImage) t.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(image, format, new File(new String(location+prefix+image+timestamp)));
}
catch(Exception e)
{
}
}
}
The first try catch block can open a window, take image format, prefix and storage location. The second try catch block alone can take screen shot when run not when printscreen key is pressed but with the first try catch it does not print anything. So, what to do to take the screenshot when printscreen key is pressed ?

I have approached the solution in a little bit another way.
As people always works with mouse while on online meeting, I removed the clause of PrintScreen button from keyboard and instead the attendees can click on swing window button to capture screen.
My solution as follows:
MainClass.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainClass{
static String location = "";
static String prefix = "";
static String format = "";
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
final JFrame f = new JFrame("ENTER ALL DETAILS BELOW");
f.setAlwaysOnTop(true);
f.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField("Enter Location To Save Image Files");
textField1.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField1.setText("");
}
});
f.getContentPane().add(textField1);
final JTextField textField2 = new JTextField("Enter MeetingID");
textField2.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
textField2.setText("");
}
});
f.getContentPane().add(textField2);
String jlistData[] =
{
"GIF",
"PNG",
"JPG"
};
final JComboBox jlist = new JComboBox<String>( jlistData );
f.getContentPane().add(jlist);
final JButton jButton = new JButton("OKAY");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location = textField1.getText();
prefix = textField2.getText();
format = jlist.getSelectedItem().toString();
System.out.println(location);
System.out.println(prefix);
System.out.println(format);
f.setVisible(false);
PrintButton.printButton();
}
});
f.getContentPane().add(jButton);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
}
}
PrintButton.java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class PrintButton
{
static void printButton()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//final JFrame f = new JFrame("Print Screen App");
Dlg f = new Dlg(new JFrame(), "PRINT");
f.setAlwaysOnTop(true);
f.getContentPane().setLayout(new FlowLayout());
final JButton jButton = new JButton("OKAY");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PrintScreen.printScreen();
}
});
f.getContentPane().add(jButton);
f.pack();
f.setVisible(true);
}
catch (Exception evt)
{
evt.printStackTrace();
}
}
}
class Dlg extends JDialog {
public Dlg(JFrame frame, String str) {
super(frame, str);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
PrintScreen.java
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.image.RenderedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class PrintScreen
{
static void printScreen()
{
try
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
RenderedImage image = (RenderedImage) t.getTransferData(DataFlavor.imageFlavor);
ImageIO.write(image, MainClass.format, new File(new String(MainClass.location+ "\\" +MainClass.prefix+"_"+System.currentTimeMillis()+"."+MainClass.format)));
}
catch(Exception e)
{
}
}
}
I hope this will be helpfull to some freinds. Is there any scope to improve this?
How to create a installable version for Windows and Linux/Ubuntu and Linux/RedHat ?

Related

Need to display ImageIcon when Jbutton is pressed

I am having trouble getting my Image to display when I click my Jbutton, the test sysoutprint works but the Image does not. Any Ideas on what to do I am very lost! The Image is an easter egg for a school project, feel free to make comments. Should I use something besides a ImageIcon or what not?
Also if there are any other errors please let me know!
package GUI;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView{
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox
private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;
public void codeNameView(){
main = new JFrame("CodeNames");
main.setSize(600, 900);
main.setVisible(true);
//dropdown menu for quit and new game
String[] choice = {" " , "NewGame" , "Quit"};
dropDown = new JComboBox(choice);
//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel,BorderLayout.NORTH);
//easter egg
JButton easterButt = new JButton("Pass CSE 116");
JLabel eastLbl = new JLabel();
//added button to JLabel
eastLbl.add(easterButt);
try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);
}catch(Exception ex){
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(eastLbl);
eastLbl.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
eastLbl.setIcon(eastImg);
System.out.print("test");
}
//Ignore
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener(){
/**
* Allows for the user to select New Game or Quit and have the game perform said action
*/
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
if (selectedOption.equals("Quit")) {
main.dispose();
}else if(selectedOption.equals("NewGame")){
codeNameView();
System.out.print("yolo");
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainView x = new mainView();
// create a instance on mainview to run instead of using static methods
}
});
}
}
The primary issue seems to be right here
try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);
}catch(Exception ex){
System.out.print(ex);
}
The path is referencing a resource within the context of your src path. You should never reference src in your code, it won't exist once the program is exported (to a Jar or run on a different computer)
Instead, you should consider using Class#getResource to obtain a reference to the image and I'd personally use ImageIO.read over ImageIcon as a personal preference.
try{
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
}catch(Exception ex){
System.out.print(ex);
}
And, your next problem is, you're trying to add a JLabel to a JButton, expect, a JButton has not layout manager AND JButton already has support for display an image, so instead, you should be doing something more like...
JButton easterButt = new JButton("Pass CSE 116");
//JLabel eastLbl = new JLabel();
//added button to JLabel
//eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});
You really should take a closer look at How to Use Buttons, Check Boxes, and Radio Buttons
Test Code
This is the code I used to test the solutions suggested above
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView {
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox
private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;
public void codeNameView() {
main = new JFrame("CodeNames");
main.setSize(600, 900);
//dropdown menu for quit and new game
String[] choice = {" ", "NewGame", "Quit"};
dropDown = new JComboBox(choice);
//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel, BorderLayout.NORTH);
//easter egg
JButton easterButt = new JButton("Pass CSE 116");
// JLabel eastLbl = new JLabel();
// //added button to JLabel
// eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener() {
/**
* Allows for the user to select New Game or Quit and have the game
* perform said action
*/
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
if (selectedOption.equals("Quit")) {
main.dispose();
} else if (selectedOption.equals("NewGame")) {
codeNameView();
System.out.print("yolo");
}
}
});
main.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("Hello");
mainView x = new mainView();
x.codeNameView();
// create a instance on mainview to run instead of using static methods
}
});
}
}
Try using something like this:
String path = "C:\\Users\\nabeelkhalid\\git\\s18semesterproject-b4-zigzag1\\src\\GUI\\MatthewPhoto.jpg";

When my app opens a new java program, how do I prevent my app from repainting itself with a new theme?

Basically what I'm doing is creating a swing application that acts as a launcher. All it does is gives the user 3 options they can choose from to open a new java application. The 3 different java applications all have different themes, and one doesn't have a theme at all. I'm trying to get it so when I select an option, my launcher app doesn't repaint it self to what the new program is. I want the launcher to maintain its theme.
I'm probably not using EventQueue right but I'm not sure which one to use.
package wind;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.ParseException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel;
public class Launcher {
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton btn1, btn2, btn3;
private GridBagConstraints gbc = new GridBagConstraints();
private JMenuBar menuBar;
private JMenu menu, menu2, menu3, menu4;
private JMenuItem menuItem, menuItem2, menuItem3, menuItem4,
menuItem5, menuItem6, menuItem7, menuItem8, menuItem9, menuItem10,
menuItem11, menuItem12, menuItem13, submenu1, submenu2, submenu3, submenu4, submenu5,
submenu6, submenu7, submenu8, submenu9, submenu10;
JFrame frame;
public Launcher() {
JFrame.setDefaultLookAndFeelDecorated(true);
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
try {
UIManager.setLookAndFeel(new SyntheticaAluOxideLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
frame = new JFrame();
frame.setTitle("Project Wind Client Launcher");
Image icon = getImage("windicon.png");
if (icon != null)
frame.setIconImage(icon);
components();
frame.add(mainPanel());
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setResizable(false);
frame.setVisible(true);
}
});
}
private JPanel mainPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
btn1 = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("/resources/gui.png"));
btn1.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
btn1.setToolTipText("Click here to launch the client with a graphic user interface.");
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runGUIMode(e);
}
});
//btn1.setBorder(null);
btn1.setOpaque(true);
btn1.setContentAreaFilled(false);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.25;
mainPanel.add(btn1, gbc);
btn2 = new JButton();
try {
Image img2 = ImageIO.read(getClass().getResource("/resources/nogui.png"));
btn2.setIcon(new ImageIcon(img2));
} catch (IOException ex) {
}
btn2.setToolTipText("This will launch the client without a graphic user interface.");
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runNoGUI(e);
}
});
btn2.setContentAreaFilled(false);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.weightx = 0.25;
mainPanel.add(btn2, gbc);
btn3 = new JButton();
try {
Image img2 = ImageIO.read(getClass().getResource("/resources/app.png"));
btn3.setIcon(new ImageIcon(img2));
} catch (IOException ex) {
}
btn3.setToolTipText("This will launch the client in application mode.");
btn3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runApplicationMode(e);
}
});
btn3.setContentAreaFilled(false);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.25;
mainPanel.add(btn3, gbc);
return mainPanel;
}
private void runApplicationMode(ActionEvent e) {
new FrameListener(FrameListener.LaunchMode.APPLICATION);
}
private void runNoGUI(ActionEvent e) {
new FrameListener(FrameListener.LaunchMode.NOGUI);
}
private void runGUIMode(ActionEvent e) {
new FrameListener(FrameListener.LaunchMode.GUI);
}
public void components() {
menuBar = new JMenuBar();
menu = new JMenu("File");
menu2 = new JMenu("Links");
menu3 = new JMenu("Guides");
menu4 = new JMenu("Help");
menuBar.add(menu);
menuBar.add(menu2);
menuBar.add(menu3);
menuBar.add(menu4);
menuItem = new JMenuItem("Exit");
menuItem.setToolTipText("Click here to exit the client launcher.");
menuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
exitClient(e);
}
});
menuItem2 = new JMenuItem("Update");
menuItem2.setToolTipText("Click here to update your client.");
menuItem2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateClient(e);
}
});
menuItem3 = new JMenuItem("Check Version");
menuItem3.setToolTipText("Click here to check the version of your client.");
menuItem3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
checkVersion(e);
}
});
menuItem13 = new JMenuItem("Hide Launcher");
menuItem13.setToolTipText("Click here to hide the client launcher.");
menuItem13.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
hideLauncher(e);
}
});
menu.add(menuItem3);
menu.add(menuItem);
menu.add(menuItem13);
menu.add(menuItem2);
menuItem4 = new JMenuItem("Home");
menuItem4.setToolTipText("Click here to open up your homepage.");
menuItem4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
home(e);
}
});
menuItem5 = new JMenuItem("YouTube");
menuItem5.setToolTipText("Click here to open up YouTube.");
menuItem5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem5)
openURL("http://youtube.com");
}
});
menuItem6 = new JMenuItem("Twitter");
menuItem6.setToolTipText("Click here to open up Twitter.");
menuItem6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem6)
openURL("http://twitter.com");
}
});
menuItem10 = new JMenuItem("Twitch");
menuItem10.setToolTipText("Click here to open up Twitch.");
menuItem10.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menuItem10)
openURL("http://twitch.tv");
}
});
menu2.add(menuItem4);
menu2.add(menuItem10);
menu2.add(menuItem6);
menu2.add(menuItem5);
menuItem7 = new JMenu("Combat");
menuItem7.setToolTipText("Click here to view more options related to combat.");
submenu1 = new JMenu("Attack");
submenu2 = new JMenu("Strength");
submenu3 = new JMenu("Defence");
submenu4 = new JMenu("Hitpoints");
submenu5 = new JMenu("Prayer");
submenu6 = new JMenu("Ranged");
submenu7 = new JMenu("Magic");
menuItem7.add(submenu1);
menuItem7.add(submenu3);
menuItem7.add(submenu4);
menuItem7.add(submenu5);
menuItem7.add(submenu7);
menuItem7.add(submenu6);
menuItem7.add(submenu2);
menuItem8 = new JMenu("Skilling");
menuItem8.setToolTipText("Click here to view more options about skilling.");
submenu8 = new JMenu("Cooking");
submenu9 = new JMenu("Fishing");
submenu10 = new JMenu("Fletching");
menuItem8.add(submenu8);
menuItem8.add(submenu9);
menuItem8.add(submenu10);
menuItem9 = new JMenu("Money Making");
menuItem9.setToolTipText("Click here to view more options related to money making.");
menu3.add(menuItem7);
menu3.add(menuItem8);
menu3.add(menuItem9);
menuItem11 = new JMenu("Report a Bug");
menuItem11.setToolTipText("See any bugs? Click here and report them.");
menuItem12 = new JMenu("Commands");
menuItem12.setToolTipText("Click here to see which commands are available.");
menu4.add(menuItem11);
menu4.add(menuItem12);
}
private void exitClient(ActionEvent e) {
System.exit(1);
}
private void updateClient(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Client will now update.");
}
private void checkVersion(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Your files are fully updated.");
}
private void hideLauncher(ActionEvent e) {
frame.setState(Frame.ICONIFIED);
}
private void home(ActionEvent e) {
openURL("http://google.com");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Launcher();
}
});
}
public void openURL(String url) {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI(url);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
private Image getImage(String name) {
String url = "https://dl.dropboxusercontent.com/u/5173165/icons/" + name;
try {
File f = new File(name);
if (f.exists())
return ImageIO.read(f.toURI().toURL());
Image img = ImageIO.read(new URL(url));
if (img != null) {
ImageIO.write((RenderedImage) img, "PNG", f);
return img;
}
} catch (MalformedURLException e) {
System.out.println("Error connecting to image URL: " + url);
} catch (IOException e) {
System.out.println("Error reading file: " + name);
}
return null;
}
}
This is a class that creates the new application the user selects
package wind;
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import wind.gui.Application;
import wind.gui.Gui;
import wind.web.WebClient;
public class FrameListener {
static JLabel image;
LaunchMode mode;
public FrameListener(LaunchMode mode) {
this.mode = mode;
initClient();
}
public enum LaunchMode {
APPLICATION,
GUI,
NOGUI;
}
public void initClient() {
switch(mode) {
case APPLICATION:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Application();
}
});
break;
case GUI:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Gui();
}
});
break;
case NOGUI:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new WebClient(null);
}
});
break;
default:
mode = LaunchMode.GUI;
break;
}
}
}
This Swing based Launcher uses ProcessBuilder to run programs in a separate JVM. You can assess its suitability for your application by running it with a non-default Look & Feel. Note MetalLookAndFeel on the left and AquaLookAndFeel on the right in the illustration below.
$ java -Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel \
-cp build/classes gui.Launcher

java drop and drag label to join correct image

this code is only allowing me to reject a string the second time to try to drop in a textArea where there is all ready a string.
public GridLayoutTest() {
JFrame frame = new JFrame("GridLayout test");
connection = getConnection();
try {
statement = (PreparedStatement) connection
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
}
}
catch (SQLException e) {
e.printStackTrace();}
}
So, two things, first...
public void DropTargetTextArea(String string1, String string2) {
Isn't a constructor, it's a method, note the void. This means that it is never getting called. It's also the reason why DropTargetTextArea textArea = new DropTargetTextArea(); works, when you think it shouldn't.
Second, you're not maintaining a reference to the values you pass in to the (want to be) constructor, so you have no means to references them later...
You could try using something like...
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true);
}
And then use something like...
if (values[0].equals(dragContents) || values[1].equals(dragContents)) {
In the drop method.
In your dragEnter, dragOver and dropActionChanged methods you have the oppurtunity to accept or reject the drag action using something like dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); or dtde.rejectDrag();
Updated with test code
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DragAndDropExample {
public static void main(String[] args) {
ImageIcon ii1 = new ImageIcon("C:\\Users\\Desktop\\home.jpg");
ImageIcon ii = new ImageIcon("C:\\Users\\Desktop\\images (2).jpg");
// Create a frame
JFrame frame = new JFrame("test");
JLabel label = new JLabel(ii);
JLabel label1 = new JLabel(ii1);
JPanel panel = new JPanel(new GridLayout(2, 4, 10, 10));
JLabel testLabel = new DraggableLabel("test");
JLabel testingLabel = new DraggableLabel("testing");
panel.add(testLabel);
panel.add(testingLabel);
panel.add(label);
panel.add(label1);
Component textArea = new DropTargetTextArea("test", "testing");
frame.add(textArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class DraggableLabel extends JLabel implements DragGestureListener, DragSourceListener {
DragSource dragSource1;
public DraggableLabel(String text) {
setText(text);
dragSource1 = new DragSource();
dragSource1.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent evt) {
Transferable transferable = new StringSelection(getText());
dragSource1.startDrag(evt, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent evt) {
System.out.println("Drag enter");
}
public void dragOver(DragSourceDragEvent evt) {
System.out.println("Drag over");
}
public void dragExit(DragSourceEvent evt) {
System.out.println("Drag exit");
}
public void dropActionChanged(DragSourceDragEvent evt) {
System.out.println("Drag action changed");
}
public void dragDropEnd(DragSourceDropEvent evt) {
System.out.println("Drag action End");
}
}
public static class DropTargetTextArea extends JLabel implements DropTargetListener {
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void dragEnter(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag enter");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragOver(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag over");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragExit(DropTargetEvent evt) {
System.out.println("Drop exit");
}
public void dropActionChanged(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject dropActionChanged");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void drop(DropTargetDropEvent evt) {
if (!getText().isEmpty()) {
evt.rejectDrop();
} else {
try {
Transferable transferable = evt.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String dragContents = (String) transferable.getTransferData(DataFlavor.stringFlavor);
evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
if (values[0].equals(dragContents) || (values[1]).equals(dragContents)) {
System.out.println("Accept Drop");
setText(getText() + " " + dragContents);
evt.getDropTargetContext().dropComplete(true);
} else {
System.out.println("Reject Drop");
}
}
} catch (IOException e) {
evt.rejectDrop();
evt.dropComplete(false);
} catch (UnsupportedFlavorException e) {
}
}
}
}
}

Can't access variables for SwingWorker

I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Java string replaceAll()

I've been wondering if for example:
JTextPane chatTextArea = new JTextPane();
s.replaceAll(":\\)", emoticon());
public String emoticon(){
chatTextArea.insertIcon(new ImageIcon(ChatFrame.class.getResource("/smile.png")));
return "`";
}
can put a picture and a "`" everywhere ":)" is found. When I run it like this if s contains a ":)" then the whole s gets replaced just by the icon.
Is there a way to do it?
Here is a small example I made (+1 to #StanislavL for the original), simply uses DocumentListener and checks when a matching sequence for an emoticon is entered and replaces it with appropriate image:
NB: SPACE must be pressed or another character/emoticon typed to show image
import java.awt.Dimension;
import java.awt.Image;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Utilities;
public class JTextPaneWithEmoticon {
private JFrame frame;
private JTextPane textPane;
static ImageIcon smiley, sad;
static final String SMILEY_EMOTICON = ":)", SAD_EMOTICON = ":(";
String[] emoticons = {SMILEY_EMOTICON, SAD_EMOTICON};
private void initComponents() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textPane = new JTextPane();
//add docuemntlistener to check for emoticon insert i.e :)
((AbstractDocument) textPane.getDocument()).addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(final DocumentEvent de) {
//We should surround our code with SwingUtilities.invokeLater() because we cannot change document during mutation intercepted in the listener.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
StyledDocument doc = (StyledDocument) de.getDocument();
int start = Utilities.getRowStart(textPane, Math.max(0, de.getOffset() - 1));
int end = Utilities.getWordStart(textPane, de.getOffset() + de.getLength());
String text = doc.getText(start, end - start);
for (String emoticon : emoticons) {//for each emoticon
int i = text.indexOf(emoticon);
while (i >= 0) {
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start + i).getAttributes());
if (StyleConstants.getIcon(attrs) == null) {
switch (emoticon) {//check which emtoticon picture to apply
case SMILEY_EMOTICON:
StyleConstants.setIcon(attrs, smiley);
break;
case SAD_EMOTICON:
StyleConstants.setIcon(attrs, sad);
break;
}
doc.remove(start + i, emoticon.length());
doc.insertString(start + i, emoticon, attrs);
}
i = text.indexOf(emoticon, i + emoticon.length());
}
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(300, 300));
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {//attempt to get icon for emoticons
smiley = new ImageIcon(ImageIO.read(new URL("http://facelets.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/e/m/emoticons0001.png")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
sad = new ImageIcon(ImageIO.read(new URL("http://zambia.primaryblogger.co.uk/files/2012/04/sad.jpg")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTextPaneWithEmoticon().initComponents();
}
});
}
}
References:
How to add smileys in java swing?

Categories