lotus03
asked on
How to display image in Java?
I would like to build a program in Java that can choose image file from folder and display it in the pane..how to do this?
thank u.
thank u.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
how bout calling the JPanel paintComponent method?? can it work?
To choose your file, use a JFileChooser (in the javax.swing package)
ASKER
thanks Javatm..
I have implement it in my program... but why the image can't be inserted?
When I try to insert Image, it will pop out a dialog box .. after I chosed the selected image file.. and click Open.. it seems like nothing happen.. coz the image still haven't being inserted.. why?
Anything wrong with my code? Thanks.
Below is my code:
========================== ==
package Editor1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.html.*;
public class UI1 extends JFrame {
public static final String APP_NAME = "JSP Editor";
protected JTextPane m_editor;
protected StyleSheet m_context;
protected HTMLDocument m_doc;
protected HTMLEditorKit m_kit;
// protected SimpleFilter m_htmlFilter;
protected JToolBar m_toolBar;
protected JFileChooser m_chooser;
protected File m_currentFile;
protected boolean m_textChanged = false;
public UI1() {
super(APP_NAME);
m_editor = new JTextPane();
m_kit = new HTMLEditorKit();
m_editor.setEditorKit(m_ki t);
JScrollPane ps = new JScrollPane(m_editor);
getContentPane().add(ps, BorderLayout.CENTER);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( 'F' );
//JMenuItem newItem = new JMenuItem("New");
// newItem.setMnemonic('n');
//fileMenu.add(newItem);
ImageIcon iconNew = new ImageIcon("New16.gif");
Action actionNew = new AbstractAction("New", iconNew) {
public void actionPerformed(ActionEven t e) {
if (!promptToSave())
return;
newDocument();
}
};
JMenuItem newItem = new JMenuItem(actionNew);
newItem.setMnemonic('n');
newItem.setAccelerator(Key Stroke.get KeyStroke(
KeyEvent.VK_N, InputEvent.CTRL_MASK));
fileMenu.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
fileMenu.add(openItem);
JMenuItem closeItem = new JMenuItem("Close");
closeItem.setMnemonic('L') ;
fileMenu.add(closeItem);
fileMenu.addSeparator();
JMenuItem saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
fileMenu.add(saveItem);
JMenuItem saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic('A' );
fileMenu.add(saveAsItem);
fileMenu.addSeparator();
JMenuItem printCodeItem = new JMenuItem("Print Code");
printCodeItem.setMnemonic( 'P');
fileMenu.add(printCodeItem );
JMenuItem previewItem = new JMenuItem("Preview");
previewItem.setMnemonic('R ');
fileMenu.add(previewItem);
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('T');
fileMenu.add(exitItem);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(fileMenu);
JMenu editMenu = new JMenu( "Edit" );
editMenu.setMnemonic( 'E' );
JMenuItem cutItem = new JMenuItem("Cut");
cutItem.setMnemonic('X');
editMenu.add(cutItem);
JMenuItem copyItem = new JMenuItem("Copy");
copyItem.setMnemonic('C');
editMenu.add(copyItem);
JMenuItem pasteItem = new JMenuItem("Paste");
pasteItem.setMnemonic('V') ;
editMenu.add(pasteItem);
bar.add(editMenu);
JMenu viewMenu = new JMenu( "View" );
viewMenu.setMnemonic( 'I' );
JMenuItem codeItem = new JMenuItem("Code");
viewMenu.add(codeItem);
JMenuItem designItem = new JMenuItem("Design");
viewMenu.add(designItem);
bar.add(viewMenu);
JMenu insertMenu = new JMenu( "Insert" );
JMenuItem imageItem = new JMenuItem("Image");
insertMenu.add(imageItem);
imageItem.addActionListene r(new ActionListener() {
public void actionPerformed (ActionEvent e) {
doInsertImageCommand();
}
});
bar.add(insertMenu);
}
public void doInsertImageCommand() {
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(thi s);
if (status == JFileChooser.APPROVE_OPTIO N) {
File file = chooser.getSelectedFile();
Icon icon = new ImageIcon (file.getAbsolutePath());
m_editor.insertIcon (icon);
}
}
protected void newDocument() {
m_doc = (HTMLDocument)m_kit.create DefaultDoc ument();
m_context = m_doc.getStyleSheet();
m_editor.setDocument(m_doc );
m_currentFile = null;
setTitle(APP_NAME+" ["+getDocumentName()+"]");
SwingUtilities.invokeLater (new Runnable() {
public void run() {
m_editor.scrollRectToVisib le(new Rectangle(0,0,1,1));
m_doc.addDocumentListener( new UpdateListener());
m_textChanged = false;
}
});
}
protected void openDocument() {
if (m_chooser.showOpenDialog( UI1.this) !=
JFileChooser.APPROVE_OPTIO N)
return;
File f = m_chooser.getSelectedFile( );
if (f == null || !f.isFile())
return;
m_currentFile = f;
setTitle(APP_NAME+" ["+getDocumentName()+"]");
UI1.this.setCursor(
Cursor.getPredefinedCursor (Cursor.WA IT_CURSOR) );
// Can't do this in thread - Pavel
try {
InputStream in = new FileInputStream(m_currentF ile);
m_doc = (HTMLDocument)m_kit.create DefaultDoc ument();
m_kit.read(in, m_doc, 0);
m_context = m_doc.getStyleSheet();
m_editor.setDocument(m_doc );
in.close();
}
catch (Exception ex) {
showError(ex, "Error reading file "+m_currentFile);
}
UI1.this.setCursor(Cursor. getPredefi nedCursor(
Cursor.DEFAULT_CURSOR));
SwingUtilities.invokeLater (new Runnable() {
public void run() {
m_editor.setCaretPosition( 1);
m_editor.scrollRectToVisib le(new Rectangle(0,0,1,1));
m_doc.addDocumentListener( new UpdateListener());
m_textChanged = false;
}
});
}
class UpdateListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
m_textChanged = true;
}
public void removeUpdate(DocumentEvent e) {
m_textChanged = true;
}
public void changedUpdate(DocumentEven t e) {
m_textChanged = true;
}
}
protected boolean promptToSave() {
if (!m_textChanged)
return true;
/*int result = JOptionPane.showConfirmDia log(this,
"Save changes to "+getDocumentName()+"?",
APP_NAME, JOptionPane.YES_NO_CANCEL_ OPTION,
JOptionPane.INFORMATION_ME SSAGE);
switch (result) {
case JOptionPane.YES_OPTION:
if (!saveFile(false))
return false;
return true;
case JOptionPane.NO_OPTION:
return true;
case JOptionPane.CANCEL_OPTION:
return false;
} */
return true;
}
protected String getDocumentName() {
return m_currentFile==null ? "Untitled" :
m_currentFile.getName();
}
public void showError(Exception ex, String message) {
ex.printStackTrace();
JOptionPane.showMessageDia log(this,
message, APP_NAME,
JOptionPane.WARNING_MESSAG E);
}
public static void main(String[] args) {
// UI1 frame1 = new UI1();
// frame1.show();
JFrame.setDefaultLookAndFe elDecorate d(true);
JDialog.setDefaultLookAndF eelDecorat ed(true);
UI1 frame1 = new UI1();
frame1.setDefaultCloseOper ation(JFra me.DO_NOTH ING_ON_CLO SE);
frame1.setVisible(true);
}
private void jbInit() throws Exception {
setSize(new Dimension(800, 600));
setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperat ion(DO_NOT HING_ON_CL OSE);
show();
}
}
========================== ========== ========== ===
I have implement it in my program... but why the image can't be inserted?
When I try to insert Image, it will pop out a dialog box .. after I chosed the selected image file.. and click Open.. it seems like nothing happen.. coz the image still haven't being inserted.. why?
Anything wrong with my code? Thanks.
Below is my code:
==========================
package Editor1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.html.*;
public class UI1 extends JFrame {
public static final String APP_NAME = "JSP Editor";
protected JTextPane m_editor;
protected StyleSheet m_context;
protected HTMLDocument m_doc;
protected HTMLEditorKit m_kit;
// protected SimpleFilter m_htmlFilter;
protected JToolBar m_toolBar;
protected JFileChooser m_chooser;
protected File m_currentFile;
protected boolean m_textChanged = false;
public UI1() {
super(APP_NAME);
m_editor = new JTextPane();
m_kit = new HTMLEditorKit();
m_editor.setEditorKit(m_ki
JScrollPane ps = new JScrollPane(m_editor);
getContentPane().add(ps, BorderLayout.CENTER);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( 'F' );
//JMenuItem newItem = new JMenuItem("New");
// newItem.setMnemonic('n');
//fileMenu.add(newItem);
ImageIcon iconNew = new ImageIcon("New16.gif");
Action actionNew = new AbstractAction("New", iconNew) {
public void actionPerformed(ActionEven
if (!promptToSave())
return;
newDocument();
}
};
JMenuItem newItem = new JMenuItem(actionNew);
newItem.setMnemonic('n');
newItem.setAccelerator(Key
KeyEvent.VK_N, InputEvent.CTRL_MASK));
fileMenu.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
fileMenu.add(openItem);
JMenuItem closeItem = new JMenuItem("Close");
closeItem.setMnemonic('L')
fileMenu.add(closeItem);
fileMenu.addSeparator();
JMenuItem saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
fileMenu.add(saveItem);
JMenuItem saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic('A'
fileMenu.add(saveAsItem);
fileMenu.addSeparator();
JMenuItem printCodeItem = new JMenuItem("Print Code");
printCodeItem.setMnemonic(
fileMenu.add(printCodeItem
JMenuItem previewItem = new JMenuItem("Preview");
previewItem.setMnemonic('R
fileMenu.add(previewItem);
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('T');
fileMenu.add(exitItem);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(fileMenu);
JMenu editMenu = new JMenu( "Edit" );
editMenu.setMnemonic( 'E' );
JMenuItem cutItem = new JMenuItem("Cut");
cutItem.setMnemonic('X');
editMenu.add(cutItem);
JMenuItem copyItem = new JMenuItem("Copy");
copyItem.setMnemonic('C');
editMenu.add(copyItem);
JMenuItem pasteItem = new JMenuItem("Paste");
pasteItem.setMnemonic('V')
editMenu.add(pasteItem);
bar.add(editMenu);
JMenu viewMenu = new JMenu( "View" );
viewMenu.setMnemonic( 'I' );
JMenuItem codeItem = new JMenuItem("Code");
viewMenu.add(codeItem);
JMenuItem designItem = new JMenuItem("Design");
viewMenu.add(designItem);
bar.add(viewMenu);
JMenu insertMenu = new JMenu( "Insert" );
JMenuItem imageItem = new JMenuItem("Image");
insertMenu.add(imageItem);
imageItem.addActionListene
public void actionPerformed (ActionEvent e) {
doInsertImageCommand();
}
});
bar.add(insertMenu);
}
public void doInsertImageCommand() {
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(thi
if (status == JFileChooser.APPROVE_OPTIO
File file = chooser.getSelectedFile();
Icon icon = new ImageIcon (file.getAbsolutePath());
m_editor.insertIcon (icon);
}
}
protected void newDocument() {
m_doc = (HTMLDocument)m_kit.create
m_context = m_doc.getStyleSheet();
m_editor.setDocument(m_doc
m_currentFile = null;
setTitle(APP_NAME+" ["+getDocumentName()+"]");
SwingUtilities.invokeLater
public void run() {
m_editor.scrollRectToVisib
m_doc.addDocumentListener(
m_textChanged = false;
}
});
}
protected void openDocument() {
if (m_chooser.showOpenDialog(
JFileChooser.APPROVE_OPTIO
return;
File f = m_chooser.getSelectedFile(
if (f == null || !f.isFile())
return;
m_currentFile = f;
setTitle(APP_NAME+" ["+getDocumentName()+"]");
UI1.this.setCursor(
Cursor.getPredefinedCursor
// Can't do this in thread - Pavel
try {
InputStream in = new FileInputStream(m_currentF
m_doc = (HTMLDocument)m_kit.create
m_kit.read(in, m_doc, 0);
m_context = m_doc.getStyleSheet();
m_editor.setDocument(m_doc
in.close();
}
catch (Exception ex) {
showError(ex, "Error reading file "+m_currentFile);
}
UI1.this.setCursor(Cursor.
Cursor.DEFAULT_CURSOR));
SwingUtilities.invokeLater
public void run() {
m_editor.setCaretPosition(
m_editor.scrollRectToVisib
m_doc.addDocumentListener(
m_textChanged = false;
}
});
}
class UpdateListener implements DocumentListener {
public void insertUpdate(DocumentEvent
m_textChanged = true;
}
public void removeUpdate(DocumentEvent
m_textChanged = true;
}
public void changedUpdate(DocumentEven
m_textChanged = true;
}
}
protected boolean promptToSave() {
if (!m_textChanged)
return true;
/*int result = JOptionPane.showConfirmDia
"Save changes to "+getDocumentName()+"?",
APP_NAME, JOptionPane.YES_NO_CANCEL_
JOptionPane.INFORMATION_ME
switch (result) {
case JOptionPane.YES_OPTION:
if (!saveFile(false))
return false;
return true;
case JOptionPane.NO_OPTION:
return true;
case JOptionPane.CANCEL_OPTION:
return false;
} */
return true;
}
protected String getDocumentName() {
return m_currentFile==null ? "Untitled" :
m_currentFile.getName();
}
public void showError(Exception ex, String message) {
ex.printStackTrace();
JOptionPane.showMessageDia
message, APP_NAME,
JOptionPane.WARNING_MESSAG
}
public static void main(String[] args) {
// UI1 frame1 = new UI1();
// frame1.show();
JFrame.setDefaultLookAndFe
JDialog.setDefaultLookAndF
UI1 frame1 = new UI1();
frame1.setDefaultCloseOper
frame1.setVisible(true);
}
private void jbInit() throws Exception {
setSize(new Dimension(800, 600));
setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperat
show();
}
}
==========================
Try to implement this 1st w/o package ok :)
Also try different kind of image format like .jpg .gif & other format.
Checked on what version of jdk do you use.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.util.*;
public class Formatter extends JFrame {
final static int WIDTH = 400;
final static int HEIGHT = 300;
StyledDocument doc;
JTextPane pane;
JLabel statusInfo;
public Formatter(String lab) {
super (lab);
// Get ContentPane
Container c = getContentPane();
// Setup Status Message Area
statusInfo = new JLabel();
c.add (statusInfo, BorderLayout.SOUTH);
// Setup Text Pane
doc = new DefaultStyledDocument();
pane = new JTextPane (doc);
// Place in JScrollPane
JScrollPane sp = new JScrollPane (pane);
c.add(sp, BorderLayout.CENTER);
// Setup Menus
JMenuBar menuBar = new JMenuBar();
setJMenuBar (menuBar);
// Setup File Menu
JMenu file = new JMenu ("File");
JMenuItem item;
file.add (item = new JMenuItem ("New"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doNewCommand();
}
});
file.add (item = new JMenuItem ("Open"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doOpenCommand();
}
});
file.add (item = new JMenuItem ("Load Text"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doLoadCommand();
}
});
file.add (item = new JMenuItem ("Save"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doSaveCommand();
}
});
file.addSeparator();
file.add (item = new JMenuItem ("Close"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doCloseCommand();
}
});
menuBar.add (file);
// Setup Color Menu
JMenu color = new JMenu("Color");
color.add (item = new JMenuItem ("Red"));
item.setIcon (new ColoredBox(Color.red));
item.addActionListener (new
StyledEditorKit.Foreground Action (
"set-foreground-red", Color.red));
color.add (item = new JMenuItem ("Orange"));
item.setIcon (new ColoredBox(Color.orange));
item.addActionListener (new
StyledEditorKit.Foreground Action (
"set-foreground-orange", Color.orange));
color.add (item = new JMenuItem ("Yellow"));
item.setIcon (new ColoredBox(Color.yellow));
item.addActionListener (new
StyledEditorKit.Foreground Action (
"set-foreground-yellow", Color.yellow));
color.add (item = new JMenuItem ("Green"));
item.setIcon (new ColoredBox(Color.green));
item.addActionListener (new
StyledEditorKit.Foreground Action (
"set-foreground-green", Color.green));
color.add (item = new JMenuItem ("Blue"));
item.setIcon (new ColoredBox(Color.blue));
item.addActionListener (new
StyledEditorKit.Foreground Action (
"set-foreground-blue", Color.blue));
color.add (item = new JMenuItem ("Magenta"));
item.setIcon (new ColoredBox(Color.magenta)) ;
item.addActionListener (new
StyledEditorKit.Foreground Action (
"set-foreground-magenta", Color.magenta));
color.add (item = new JMenuItem ("Custom Color"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doColorCommand();
}
});
menuBar.add (color);
// Setup Font Menu
JMenu font = new JMenu("Font");
font.add (item = new JMenuItem ("12"));
item.addActionListener (new
StyledEditorKit.FontSizeAc tion (
"font-size-12", 12));
font.add (item = new JMenuItem ("24"));
item.addActionListener (new
StyledEditorKit.FontSizeAc tion (
"font-size-24", 24));
font.add (item = new JMenuItem ("36"));
item.addActionListener (new
StyledEditorKit.FontSizeAc tion (
"font-size-36", 36));
font.addSeparator();
font.add (item = new JMenuItem ("Serif"));
item.setFont (new Font ("Serif", Font.PLAIN, 12));
item.addActionListener (new
StyledEditorKit.FontFamily Action (
"font-family-Serif", "Serif"));
font.add (item = new JMenuItem ("SansSerif"));
item.setFont (new Font ("SansSerif", Font.PLAIN, 12));
item.addActionListener (new
StyledEditorKit.FontFamily Action (
"font-family-SansSerif", "SansSerif"));
font.add (item = new JMenuItem ("Monospaced"));
item.setFont (new Font ("Monospaced", Font.PLAIN, 12));
item.addActionListener (new
StyledEditorKit.FontFamily Action (
"font-family-Monospaced", "Monospaced"));
font.addSeparator();
font.add (item = new JMenuItem ("Bold"));
item.setFont (new Font ("Serif", Font.BOLD, 12));
item.addActionListener (
new StyledEditorKit.BoldAction ());
font.add (item = new JMenuItem ("Italic"));
item.setFont (new Font ("Serif", Font.ITALIC, 12));
item.addActionListener (
new StyledEditorKit.ItalicActi on ());
/* Add once FontChooser is available
font.addSeparator();
font.add (item = new JMenuItem ("Custom Font"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doFontCommand();
}
});
*/
menuBar.add (font);
// Setup Insert Menu
JMenu insert = new JMenu("Insert");
insert.add (item = new JMenuItem ("Image File"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doInsertImageCommand();
}
});
menuBar.add (insert);
}
public static void main (String args[]) {
Formatter frame = new Formatter("Mini Text Editor");
frame.addWindowListener(ne w WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
public void doNewCommand() {
pane.setStyledDocument (doc = new DefaultStyledDocument());
}
public void doCloseCommand() {
System.exit (0);
}
public void doOpenCommand() {
try {
FileInputStream fis = new FileInputStream ("doc.ser");
ObjectInputStream ois = new ObjectInputStream (fis);
doc = (StyledDocument)ois.readOb ject();
ois.close();
pane.setStyledDocument (doc);
validate();
statusInfo.setText ("Reloaded from disk");
} catch (Exception e) {
statusInfo.setText ("Unable to reload");
e.printStackTrace();
}
}
public void doSaveCommand() {
try {
FileOutputStream fos = new FileOutputStream ("doc.ser");
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (doc);
oos.flush();
oos.close();
statusInfo.setText ("Saved to disk");
} catch (IOException e) {
statusInfo.setText ("Unable to save");
e.printStackTrace();
}
}
public void doLoadCommand() {
String msg;
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(thi s);
if (status == JFileChooser.APPROVE_OPTIO N) {
char data[];
final Runnable doWaitCursor = new Runnable() {
public void run() {
setCursor (Cursor.getPredefinedCurso r(Cursor.W AIT_CURSOR ));
}
};
Thread appThread = new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWa it(doWaitC ursor);
} catch (Exception e) {
e.printStackTrace();
}
}
};
appThread.start();
File f = chooser.getSelectedFile();
try {
// Clear out current document
pane.setStyledDocument (doc = new DefaultStyledDocument());
// Read in text file
FileReader fin = new FileReader (f);
BufferedReader br = new BufferedReader (fin);
char buffer[] = new char[4096];
int len;
while ((len = br.read (buffer, 0, buffer.length)) != -1) {
// Insert into pane
doc.insertString(doc.getLe ngth(),
new String (buffer, 0, len), null);
}
statusInfo.setText ("Loaded: " + f.getName());
} catch (BadLocationException exc) {
statusInfo.setText ("Error loading: " + f.getName());
} catch (FileNotFoundException exc) {
statusInfo.setText ("File Not Found: " + f.getName());
} catch (IOException exc) {
statusInfo.setText ("IOException: " + f.getName());
}
final Runnable undoWaitCursor = new Runnable() {
public void run() {
setCursor (Cursor.getPredefinedCurso r(Cursor.D EFAULT_CUR SOR));
}
};
appThread = new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWa it(undoWai tCursor);
} catch (Exception e) {
e.printStackTrace();
}
}
};
appThread.start();
}
}
/*
public void doFontCommand() {
Font font = FontChooser.ask (
this, "Change font", getFont(), null);
if (font != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontFami ly (attr, font.getFamily());
StyleConstants.setFontSize (attr, font.getSize());
StyleConstants.setBold (attr, font.isBold());
StyleConstants.setItalic (attr, font.isItalic());
pane.setCharacterAttribute s(attr, false);
}
}
*/
public void doColorCommand() {
Color color = JColorChooser.showDialog(
this, "Color Chooser", Color.cyan);
if (color != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForegrou nd(attr, color);
pane.setCharacterAttribute s(attr, false);
}
}
public void doInsertImageCommand() {
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(thi s);
if (status == JFileChooser.APPROVE_OPTIO N) {
File file = chooser.getSelectedFile();
Icon icon = new ImageIcon (file.getAbsolutePath());
pane.insertIcon (icon);
}
}
class ColoredBox implements Icon {
Color color;
public ColoredBox (Color c) {
color = c;
}
public void paintIcon (Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect (x, y, getIconWidth(), getIconHeight());
}
public int getIconWidth() {
return 10;
}
public int getIconHeight() {
return 10;
}
}
}
Also try different kind of image format like .jpg .gif & other format.
Checked on what version of jdk do you use.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.util.*;
public class Formatter extends JFrame {
final static int WIDTH = 400;
final static int HEIGHT = 300;
StyledDocument doc;
JTextPane pane;
JLabel statusInfo;
public Formatter(String lab) {
super (lab);
// Get ContentPane
Container c = getContentPane();
// Setup Status Message Area
statusInfo = new JLabel();
c.add (statusInfo, BorderLayout.SOUTH);
// Setup Text Pane
doc = new DefaultStyledDocument();
pane = new JTextPane (doc);
// Place in JScrollPane
JScrollPane sp = new JScrollPane (pane);
c.add(sp, BorderLayout.CENTER);
// Setup Menus
JMenuBar menuBar = new JMenuBar();
setJMenuBar (menuBar);
// Setup File Menu
JMenu file = new JMenu ("File");
JMenuItem item;
file.add (item = new JMenuItem ("New"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doNewCommand();
}
});
file.add (item = new JMenuItem ("Open"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doOpenCommand();
}
});
file.add (item = new JMenuItem ("Load Text"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doLoadCommand();
}
});
file.add (item = new JMenuItem ("Save"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doSaveCommand();
}
});
file.addSeparator();
file.add (item = new JMenuItem ("Close"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doCloseCommand();
}
});
menuBar.add (file);
// Setup Color Menu
JMenu color = new JMenu("Color");
color.add (item = new JMenuItem ("Red"));
item.setIcon (new ColoredBox(Color.red));
item.addActionListener (new
StyledEditorKit.Foreground
"set-foreground-red", Color.red));
color.add (item = new JMenuItem ("Orange"));
item.setIcon (new ColoredBox(Color.orange));
item.addActionListener (new
StyledEditorKit.Foreground
"set-foreground-orange", Color.orange));
color.add (item = new JMenuItem ("Yellow"));
item.setIcon (new ColoredBox(Color.yellow));
item.addActionListener (new
StyledEditorKit.Foreground
"set-foreground-yellow", Color.yellow));
color.add (item = new JMenuItem ("Green"));
item.setIcon (new ColoredBox(Color.green));
item.addActionListener (new
StyledEditorKit.Foreground
"set-foreground-green", Color.green));
color.add (item = new JMenuItem ("Blue"));
item.setIcon (new ColoredBox(Color.blue));
item.addActionListener (new
StyledEditorKit.Foreground
"set-foreground-blue", Color.blue));
color.add (item = new JMenuItem ("Magenta"));
item.setIcon (new ColoredBox(Color.magenta))
item.addActionListener (new
StyledEditorKit.Foreground
"set-foreground-magenta", Color.magenta));
color.add (item = new JMenuItem ("Custom Color"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doColorCommand();
}
});
menuBar.add (color);
// Setup Font Menu
JMenu font = new JMenu("Font");
font.add (item = new JMenuItem ("12"));
item.addActionListener (new
StyledEditorKit.FontSizeAc
"font-size-12", 12));
font.add (item = new JMenuItem ("24"));
item.addActionListener (new
StyledEditorKit.FontSizeAc
"font-size-24", 24));
font.add (item = new JMenuItem ("36"));
item.addActionListener (new
StyledEditorKit.FontSizeAc
"font-size-36", 36));
font.addSeparator();
font.add (item = new JMenuItem ("Serif"));
item.setFont (new Font ("Serif", Font.PLAIN, 12));
item.addActionListener (new
StyledEditorKit.FontFamily
"font-family-Serif", "Serif"));
font.add (item = new JMenuItem ("SansSerif"));
item.setFont (new Font ("SansSerif", Font.PLAIN, 12));
item.addActionListener (new
StyledEditorKit.FontFamily
"font-family-SansSerif", "SansSerif"));
font.add (item = new JMenuItem ("Monospaced"));
item.setFont (new Font ("Monospaced", Font.PLAIN, 12));
item.addActionListener (new
StyledEditorKit.FontFamily
"font-family-Monospaced", "Monospaced"));
font.addSeparator();
font.add (item = new JMenuItem ("Bold"));
item.setFont (new Font ("Serif", Font.BOLD, 12));
item.addActionListener (
new StyledEditorKit.BoldAction
font.add (item = new JMenuItem ("Italic"));
item.setFont (new Font ("Serif", Font.ITALIC, 12));
item.addActionListener (
new StyledEditorKit.ItalicActi
/* Add once FontChooser is available
font.addSeparator();
font.add (item = new JMenuItem ("Custom Font"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doFontCommand();
}
});
*/
menuBar.add (font);
// Setup Insert Menu
JMenu insert = new JMenu("Insert");
insert.add (item = new JMenuItem ("Image File"));
item.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
doInsertImageCommand();
}
});
menuBar.add (insert);
}
public static void main (String args[]) {
Formatter frame = new Formatter("Mini Text Editor");
frame.addWindowListener(ne
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
public void doNewCommand() {
pane.setStyledDocument (doc = new DefaultStyledDocument());
}
public void doCloseCommand() {
System.exit (0);
}
public void doOpenCommand() {
try {
FileInputStream fis = new FileInputStream ("doc.ser");
ObjectInputStream ois = new ObjectInputStream (fis);
doc = (StyledDocument)ois.readOb
ois.close();
pane.setStyledDocument (doc);
validate();
statusInfo.setText ("Reloaded from disk");
} catch (Exception e) {
statusInfo.setText ("Unable to reload");
e.printStackTrace();
}
}
public void doSaveCommand() {
try {
FileOutputStream fos = new FileOutputStream ("doc.ser");
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (doc);
oos.flush();
oos.close();
statusInfo.setText ("Saved to disk");
} catch (IOException e) {
statusInfo.setText ("Unable to save");
e.printStackTrace();
}
}
public void doLoadCommand() {
String msg;
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(thi
if (status == JFileChooser.APPROVE_OPTIO
char data[];
final Runnable doWaitCursor = new Runnable() {
public void run() {
setCursor (Cursor.getPredefinedCurso
}
};
Thread appThread = new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWa
} catch (Exception e) {
e.printStackTrace();
}
}
};
appThread.start();
File f = chooser.getSelectedFile();
try {
// Clear out current document
pane.setStyledDocument (doc = new DefaultStyledDocument());
// Read in text file
FileReader fin = new FileReader (f);
BufferedReader br = new BufferedReader (fin);
char buffer[] = new char[4096];
int len;
while ((len = br.read (buffer, 0, buffer.length)) != -1) {
// Insert into pane
doc.insertString(doc.getLe
new String (buffer, 0, len), null);
}
statusInfo.setText ("Loaded: " + f.getName());
} catch (BadLocationException exc) {
statusInfo.setText ("Error loading: " + f.getName());
} catch (FileNotFoundException exc) {
statusInfo.setText ("File Not Found: " + f.getName());
} catch (IOException exc) {
statusInfo.setText ("IOException: " + f.getName());
}
final Runnable undoWaitCursor = new Runnable() {
public void run() {
setCursor (Cursor.getPredefinedCurso
}
};
appThread = new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWa
} catch (Exception e) {
e.printStackTrace();
}
}
};
appThread.start();
}
}
/*
public void doFontCommand() {
Font font = FontChooser.ask (
this, "Change font", getFont(), null);
if (font != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontFami
StyleConstants.setFontSize
StyleConstants.setBold (attr, font.isBold());
StyleConstants.setItalic (attr, font.isItalic());
pane.setCharacterAttribute
}
}
*/
public void doColorCommand() {
Color color = JColorChooser.showDialog(
this, "Color Chooser", Color.cyan);
if (color != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForegrou
pane.setCharacterAttribute
}
}
public void doInsertImageCommand() {
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(thi
if (status == JFileChooser.APPROVE_OPTIO
File file = chooser.getSelectedFile();
Icon icon = new ImageIcon (file.getAbsolutePath());
pane.insertIcon (icon);
}
}
class ColoredBox implements Icon {
Color color;
public ColoredBox (Color c) {
color = c;
}
public void paintIcon (Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect (x, y, getIconWidth(), getIconHeight());
}
public int getIconWidth() {
return 10;
}
public int getIconHeight() {
return 10;
}
}
}
" Sometimes debuging codes can be hard but the one who always give dedication wins. "
Javatm
Javatm
ASKER
I have try the one withot package, is ok.. I mean it's can insert image..
But then after I try to implement in my package.. and inserting the same image .. it can't.. why?
thanks..
But then after I try to implement in my package.. and inserting the same image .. it can't.. why?
thanks..
>> how to do this?
I just gave you a sample :)
fixing the codes is a seperate question
hope you understand
I just gave you a sample :)
fixing the codes is a seperate question
hope you understand
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks everyone!!
Actually the credits should go to evryone since you all really have gave me a big help on it..
but since this question should based on "How to insert image.." so, Javatm get most of the point.. but Can gnoon drop a message in my next question , that is "What's wrong with my Java code..", so that I could give u the other points.. Thank you!!
Actually the credits should go to evryone since you all really have gave me a big help on it..
but since this question should based on "How to insert image.." so, Javatm get most of the point.. but Can gnoon drop a message in my next question , that is "What's wrong with my Java code..", so that I could give u the other points.. Thank you!!
ASKER
gnoon, pls go here and drop a comment there and get extra points for your help.. Thanks a lot..
https://www.experts-exchange.com/questions/20804725/What's-wrong-with-my-Java-code-TQ.html
https://www.experts-exchange.com/questions/20804725/What's-wrong-with-my-Java-code-TQ.html
.....
ImageIcon image = new ImageIcon("someimage.gif")
JLabel label = new JLabel();
label.setIcon(image);
.....
:)