Icons in jtextarea

is there any way to insert images or icons into a jtextarea?
just like inserting and displaying icons when using instant messaging programs?
thanks a lot..!

hyper222 wrote:
is there any way to insert images or icons into a jtextarea?Is there something wrong with your shift key? If not, please apply it once at the start of each sentence, and to use the correct capitalisation for JTextArea. Unless, of course, you are referring to some 3rd party jtextarea that we do not know, and cannot help you with.
just like inserting and displaying icons when using instant messaging programs?If you are referring to JTextArea, then no. You would need a JEditorPane for that.

Similar Messages

  • Help in adding smilley icon in swings

    Hi I'm making a simple chat server. Can any plz help me that how can I add smilley icon to JTextArea as I'm using JTextArea as message display in chat client.

    Hi I'm making a simple chat server. Can any plz help
    me that how can I add smilley icon to JTextArea as I'm
    using JTextArea as message display in chat client. you have a unicode character 263a for the smiley, but
    i am not sure that you can display an icon or render this
    unicode character as smiley in JTextArea. May you have
    to try using JTextPane.

  • Swing bug? cannot set width of JToggleButton

    Hello,
    Just wondered if this was a Swing bug. See also
    bug 6349010.
    The width of the JToggleButton cannot be set.
    However the height can be set.
    The important line is line 135 - and also 140.
    Try changing the width of the button - it does not change.
    thanks,
    Anil
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.util.EventObject;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    import javax.swing.JToggleButton;
    import javax.swing.JTree;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeSelectionModel;
    public class TreeUIFailed extends JPanel {
           AnilTreeCellRenderer3 atcr;
           AnilTreeCellEditor4 atce;
           DefaultTreeModel treeModel;
           JTree tree;
           DefaultMutableTreeNode markedNode = null;
         public TreeUIFailed() {
                super(new BorderLayout());
                   treeModel = new DefaultTreeModel(null);
                   tree = new JTree(treeModel);          
                  tree.setEditable(true);
                   tree.getSelectionModel().setSelectionMode(
                             TreeSelectionModel.SINGLE_TREE_SELECTION);
                   tree.setShowsRootHandles(true);
                  tree.setCellRenderer(atcr = new AnilTreeCellRenderer3());
                  tree.setCellEditor(atce = new AnilTreeCellEditor4(tree, atcr));
                  tree.setRowHeight(0);//TEMP - needed only if setting Win L&F
                   JScrollPane scrollPane = new JScrollPane(tree);
                   add(scrollPane,BorderLayout.CENTER);
         public void setRootNode(DefaultMutableTreeNode node) {
              treeModel.setRoot(node);
              treeModel.reload();
           public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
    //            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                TreeUIFailed tb = new TreeUIFailed();
                tb.setPreferredSize(new Dimension(800,600));
                  JFrame frame = new JFrame("Tree Windows UI Failed");
                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  frame.setContentPane(tb);
                  frame.setSize(800, 600);
                  frame.pack();
                  frame.setVisible(true);
                  tb.populate();
         private void populate() {
              TextAreaNode3 r = new TextAreaNode3(this);
               setRootNode(r);
                   r.gNode.notes.addTab("0", null/* icon */, new JTextArea(2,25),
                   "no menu!");
                   r.gNode.notes.addTab("1", null/* icon */, new JTextArea(2,25),
                   "no menu!");
                   TextAreaNode3 a = new TextAreaNode3(this);
                   a.gNode.notes.addTab("1", null/* icon */, new JTextArea(2,25),
                   "no menu!");
               treeModel.insertNodeInto(a, r, r.getChildCount());          
    class AnilTreeCellRenderer3 extends DefaultTreeCellRenderer{
         TreeUIFailed panel;
    DefaultMutableTreeNode currentNode;
      public AnilTreeCellRenderer3() {
         super();
    public Component getTreeCellRendererComponent
       (JTree tree, Object value, boolean selected, boolean expanded,
       boolean leaf, int row, boolean hasFocus){
         TextAreaNode3 currentNode = (TextAreaNode3)value;
         NodeGUI4 gNode = (NodeGUI4) currentNode.gNode;
        return gNode.vBox;
    class AnilTreeCellEditor4 extends DefaultTreeCellEditor{
      DefaultTreeCellRenderer rend;
      public AnilTreeCellEditor4(JTree tree, DefaultTreeCellRenderer r){
        super(tree, r);
        rend = r;
      public Component getTreeCellEditorComponent(JTree tree, Object value,
       boolean isSelected, boolean expanded, boolean leaf, int row){
        return rend.getTreeCellRendererComponent(tree, value, isSelected, expanded,
         leaf, row, true);
      public boolean isCellEditable(EventObject event){
        return true;
    * this is done to keep gui separate from model - as in MVC.
    * not necessary.
    * @author juwo
    class NodeGUI4 {
         JPanel notesPanel = new JPanel(new BorderLayout(), true);
         JTabbedPane notes = new JTabbedPane(JTabbedPane.RIGHT);
         final TreeUIFailed view;
         Box vBox = Box.createVerticalBox();
         Box hBox = Box.createHorizontalBox();
         final JTextArea textArea = new JTextArea( 1, 5 );
         JToggleButton toggleButton = new JToggleButton();
         NodeGUI4( TreeUIFailed view_ ) {
              this.view = view_;
              toggleButton.setAlignmentX(Component.CENTER_ALIGNMENT);
    // BEGIN PROBLEM          
              toggleButton.setPreferredSize(new Dimension(200,toggleButton.getPreferredSize().height));
    // END PROBLEM
              vBox.add(toggleButton);
              vBox.add(hBox);
              hBox.add( textArea );
              textArea.setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, Color.GREEN ) );
              notesPanel.add(notes);
              hBox.add( notesPanel);
              hBox.setBorder( BorderFactory.createMatteBorder( 5, 5, 5, 5, Color.CYAN ) );
    // THE FOLLOWING DOES NOT WORK EITHER!!!          
              //          halo.setPreferredSize(new Dimension(vBox.getPreferredSize().width,halo.getPreferredSize().height));
    class TextAreaNode3 extends DefaultMutableTreeNode {  
         NodeGUI4 gNode;
         TextAreaNode3(TreeUIFailed view_t) {     
              gNode = new NodeGUI4(view_t);          
    }

    ok, sorry!
    I understood why it does not work.
    Box Layout respects the maximum size of the component.
    By default, a JToggleButton is set to 34.
    Changing the JToggleButton max width to 75, allows the preferred size to be set.
    Thank you camickr!
    Note: in contrast, Flow Layout respects the preferred size and ignores the max size!
    Message was edited by:
    anilp1

  • How to make FileChooser only  have a Folder to choose?PLs help

    Dear Java expert!!Anyone know how to make user to choose it content from a single folder only...Pls advice
    this is my program..
    `````````````````````````
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    public class Test2 extends JFrame {
         JFileChooser chooser = new JFileChooser();
         TextPreviewer previewer = new TextPreviewer();
         JPanel previewPanel = new PreviewPanel();
         class PreviewPanel extends JPanel {
              public PreviewPanel() {
                   JLabel label = new JLabel("Text Previewer",
                                                 SwingConstants.CENTER);
                   setPreferredSize(new Dimension(250,0));
                   setBorder(BorderFactory.createEtchedBorder());
                   setLayout(new BorderLayout());
                   label.setBorder(BorderFactory.createEtchedBorder());
                   add(label, BorderLayout.NORTH);
                   add(previewer, BorderLayout.CENTER);
         public Test2() {
              super("Accessory Components");
              Container contentPane = getContentPane();
              JButton     button = new JButton("Select A File");
              contentPane.setLayout(new FlowLayout());
              contentPane.add(button);          
              chooser.setAccessory(previewPanel);
              chooser.addPropertyChangeListener(
                                                 new PropertyChangeListener() {
                   public void propertyChange(PropertyChangeEvent e) {
                        if(e.getPropertyName().equals(
                             JFileChooser.SELECTED_FILE_CHANGED_PROPERTY))
                             previewer.update((File)e.getNewValue());
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        chooser.showOpenDialog(null);
         public static void main(String a[]) {
              JFrame f = new Test2();
              f.setBounds(300, 300, 300, 75);
              f.setVisible(true);
              f.setDefaultCloseOperation(
                                            WindowConstants.DISPOSE_ON_CLOSE);
              f.addWindowListener(new WindowAdapter() {
                   public void windowClosed(WindowEvent e) {
                        System.exit(0);
    class TextPreviewer extends JComponent {
         private ImageIcon icon;
         private JTextArea textArea = new JTextArea();
         public TextPreviewer() {
              setBorder(BorderFactory.createEtchedBorder());
              setLayout(new BorderLayout());
              add(new JScrollPane(textArea), BorderLayout.CENTER);
         public void update(File file) {
              textArea.setText(contentsOfFile(file));
              if(isShowing()) {
                   textArea.revalidate();
         static String contentsOfFile(File file) {
              String s = new String();
              char[] buff = new char[50000];
              InputStream is;
              InputStreamReader reader;
              URL url;
              try {
                   reader = new FileReader(file);
                   int nch;
                   while ((
                        nch = reader.read(buff, 0, buff.length)) != -1) {
                        s = s + new String(buff, 0, nch);
              catch (java.io.IOException ex) {
                   s = "Could not load file";
              return s;

    If you need to use a JFileChooser to select a folder, not a file, use:
    JFileChooser jf = new JFileChooser();
    jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    Now, your file chooser is a directory chooser....

  • Question on tidying up code

    I have my main class, which holds 5 JPanels on a container. There is an awful lot of code involved in setting all my components, especially since i use gridbagconstraints quite a bit. I will post the code, its quite a lot but its more for you to just glance over. What i wanted to do is neaten up my code, but i am not sure how. One thought was putting code related too each JPanel in its own method but i am ready to lesten to any suggestions, its problably really messy at the moment but who knows, the way i have it might be the standard way of doing it.....But as i say, any suggestions in making it better..
    import java.awt.*; //the importing of required libraries
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.event.KeyListener;
    import java.awt.event.*;
    import javax.swing.JTextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.border.*;
    public class MainPage extends JFrame implements ActionListener  //extends JFrame so that we inherit JFrame's attributes and methods
    {                                                                                //implements ActionLister on the class
    MainPageMethods mpm = new MainPageMethods(); //creating a reference to class MainPageMethods (Linking it with this class)
    private JPanel topPanel, leftPanel, centerPanel, rightPanel, bottomPanel; //declaring variables
    private JLabel logUser, logPassword, regUser, regPassword, regName, mainTitle, loginTitle, regTitle, centerPanel1;
    private JTextField logUser2, regUser2, regPassword2, regName2, logPassword2;
    private JPasswordField logPassword12;
    private JButton exitBt, logSubmitBt, regSubmitBt, regResetBt, logResetBt;
    private Icon image = new ImageIcon("london_2012.png");  //assigning an image to an Icon
    private JTextArea regTxt;
    private String logUser3, regUser3, regPassword3, regName3, logPassword3, regTxt2;
    private Container cPane;  //container which sits in the JFrame
    ImageIcon icon;
    public MainPage() //constructor of the class
    super(); //Superclassing the JFrame
    createGUI(); //Calling up method cretaeGUI when this constructor is called
    logUser3 = "";  //initialising the Strings so that they are empty
    regUser3 = "";
    regPassword3 ="";
    regName3 ="";
    logPassword3 = "";
    private void createGUI(){  //createGUI method
    cPane = getContentPane();  //assigning our container a ContentPane
    arrangeCompenents(); //calling up arrangeComponents method
    setTitle("Nrr");  //Setting title on JFrame
    setLocation(new Point(0, 0));  //location
    setVisible(true);                //making it visible
    setSize(800, 608);          //setting the size
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);  //making it disappear if closed
    private void arrangeCompenents(){  //arrangeComponents method
    topPanel = new JPanel();  //initlising our variables
    leftPanel = new JPanel();
    centerPanel = new JPanel();
    icon = new ImageIcon("london.jpg");
    rightPanel = new JPanel(){
    public void paintComponent(Graphics g)
    Dimension d = getSize();
    g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
    setOpaque( false );
    super.paintComponent(g);
    bottomPanel = new JPanel();
    logUser = new JLabel("Username");
    logPassword = new JLabel("Password");
    regUser = new JLabel("Username");
    regPassword = new JLabel("Password");
    regName = new JLabel("Full Name");
    mainTitle = new JLabel("LONDON 2012");
    loginTitle = new JLabel("<html><b><i>LOGIN</i></b></html>");  //using html within a JLabel
    regTitle = new JLabel("<html><b><i>REGISTER</i></b></html>");
    regTxt2 = ("This applicationis designed" + "\n" + "to be used by people autorised by ");  //text for JTextArea
    regTxt = new JTextArea(regTxt2, 10, 20);  //initialising a JTextArea
    regTxt.setEditable(false);           //making sure it cannot be edited
    regTxt.setBorder(BorderFactory.createLoweredBevelBorder());  //giving it a border
    logUser2 = new JTextField(10);
    logPassword2 = new JTextField(10);
    regUser2 = new JTextField(10);
    regPassword2 = new JTextField(10);
    regName2 = new JTextField(10);
    logPassword12 = new JPasswordField(10);
    exitBt = new JButton("EXIT");
    logSubmitBt = new JButton("SUBMIT");
    regSubmitBt = new JButton("SUBMIT");
    regResetBt = new JButton("RESET");
    logResetBt = new JButton("RESET");
    mainTitle.setFont(mainTitle.getFont().deriveFont(Font.BOLD, 48));
    mainTitle.setForeground(Color.white);
    centerPanel1 = new JLabel(image);
    regTitle.setFont(new Font("Serif", Font.BOLD, 35));
    regTitle.setForeground(Color.white);
    loginTitle.setFont(new Font("Serif", Font.BOLD, 35));
    loginTitle.setForeground(Color.white);
    regTxt.setBorder(BorderFactory.createLoweredBevelBorder());
    regTxt.setBackground(new Color(0, 153, 254));
    cPane.setLayout(new BorderLayout());  //setting our ContenetPane to have a BorderLayout
    cPane.add(topPanel,BorderLayout.PAGE_START);  //Setting the JPanels in a location using BorderLayout on our ContentPane
    cPane.add(centerPanel,BorderLayout.CENTER);
    cPane.add(bottomPanel, BorderLayout.PAGE_END);
    cPane.add(leftPanel, BorderLayout.LINE_START);
    cPane.add(rightPanel, BorderLayout.LINE_END);
    topPanel.setLayout(new FlowLayout());  //setting topPanel to use FlowLayout
    topPanel.setBackground(new Color(223, 0, 148));  //giving the panel a background colour
    topPanel.setBorder(BorderFactory.createRaisedBevelBorder());  //giving this panel a border
    topPanel.add(mainTitle, 0);  //adding variable mainTitle to panel
    centerPanel.setLayout(new FlowLayout());
    centerPanel.setBackground(new Color(0, 153, 254));
    centerPanel.setBorder(BorderFactory.createRaisedBevelBorder());
    centerPanel.add(centerPanel1, 0);
    bottomPanel.setLayout(new FlowLayout());
    bottomPanel.setBorder(BorderFactory.createRaisedBevelBorder());
    bottomPanel.setBackground(new Color(223, 0, 148));
    bottomPanel.setPreferredSize(new Dimension(608, 65));
    bottomPanel.add(exitBt, 0);
    leftPanel.setLayout(new GridBagLayout()); //setting the leftPanel to use GridbagLayout
    leftPanel.setBackground(new Color(0, 153, 254));  //panel background colour
    leftPanel.setBorder(BorderFactory.createLoweredBevelBorder());  //giving panel a border
    GridBagConstraints gbc01 = new GridBagConstraints();  //creating the constraints of the panel
    gbc01.gridx = 0;  //location on the x axis
    gbc01.gridy = 0;  //location on the y axis
    gbc01.insets = new Insets(35, 0, 15, 5);  //size of the insets (Spacing around the component)
    gbc01.gridwidth = GridBagConstraints.REMAINDER;  //setting the gridwidth
    gbc01.anchor = GridBagConstraints.PAGE_START;  //setting an anchor
    gbc01.fill = GridBagConstraints.NONE;         //creating a fill
    leftPanel.add(regTitle, gbc01);               //adding variable regTitle to the panel with these constraints applied on it
    GridBagConstraints gbc02 = new GridBagConstraints();
    gbc02.gridx = 0;
    gbc02.gridy = 1;
    gbc02.insets = new Insets(5, 5, 5, 5);
    gbc02.gridwidth = GridBagConstraints.REMAINDER;
    gbc02.anchor = GridBagConstraints.LINE_START;
    gbc02.fill = GridBagConstraints.NONE;
    leftPanel.add(regTxt, gbc02);
    GridBagConstraints gbc03 = new GridBagConstraints();
    gbc03.gridx = 0;
    gbc03.gridy = 2;
    gbc03.insets = new Insets(15, 5, 5, 5);
    gbc03.fill = GridBagConstraints.NONE;
    leftPanel.add(regName, gbc03);
    GridBagConstraints gbc04 = new GridBagConstraints();
    gbc04.gridx = 1;
    gbc04.insets = new Insets(15, 5, 5, 5);
    gbc04.gridy = 2;
    gbc04.gridwidth = 2;
    gbc04.fill = GridBagConstraints.NONE;
    leftPanel.add(regName2, gbc04);
    GridBagConstraints gbc05 = new GridBagConstraints();
    gbc05.gridx = 0;
    gbc05.gridy = 3;
    gbc05.insets = new Insets(5, 5, 5, 5);
    gbc05.fill = GridBagConstraints.NONE;
    leftPanel.add(regUser, gbc05);
    GridBagConstraints gbc06 = new GridBagConstraints();
    gbc06.gridx = 1;
    gbc06.insets = new Insets(5, 5, 5, 5);
    gbc06.gridy = 3;
    gbc06.gridwidth = 2;
    gbc06.fill = GridBagConstraints.NONE;
    leftPanel.add(regUser2, gbc06);
    GridBagConstraints gbc07 = new GridBagConstraints();
    gbc07.gridx = 0;
    gbc07.gridy = 4;
    gbc07.insets = new Insets(5, 5, 5, 5);
    //gbc07.anchor = GridBagConstraints.NORTH;
    gbc07.fill = GridBagConstraints.NONE;
    leftPanel.add(regPassword, gbc07);
    GridBagConstraints gbc08 = new GridBagConstraints();
    gbc08.gridx = 1;
    gbc08.insets = new Insets(5, 5, 5, 5);
    gbc08.gridy = 4;
    gbc08.gridwidth = 2;
    //gbc08.anchor = GridBagConstraints.NORTH;
    gbc08.fill = GridBagConstraints.NONE;
    leftPanel.add(regPassword2, gbc08);
    GridBagConstraints gbc09 = new GridBagConstraints();
    gbc09.gridx = 0;
    gbc09.gridy = 5;
    gbc09.insets = new Insets(5, 15, 5, 15);
    gbc09.weighty = 1.0;
    gbc09.anchor = GridBagConstraints.NORTH;
    gbc09.fill = GridBagConstraints.NONE;
    leftPanel.add(regResetBt, gbc09);
    GridBagConstraints gbc10 = new GridBagConstraints();
    gbc10.gridx = 2;
    gbc10.gridy = 5;
    gbc10.insets = new Insets(5, 15, 5, 15);
    gbc10.weighty = 1.0;
    gbc10.anchor = GridBagConstraints.NORTH;
    gbc10.fill = GridBagConstraints.HORIZONTAL;
    leftPanel.add(regSubmitBt, gbc10);
    rightPanel.setLayout(new GridBagLayout());
    rightPanel.setBackground(new Color(0, 153, 254));
    rightPanel.setBorder(BorderFactory.createLoweredBevelBorder());
    GridBagConstraints gbcR01 = new GridBagConstraints();
    gbcR01.gridx = 0;
    gbcR01.gridy = 0;
    gbcR01.insets = new Insets(35, 0, 15, 5);
    gbcR01.gridwidth = GridBagConstraints.REMAINDER;
    gbcR01.anchor = GridBagConstraints.PAGE_START;
    gbcR01.fill = GridBagConstraints.NONE;
    rightPanel.add(loginTitle, gbcR01);
    GridBagConstraints gbcR02 = new GridBagConstraints();
    gbcR02.gridx = 0;
    gbcR02.gridy = 1;
    gbcR02.insets = new Insets(35, 5, 5, 5);
    gbcR02.fill = GridBagConstraints.NONE;
    rightPanel.add(logUser, gbcR02);
    GridBagConstraints gbcR03 = new GridBagConstraints();
    gbcR03.gridx = 1;
    gbcR03.insets = new Insets(35, 5, 5, 5);
    gbcR03.gridy = 1;
    gbcR03.gridwidth = 2;
    gbc01.fill = GridBagConstraints.NONE;
    rightPanel.add(logUser2, gbcR03);
    GridBagConstraints gbcR04 = new GridBagConstraints();
    gbcR04.gridx = 0;
    gbcR04.gridy = 2;
    gbcR04.insets = new Insets(5, 5, 5, 5);
    gbcR04.fill = GridBagConstraints.NONE;
    rightPanel.add(logPassword, gbcR04);
    GridBagConstraints gbcR05 = new GridBagConstraints();
    gbcR05.gridx = 1;
    gbcR05.insets = new Insets(5, 5, 5, 5);
    gbcR05.gridy = 2;
    gbcR05.gridwidth = 2;
    gbcR05.fill = GridBagConstraints.NONE;
    rightPanel.add(logPassword12, gbcR05);
    GridBagConstraints gbcR06 = new GridBagConstraints();
    gbcR06.gridx = 0;
    gbcR06.gridy = 3;
    gbcR06.insets = new Insets(5, 15, 5, 15);
    gbcR06.weighty = 1.0;
    gbcR06.anchor = GridBagConstraints.NORTH;
    gbcR06.fill = GridBagConstraints.NONE;
    rightPanel.add(logResetBt, gbcR06);
    GridBagConstraints gbcR07 = new GridBagConstraints();
    gbcR07.gridx = 2;
    gbcR07.gridy = 3;
    gbcR07.insets = new Insets(5, 15, 5, 15);
    gbcR07.weighty = 1.0;
    gbcR07.anchor = GridBagConstraints.NORTH;
    gbcR07.fill = GridBagConstraints.HORIZONTAL;
    rightPanel.add(logSubmitBt, gbcR07);
    exitBt.addActionListener(this);  //adding an ActionListener on all JButtons
    logSubmitBt.addActionListener(this);
    regSubmitBt.addActionListener(this);
    regResetBt.addActionListener(this);
    logResetBt.addActionListener(this);
    public void actionPerformed(ActionEvent e) //creating the ActionEvents
    if (e.getSource() == exitBt)  //if the ActionEvent is exitBt
    this.dispose();       //do this
    else if (e.getSource() == logSubmitBt) //if the ActionEvent is ....
    logUser3 = getLogUser();  //call up the getLogUser method and assign value to variable logUser3
    logPassword3= getlogPassword(); //call up the getLogPassword method and assign value to variable logPassword3
    mpm.LogSubmit(logUser3, logPassword3);  //send these two variables to the LogSubmit method in mpm class (MainPageMethods), referenced at the top
    logClear();          
    else if (e.getSource() == regSubmitBt)
    regName3 = getRegName();  //call up the getRegName method and assign value to variable regName3
    regUser3 = getRegUser();  //call up the getRegUser method and assign value to variable regUser3
    regPassword3= getRegPassword();  //call up the getRegPassword method and assign value to variable regPassword3
    mpm.RegSubmit(regName3, regUser3, regPassword3); //send these three variables to the RegSubmit method in mpm class (MainPageMethods)
    regClear();
    else if (e.getSource() == regResetBt)
    regClear();  //calling up the regClear method below
    else if (e.getSource() == logResetBt)
    logClear();
    String getRegName() //methods to retrieve the values entered in the TextFields
    return regName2.getText();
    String getRegUser()
    return regUser2.getText();
    String getRegPassword()
    return regPassword2.getText();
    String getlogUser()
    return logUser2.getText();
    String getLogUser()
    return logUser2.getText();
    String getlogPassword()
    return new String(logPassword12.getPassword());
    public void regClear()  //methods to clear the TextFields
    regName2.setText("");  //by setting the text of the fields to an empty string
    regUser2.setText("");
    regPassword2.setText("");
    public void logClear()
    logUser2.setText("");
    logPassword12.setText("");
    public static void main(String[] args){  //main method to execute the class
    SwingUtilities.invokeLater(new Runnable(){
    public void run(){
    new MainPage();
    }

    Woo, 5 hour conference call.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.WindowConstants;
    public class MainView {
         private static final Font PANEL_TITLE_FONT =
              new Font("Serif", Font.BOLD + Font.ITALIC, 35);
         private final MainPageMethods mpm = new MainPageMethods();
         private final JTextField loginUsername = new JTextField(10);
         private final JPasswordField loginPassword = new JPasswordField(10);
         private final JTextField registerFullName = new JTextField(10);
         private final JTextField registerUsername = new JTextField(10);
         private final JTextField registerPassword = new JPasswordField(10);
         public MainView(final Container container, final Action exitAction) {
              super();
              container.setLayout(new BorderLayout());
              container.add(this.buildTitlePanel(), BorderLayout.PAGE_START);
              container.add(this.buildImagePanel(),BorderLayout.CENTER);
              container.add(this.buildExitPanel(exitAction), BorderLayout.PAGE_END);
              container.add(this.buildRegistrationPanel(), BorderLayout.LINE_START);
              container.add(this.buildLoginPanel(), BorderLayout.LINE_END);
         private final JPanel buildLoginPanel() {
              final ImageIcon background = new ImageIcon("london.jpg");
              final JPanel loginPanel = new JPanel(new GridBagLayout()) {
                   public void paintComponent(final Graphics g) {
                        super.paintComponent(g);
                        final Dimension d = this.getSize();
                        g.drawImage(background.getImage(), 0, 0, d.width, d.height, this);
                        this.setOpaque(false);
              loginPanel.setBackground(new Color(0, 153, 254));
              loginPanel.setBorder(BorderFactory.createLoweredBevelBorder());
              final JLabel title = new JLabel("LOGIN");
              title.setFont(PANEL_TITLE_FONT);
              title.setForeground(Color.white);
              final GridBagConstraints constraints = new GridBagConstraints();
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.insets = new Insets(35, 0, 15, 5);
              constraints.gridwidth = GridBagConstraints.REMAINDER;
              constraints.anchor = GridBagConstraints.PAGE_START;
              constraints.fill = GridBagConstraints.NONE;
              loginPanel.add(title, constraints);
              constraints.gridx = 0;
              constraints.gridy = 1;
              constraints.insets = new Insets(35, 5, 5, 5);
              constraints.gridwidth = 1;
              loginPanel.add(new JLabel("Username"), constraints);
              constraints.gridx = 0;
              constraints.gridy = 2;
              constraints.insets = new Insets(5, 5, 5, 5);
              loginPanel.add(new JLabel("Password"), constraints);
              constraints.gridx = 1;
              constraints.gridy = 1;
              constraints.insets = new Insets(35, 5, 5, 5);
              constraints.gridwidth = 2;
              loginPanel.add(this.loginUsername, constraints);
              constraints.gridx = 1;
              constraints.gridy = 2;
              constraints.insets = new Insets(5, 5, 5, 5);
              loginPanel.add(this.loginPassword, constraints);
              final JButton reset = new JButton(new ClearLoginAction());
              constraints.gridx = 0;
              constraints.gridy = 3;
              constraints.gridwidth = 1;
              constraints.insets = new Insets(5, 15, 5, 15);
              constraints.weighty = 1.0;
              constraints.anchor = GridBagConstraints.NORTH;
              constraints.fill = GridBagConstraints.NONE;
              loginPanel.add(reset, constraints);
              final JButton submit = new JButton(new LoginAction());
              constraints.gridx = 2;
              constraints.gridy = 3;
              constraints.weighty = 1.0;
              constraints.fill = GridBagConstraints.HORIZONTAL;
              loginPanel.add(submit, constraints);
              return loginPanel;
         private final JPanel buildRegistrationPanel() {
              final JPanel registrationPanel = new JPanel();
              registrationPanel.setLayout(new GridBagLayout());
              registrationPanel.setBackground(new Color(0, 153, 254));
              registrationPanel.setBorder(BorderFactory.createLoweredBevelBorder());
              final JLabel regTitle = new JLabel("REGISTER");
              regTitle.setFont(PANEL_TITLE_FONT);
              regTitle.setForeground(Color.white);
              final GridBagConstraints constraints = new GridBagConstraints();
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.insets = new Insets(35, 0, 15, 5);
              constraints.gridwidth = GridBagConstraints.REMAINDER;
              constraints.anchor = GridBagConstraints.PAGE_START;
              constraints.fill = GridBagConstraints.NONE;
              registrationPanel.add(regTitle, constraints);
              final JTextArea authMessage = new JTextArea(10, 20);
              authMessage.setText("This application is designed "
                        + "to be used by people authorised by ");
              authMessage.setLineWrap(true);
              authMessage.setEditable(false);
              authMessage.setBorder(BorderFactory.createLoweredBevelBorder());
              authMessage.setBackground(new Color(0, 153, 254));
              constraints.gridx = 0;
              constraints.gridy = 1;
              constraints.insets = new Insets(5, 5, 5, 5);
              constraints.anchor = GridBagConstraints.LINE_START;
              constraints.fill = GridBagConstraints.NONE;
              registrationPanel.add(authMessage, constraints);
              constraints.gridx = 0;
              constraints.gridy = 2;
              constraints.gridwidth = 1;
              constraints.insets = new Insets(15, 5, 5, 5);
              registrationPanel.add(new JLabel("Full Name"), constraints);
              constraints.gridx = 0;
              constraints.gridy = 3;
              constraints.insets = new Insets(5, 5, 5, 5);
              registrationPanel.add(new JLabel("Username"), constraints);
              constraints.gridx = 0;
              constraints.gridy = 4;
              constraints.insets = new Insets(5, 5, 5, 5);
              registrationPanel.add(new JLabel("Password"), constraints);
              constraints.gridx = 1;
              constraints.gridy = 2;
              constraints.insets = new Insets(15, 5, 5, 5);
              constraints.gridwidth = 2;
              registrationPanel.add(this.registerFullName, constraints);
              constraints.gridx = 1;
              constraints.gridy = 3;
              constraints.insets = new Insets(5, 5, 5, 5);
              registrationPanel.add(this.registerUsername, constraints);
              constraints.gridx = 1;
              constraints.gridy = 4;
              registrationPanel.add(this.registerPassword, constraints);
              final JButton reset = new JButton(new ClearRegistrationAction());
              constraints.gridx = 0;
              constraints.gridy = 5;
              constraints.insets = new Insets(5, 15, 5, 15);
              constraints.weighty = 1.0;
              constraints.anchor = GridBagConstraints.NORTH;
              registrationPanel.add(reset, constraints);
              final JButton submit = new JButton(new LoginAction());
              constraints.gridx = 2;
              constraints.gridy = 5;
              constraints.fill = GridBagConstraints.HORIZONTAL;
              registrationPanel.add(submit, constraints);
              return registrationPanel;
         public JPanel buildTitlePanel() {
              final JPanel titlePanel = new JPanel();
              titlePanel.setBackground(new Color(223, 0, 148));
              titlePanel.setBorder(BorderFactory.createRaisedBevelBorder());
              final JLabel mainTitle = new JLabel("LONDON 2012");
              mainTitle.setFont(mainTitle.getFont().deriveFont(Font.BOLD, 48));
              mainTitle.setForeground(Color.white);
              titlePanel.add(mainTitle);
              return titlePanel;
         public JPanel buildExitPanel(final Action exitAction) {
              final JPanel exitPanel = new JPanel();
              exitPanel.setBorder(BorderFactory.createRaisedBevelBorder());
              exitPanel.setBackground(new Color(223, 0, 148));
              exitPanel.setPreferredSize(new Dimension(608, 65));
              final JButton exit = new JButton(exitAction);
              exitPanel.add(exit);
              return exitPanel;
         public JPanel buildImagePanel() {
              final JPanel imagePanel = new JPanel();
              imagePanel.setLayout(new FlowLayout());
              imagePanel.setBackground(new Color(0, 153, 254));
              imagePanel.setBorder(BorderFactory.createRaisedBevelBorder());
              final Icon image = new ImageIcon("london_2012.png");
              final JLabel centerPanel1 = new JLabel(image);
              imagePanel.add(centerPanel1);
              return imagePanel;
         private static class ExitAction extends AbstractAction {
              private final JFrame frame;
              public ExitAction(final JFrame frame) {
                   super("EXIT");
                   this.frame = frame;
              public void actionPerformed(final ActionEvent e) {
                   this.frame.dispose();
         private class LoginAction extends AbstractAction {
              public LoginAction() {
                   super("SUBMIT");
              public void actionPerformed(final ActionEvent e) {
                   MainView.this.mpm.LogSubmit(
                             MainView.this.loginUsername.getText(),
                             MainView.this.loginPassword.getPassword());
         private class RegisterAction extends AbstractAction {
              public RegisterAction() {
                   super("SUBMIT");
              public void actionPerformed(final ActionEvent e) {
                   MainView.this.mpm.RegSubmit(
                             MainView.this.registerFullName.getText(),
                             MainView.this.registerUsername.getText(),
                             MainView.this.registerPassword.getText());
         private class ClearLoginAction extends AbstractAction {
              public ClearLoginAction() {
                   super("RESET");
              public void actionPerformed(final ActionEvent e) {
                   MainView.this.loginUsername.setText("");
                   MainView.this.loginPassword.setText("");
         private class ClearRegistrationAction extends AbstractAction {
              public ClearRegistrationAction() {
                   super("RESET");
              public void actionPerformed(final ActionEvent e) {
                   MainView.this.registerFullName.setText("");
                   MainView.this.registerUsername.setText("");
                   MainView.this.registerPassword.setText("");
         public static void main(String[] args) {
              final JFrame frame = new JFrame();
              new MainView(frame.getContentPane(), new ExitAction(frame));
              frame.setTitle("Nrr");
              frame.setLocation(new Point(0, 0));
              frame.setSize(800, 608);
              frame.pack();
              frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }

  • Add Icon to a JTextArea

    Hola a todos,
    I want to add an icon to a JTextArea. How can I do that?
    Chao
    Juergen

    With the JTextPane and the method
    insertIcon(Icon g);
    I can insert an icon but only at the end. I want to have the icon at the beginning of the line.
    The text is set by:
    setText(....);
    I think the text overrides the icon. How can I add the text behind the icon?
    setText (valor.toString());
    insertIcon(new ImageIcon("libro1.gif"));
    Then I have the Text and the icon behind.
    insertIcon(new ImageIcon("libro1.gif"));
    setText (valor.toString());
    Then I do only have the text.
    Does anybody know why?
    Chao
    Juergen

  • Keyevent used for setMnemonic show in editable jtextarea

    I don't know if this has been fix. I notice that if I used the setMnemonic to access a editable jtextarea, that the key I used is inserted into the jtextarea. After searching the web, I found nothing about this problem.
    So, I took the program from the java tutorial, MenuDemo.java and reproduct the same problem but setting the jtextarea to editable (output.setEditable(true). It happens everytime. Below is the MenuDemo.java with the change. By selecting t or b in the A Menu menu,then which ever t or b used will show up in the text area after the expected line displays. I am using 1.5 so this problem may have been fix.
    If anyone knows if it has or a work around, please let me know.
    Thanks
    Kevin
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    * This class adds event handling to MenuLookDemo.
    public class MenuDemo extends JFrame
    implements ActionListener, ItemListener {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public MenuDemo() {
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Add regular components to the window, using the default BorderLayout.
    Container contentPane = getContentPane();
    output = new JTextArea(5, 30);
    output.setEditable(true);
    scrollPane = new JScrollPane(output);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    menuBar.add(menu);
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem("Both text and icon",
    new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);
    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);
    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);
    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Action event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")";
    output.append(s + newline);
    public void itemStateChanged(ItemEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    String s = "Item event detected."
    + newline
    + " Event source: " + source.getText()
    + " (an instance of " + getClassName(source) + ")"
    + newline
    + " New state: "
    + ((e.getStateChange() == ItemEvent.SELECTED) ?
    "selected":"unselected");
    output.append(s + newline);
    // Returns just the class name -- no package info.
    protected String getClassName(Object o) {
    String classString = o.getClass().getName();
    int dotIndex = classString.lastIndexOf(".");
    return classString.substring(dotIndex+1);
    public static void main(String[] args) {
    MenuDemo window = new MenuDemo();
    window.setTitle("MenuDemo");
    window.setSize(450, 260);
    window.setVisible(true);

    Yes your are correct. I forgot why I went to 1.5 but until better time come along and I can get a new computer, I will have to live with 1.4.2._06. But, it did fit my problem.

  • How to drag and drop a file with its Systemfile icon to a Jtext area

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    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.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    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.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

  • Icon in front of the JList items?

    Hola a todos,
    I am rendering a JList to a JTextArea and I want to add a icon in front of each of the items. First it can be the same icon later each one should become its own one.
    I am using this little piece of code to render the JList:
    JList lista_libros = new JList();
    lista_libros.setCellRenderer(new mirenderer());
    class mirenderer extends JTextArea implements ListCellRenderer
              public Component getListCellRendererComponent ( JList lista_libros, Object valor,
              int indice,     boolean seleccionado,boolean conFoco)
                   setBorder(new BevelBorder ( BevelBorder.RAISED));
                   setText (valor.toString());
                   //setIcon(new ImageIcon("libro1.gif"));
                   if (seleccionado)
                        setBackground (Color.blue);
                        setForeground (Color.white);
                   else
                        setBackground (Color.white);
                        setForeground (Color.black);
                   return this;
              } // getListCellRendererComponent()
         } // class mirenderer
    When I am using a JLabel instead of a JTextArea it is easy to add an icon, but the text is to long for only one line.
    Is it possible to add an icon to each item of the JList in the JTextArea?
    Chao
    Juergen

    Or is it possible to write a JLabel over moore than only one line?
    Chao
    Juergen

  • Document Listener for JTextArea in JTable

    I am trying to implement a DocumentListener for JTextArea in JTable, but its not happening.
    Can someone tell me what's wrong. SSCCE below.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.text.Document;
    public class MyTable_TextArea extends JTable {
         private DefaultTableModel defaultTableModel;
         private Object[][] dataArray;
         private Object[] columnNameArray;
         public final int TEXT_COLUMN = 0;     
         // column headers
         public static final String TEXT_COLUMN_HEADER = "Text";
         // text area
         TextFieldRenderer3 textFieldRenderer3;
          * constructor
          * @param variableNameArray
          * @param columnNameArray
         public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
              this.dataArray = variableNameArray;
              this.columnNameArray = columnNameArray;
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              // text field
            textFieldRenderer3 = new TextFieldRenderer3();
              MyDocumentListener myListener = new MyDocumentListener();
              textFieldRenderer3.getDocument().addDocumentListener(myListener);
            TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
              modelColumn.setCellRenderer(textFieldRenderer3);
          * nested class
         class MyDocumentListener implements DocumentListener {
             String newline = "\n";
             public void insertUpdate(DocumentEvent e) {
                  System.out.println ("insert update");
                 updateLog(e, "inserted into");
             public void removeUpdate(DocumentEvent e) {
                  System.out.println ("remove update");
                 updateLog(e, "removed from");
             public void changedUpdate(DocumentEvent e) {
                 //Plain text components do not fire these events
             public void updateLog(DocumentEvent e, String action) {
                 Document doc = (Document)e.getDocument();
                 int changeLength = e.getLength();
                 textFieldRenderer3.append(
                     changeLength + " character" +
                     ((changeLength == 1) ? " " : "s ") +
                     action + doc.getProperty("name") + "." + newline +
                     "  Text length = " + doc.getLength() + newline);
          * @param args
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception e){
                   e.printStackTrace();
             String[] columnNameArray = {
                       TEXT_COLUMN_HEADER,
                       "1",
                       "2",
              Object[][]  dataArray = {      {"", "", ""},      };
              final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(panel));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(500, 200));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(300, 200);
              frame.pack();
              frame.setVisible(true);
    class TextFieldRenderer3 extends JTextArea implements TableCellRenderer {
         Icon defaultIcon;
         boolean isChecked = false;
         public TextFieldRenderer3() {
              System.out.println ("TextFieldRenderer()");
              setToolTipText("Double click to type");
         @Override
         public Component getTableCellRendererComponent(JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column) {
              System.out.println ("TextFieldRenderer.getTableCellRendererComponent() row/column: " + row + "\t"+ column);
              return this;
    }

    I've implemented in the cell editor. I don't see how to get the value being typed (and nothing appears in the text area)
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.EventObject;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.text.Document;
    public class MyTable_TextArea extends JTable {
         private DefaultTableModel defaultTableModel;
         private Object[][] dataArray;
         private Object[] columnNameArray;
         public final int TEXT_COLUMN = 0;     
         // column headers
         public static final String TEXT_COLUMN_HEADER = "Text";
         // text area
         TextAreaEditor textAreaEditor;
          * constructor
          * @param variableNameArray
          * @param columnNameArray
         public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
              this.dataArray = variableNameArray;
              this.columnNameArray = columnNameArray;
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              // text field
            textAreaEditor = new TextAreaEditor();
              MyDocumentListener myListener = new MyDocumentListener();
              textAreaEditor.getDocument().addDocumentListener(myListener);
            TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
              modelColumn.setCellEditor(textAreaEditor);
          * nested class
         class MyDocumentListener implements DocumentListener {
             String newline = "\n";
             public void insertUpdate(DocumentEvent e) {
                  System.out.println ("insert update");
                 updateLog(e, "inserted into");
             public void removeUpdate(DocumentEvent e) {
                  System.out.println ("remove update");
                 updateLog(e, "removed from");
             public void changedUpdate(DocumentEvent e) {
                 //Plain text components do not fire these events
             public void updateLog(DocumentEvent e, String action) {
                 Document doc = (Document)e.getDocument();
                 int changeLength = e.getLength();
                 textAreaEditor.append(
                     changeLength + " character" +
                     ((changeLength == 1) ? " " : "s ") +
                     action + doc.getProperty("name") + "." + newline +
                     "  Text length = " + doc.getLength() + newline);
          * @param args
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception e){
                   e.printStackTrace();
             String[] columnNameArray = {
                       TEXT_COLUMN_HEADER,
                       "1",
                       "2",
              Object[][]  dataArray = {      {"", "", ""},      };
              final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(panel));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(500, 200));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(300, 200);
              frame.pack();
              frame.setVisible(true);
    class TextAreaEditor extends JTextArea implements TableCellEditor {
         Icon defaultIcon;
         boolean isChecked = false;
         public TextAreaEditor() {
              System.out.println ("TextAreaEditor()");
              setToolTipText("Double click to type");
         @Override
         public Component getTableCellEditorComponent(JTable arg0,
                   Object arg1,
                   boolean arg2,
                   int arg3,
                   int arg4) {
              System.out.println ("TextAreaEditor() arg1: " + arg1 + "arg2: " + arg2  + " arg3: " + arg3  + " arg4: " + arg4  );
              return null;
         @Override
         public void addCellEditorListener(CellEditorListener arg0) {
              System.out.println ("TextAreaEditor().addCellEditorListener");
         @Override
         public void cancelCellEditing() {
              System.out.println ("TextAreaEditor().cancelCellEditing");
         @Override
         public Object getCellEditorValue() {
              System.out.println ("TextAreaEditor().getCellEditorValue");
              return null;
         @Override
         public boolean isCellEditable(EventObject arg0) {
              System.out.println ("TextAreaEditor().isCellEditable");
              return true;
         @Override
         public void removeCellEditorListener(CellEditorListener arg0) {
              System.out.println ("TextAreaEditor().removeCellEditorListener");          
         @Override
         public boolean shouldSelectCell(EventObject arg0) {
              System.out.println ("TextAreaEditor().shouldSelectCell");
              return false;
         @Override
         public boolean stopCellEditing() {
              System.out.println ("TextAreaEditor().stopCellEditing");
              return false;
    }

  • TreeCellRendere updating icons

    I have a TreeCellRederer which changes the icons of JTREE when openen/closing items (linked to start/stop applications)
    When an item (application) is open and i switch to another item, the icon does not change (correct because app is still running). When i select an item and close the application, the icon is changed correctly (from closed to open and vise versa).
    When an item (app3) is open and i switch to another application (app2) and then close the app2, my cursus jumps to item 0 (top level) and the icon of the app2 is closed. Then i close app3 (without selecting it first). Now it is goes wrong, the icon is not changed. This is because the line is not rendered.
    I can force closing of the item by jumping to the last item in the list and then to the first item in the list "removeFromActiveApplicationList(String application)" method, but this is a bit of overkill.
    The problem is that the item-row is not rendered when application is closed without the item be-ing active. Any idea how to solve this?
    I will include all coding but icon-iconimages.
    MenuApplication:
    package myMenu;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyVetoException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.StringTokenizer;
    import java.util.logging.Handler;
    import java.util.logging.Logger;
    import javax.swing.ImageIcon;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import testje.testApp;
    import testje.testInternalFrame;
    public class MenuTest extends JFrame implements TreeSelectionListener{
        // System Properties
        public static Logger myLogger = Logger.getLogger(MenuTest.class.getName());
        public Handler myHandler = null;
        private static String appName;
        // Variables
        public ArrayList activeApplicationList;
        private Object[] [] data;
        private ArrayList sflData;
        public String selectedApplication;
        // Swing objects and varialbles
        public JDesktopPane myDeskTop;
        private JPanel jContentPane = null;
        private JSplitPane jSplitPane = null;
        private JTree jTree = null;
        private javax.swing.JMenuBar jJMenuBar = null;
        private javax.swing.JMenu fileMenu = null;
        private javax.swing.JMenuItem exitMenuItem = null;
        private boolean packFrame = false;
        private PropertyChangeEvent currentEvent;
        // Applications
        private testApp myPanelTestje;
        private testInternalFrame myFrameTestje;
         * This is the default constructor
        public MenuTest() {
            super();
            initialize();
            setAppName("Test Menu");
         * Launches this application
        public static void main(String[] args) {
             MenuTest myMenu = new MenuTest();
             myMenu.setVisible(true);
         * This method initializes this
         * @return void
        private void initialize() {
            setContentPane(getJContentPane());
            setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
            setJMenuBar(getJJMenuBar());
            setSize(800, 600);
            setTitle("MyMenu");
            setVisible(true);
            //Validate frames that have preset sizes
            //Pack frames that have useful preferred size info, e.g. from their layout
            if (packFrame) {
              this.pack();
            else {
              this.validate();
            //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = this.getSize();
            if (frameSize.height > screenSize.height) {
              frameSize.height = screenSize.height;
            if (frameSize.width > screenSize.width) {
              frameSize.width = screenSize.width;
            setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
         * This method initializes jJMenuBar   
         * @return javax.swing.JMenuBar
        private javax.swing.JMenuBar getJJMenuBar() {
            if (jJMenuBar == null) {
                jJMenuBar = new javax.swing.JMenuBar();
                jJMenuBar.add(getFileMenu());
            return jJMenuBar;
         * This method initializes jMenu   
         * @return javax.swing.JMenu   
        private javax.swing.JMenu getFileMenu() {
            if (fileMenu == null) {
                fileMenu = new javax.swing.JMenu();
                fileMenu.setText("File");
                fileMenu.add(getExitMenuItem());
            return fileMenu;
         * This method initializes jMenuItem   
         * @return javax.swing.JMenuItem   
        private javax.swing.JMenuItem getExitMenuItem() {
            if (exitMenuItem == null) {
                exitMenuItem = new javax.swing.JMenuItem();
                exitMenuItem.setText("Exit");
                exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {   
                        System.exit(0);
            return exitMenuItem;
         * This method initializes jContentPane
         * @return javax.swing.JPanel  
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                jContentPane = new JPanel();
                jContentPane.setLayout(new BorderLayout());
                jContentPane.add(getJSplitPane(), java.awt.BorderLayout.CENTER);
            return jContentPane;
         * This method initializes jSplitPane  
         * @return javax.swing.JSplitPane  
        private JSplitPane getJSplitPane() {
            if (jSplitPane == null) {
                jSplitPane = new JSplitPane();
                jSplitPane.setLeftComponent(getJTree());
                myDeskTop = new JDesktopPane();
                jSplitPane.setRightComponent(myDeskTop);
                jSplitPane.setDividerLocation(150);
            return jSplitPane;
        private JTree getJTree() {
            if (jTree == null) {
                // Create Root
                DefaultMutableTreeNode root = new DefaultMutableTreeNode("Conti7");
                setActiveApplicationList(new ArrayList());
                // Create ApplicationsList
                // Get Applicationlist
                getApplicationList();
                // Process MenuArray to create Menu
                String previousFolder = "";
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
                for (int i = 0; i < sflData.size(); i++){
                    myLogger.fine(
                            "Dataline "+i +" =" + data[0] + " | "
    + data[i][1] + " | "
    + data[i][2] + " | "
    + data[i][3] + " | "
    + data[i][4] + " | "
    + data[i][5]);
    if (!(((String)data[i][2]).equals(previousFolder))) {
    if (!(previousFolder.equals(""))){
    root.add(newNode);
    previousFolder = (String)data[i][2];
    newNode = new DefaultMutableTreeNode(previousFolder);
    newNode.add(new DefaultMutableTreeNode(data[i][3]));
    if (!previousFolder.equals("")){
    root.add(newNode);
    // Add Full menu to tree
    jTree = new JTree(root);
    jTree.setCellRenderer(new TreeExRenderer());
    jTree.addTreeSelectionListener(this);
    return jTree;
    public void valueChanged(TreeSelectionEvent event) {
    String selectedApplication = jTree.getLastSelectedPathComponent().toString();
    myLogger.info(
    "Current Item Selection = " + selectedApplication);
    setSelectedApplication(selectedApplication);
    activateApplication(selectedApplication);
    private void activateApplication(String selectedApplication) {
    if (getSelectedApplication().equals("PanelTestje")){
    if (myPanelTestje==null){
    myPanelTestje = new testje.testApp();
    addInternalFrame(myPanelTestje);
    activateInternalFrame(myPanelTestje);
    if (getSelectedApplication().equals("FrameTestje")){
    if (myFrameTestje==null){
    myFrameTestje = new testje.testInternalFrame();
    addInternalFrame(myFrameTestje);
    activateInternalFrame(myFrameTestje);
    public void addInternalFrame(JInternalFrame myFrame) {
    myDeskTop.add(myFrame);
    myFrame.pack();
    myFrame.setClosable(true);
    try {
    myFrame.setMaximum(true);
    } catch (PropertyVetoException e){}
    myFrame.addPropertyChangeListener(new PropertyChangeHandler());
    activeApplicationList.add(getSelectedApplication());
    Collections.sort(activeApplicationList);
    public void activateInternalFrame(JInternalFrame myFrame) {
    myFrame.setVisible(true);
    myFrame.toFront();
    class PropertyChangeHandler implements PropertyChangeListener {
    public void propertyChange(PropertyChangeEvent e) {
    if (((String)e.getPropertyName()).equals("closed")){
    setCurrentEvent(e);
    deActivateApplication(e);
    private void deActivateApplication(PropertyChangeEvent currentEvent){
    if ((getCurrentEvent().getSource() instanceof testje.testApp)){
    myPanelTestje = null;
    removeFromActiveApplicationList("PanelTestje");
    if ((getCurrentEvent().getSource() instanceof testje.testInternalFrame)){
    myFrameTestje = null;
    removeFromActiveApplicationList("FrameTestje");
    * Deze methode wordt gebruikt om de applicatienaam op
    * te vragen.
    * <p>
    * @return appName : appName Objectvalue.
    public static String getAppName() {
    return appName;
    * Deze methode wordt gebruikt om de applicatie af te sluiten
    * nadat eerst connectieObject wordt afgesloten.
    * <p>
    public static void exitApplication() {
    myLogger.info("End application.");
    System.exit(0);
    private static void setAppName(String appName)
    MenuTest.appName = appName;
    public class TreeExRenderer extends DefaultTreeCellRenderer {
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
    row, hasFocus);
    String nodeName = value.toString();
    ImageIcon main_leaf = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon main_open = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon main_close = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon leafIcon = createImageIcon("/images/jTreeFolderClosed.gif");
    ImageIcon leafOpen = createImageIcon("/images/jTreeFolderOpen.gif");
    ImageIcon leafClosed = createImageIcon("/images/jTreeFolderClosed.gif");
    ImageIcon leafSelected = createImageIcon("/images/jTreeItemSelected.gif");
    ImageIcon leafActivated = createImageIcon("/images/jTreeItemSelected.gif");
    if (row==0){
    setIcon(main_leaf);
    } else {
    if(sel){
    setIcon(leafSelected);
    } else {
    if (!expanded) {
    if (isApplicationInActiveList(nodeName)){
    setIcon(leafActivated);
    } else {
    setIcon(leafClosed);
    }else{
    setIcon(leafOpen);
    return this;
    public ImageIcon createImageIcon(String path) {
    URL imgURL = MenuTest.class.getResource(path);
    URL imgURL1 = MenuTest.class.getResource(path);
    if ((imgURL != null)) {
    return new ImageIcon(imgURL);
    } else if ((imgURL == null)) {
    return new ImageIcon(imgURL1);
    } else {
    System.out.println("Hello ");
    System.err.println("Couldn't find file: " + path);
    return null;
    private ArrayList getActiveApplicationList()
    return activeApplicationList;
    private void setActiveApplicationList(ArrayList activeApplicationList)
    this.activeApplicationList = activeApplicationList;
    private boolean isApplicationInActiveList(String nodeName)
    if (activeApplicationList.indexOf(nodeName)>-1) {
    return true;
    } else {
    return false;
    public void removeFromActiveApplicationList(String application)
    activeApplicationList.remove(activeApplicationList.indexOf(application));
    // jTree.setSelectionRow((jTree.getRowCount())-1);
    jTree.setSelectionRow(0);
    public String getSelectedApplication()
    return selectedApplication;
    private void setSelectedApplication(String selectedApplication)
    this.selectedApplication = selectedApplication;
    public PropertyChangeEvent getCurrentEvent()
    return currentEvent;
    private void setCurrentEvent(PropertyChangeEvent currentEvent)
    this.currentEvent = currentEvent;
    private void getApplicationList() {
    sflData = new ArrayList();
    // Get Applicationlist
    sflData.add("PGO;50;General;App1;pack.myApp1;Application 1");
    sflData.add("PGO;55;Operational;App2;pack.myApp2;Application 2");
    sflData.add("PGO;60;Operational;App3;pack.myApp3;Application 3");
    sflData.add("PGO;65;Expeditie;PanelTestje;testje.Paneltestje;Expeditie Paneltestje");
    sflData.add("PGO;70;Desktop;App4;pack.myApp4;Application 4");
    sflData.add("PGO;75;Manifest;FrameTestje;testje.FrameTestje;Maritiem FrameTestje");
    sflData.add("PGO;80;Desktop;App5;pack.myApp5;Application 5");
    // Convert applicationlist to MenuArray
    data = new Object[sflData.size()][6];
    for (int i = 0; i < sflData.size(); i++){
    int count = 0;
    String str;
    str = (String)sflData.get(i);
    StringTokenizer token = new StringTokenizer(str,";");
    while (token.hasMoreTokens()){
    data [i] [count] = token.nextToken();
    count++;
    *testapp1*package testje;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testApp
    extends JInternalFrame {
         testPanel p;
    Container c;
    boolean packFrame = false;
         public testApp() {
              super("Swing-Toepassing PanelTestje");
              c = getContentPane();
    c.setLayout(new BorderLayout());
              p = new testPanel();
              c.add(p);
    //setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
    this.pack();
    else {
    this.validate();
    // addWindowListener(new WindowAdapter() {
    // public void windowClosed(WindowEvent e) {
    // System.exit(0);
         public static void main(String[] args) {
              // final JFrame f = new testApp();
    // new testApp();
    *testInternalFrame*/*
    * Created on 19-apr-2007
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package testje;
    import javax.swing.*;
    import java.awt.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testInternalFrame extends JInternalFrame {
         public void testInternalFrame(){
              setBackground(Color.white);
              Container contentPane = getContentPane();
              setLocation(20,20);
              setTitle("Internal Frame");
              setClosable(true);
              setResizable(true);
              setMaximizable(true);
              setIconifiable(true);
              setVisible(true);
              contentPane.setLayout(new FlowLayout());
              contentPane.add(new JTextArea(5,15), "Center");
              pack();
    *testPanel*/*
    * Created on 19-apr-2007
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package testje;
    import javax.swing.*;
    import java.awt.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testPanel extends JPanel {
         public void testPanel(){
              setBackground(Color.blue);
         public void paintComponent (Graphics g){
              super.paintComponent(g);
              g.drawString("Groeten van Patrick", 0, 60);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    When you say "the JLabel changes" I'm guessing you mean that the JLabel variable named "imageLabel" was the thing that changed? That won't change the GUI's reference to the original JLabel object.
    Which is what you have to change. You have a reference to that object in the form of the "imageLabel" variable; to change the object you call one of its methods, like maybe setIcon() or something... whatever your ImageManager class is doing to create the label in the first place.

  • JPanel Scrollable mimic Windows Explorer Icon View

    I am developing an image viewer application, and I want my thumbnail image JPanel to mimic MS Windows Explorer's layout in icon view. However, I have not been able to accomplish this. I have searched high and low, finding many others with my same problem, but no solution. To see exactly what I want to mimic, go to Windows Explorer and take a look at Icon View.
    Windows Explorer seems to be using a type of FlowLayout, and the icons get wrapped to the next line. If the number of icons exceeds the viewable space, the vertical scrollbar appears. Note that there is no horizontal scrolling; only vertical scrolling with the FlowLayout. If the user adjusts the SplitPane, then the layout adjusts the scrolling and icons accordingly.
    ============================================================
    QUESTION: How can I get my JPanel to mimic Windows Explorer Icon View?
    ============================================================
    10 Dukes to anyone who can get this to mimic Windows Explorer. Ideally the solution would not be too involved.
    P.S. I think it stinks that JPanel, by design, does not implement Scrollable Interface. Even then, it doesn't work the way I want it to with my FlowLayout and only vertical scrolling. Does anyone understand why it doesn't implement Scrollable, like JTextArea, JEditorPane, etc. do?
    Thanks
    Wayne

    Thanks camickr! I didn't try your layout manager since I managed to find another one which seems to do the trick as well. Here is the link from which I found it:
    http://groups.google.com/groups?selm=c43ovb%242db505%241%40ID-76750.news.uni-berlin.de&output=gplain
    It seems that in the source there is a small bug which is easy to fix. I think the boolean parameters in minimumLayoutSize and preferredLayoutSize should be changed.
    So in minimumLayoutSize():
    return computeSize(target, true);and in preferredLayoutSize():
    return computeSize(target, false);After that fix, it worked just fine for me.
    Here is the complete source (author Babu Kalakrishnan):
    import java.awt.*;
      * A modified version of FlowLayout that allows containers using this
      * Layout to behave in a reasonable manner when placed inside a
      * JScrollPane
      * @author Babu Kalakrishnan
    public class ModifiedFlowLayout extends FlowLayout
         public ModifiedFlowLayout()
             super();
         public ModifiedFlowLayout(int align)
             super(align);
         public ModifiedFlowLayout(int align, int hgap, int vgap)
             super(align, hgap, vgap);
         public Dimension minimumLayoutSize(Container target)
             return computeSize(target, false);
         public Dimension preferredLayoutSize(Container target)
             return computeSize(target, true);
         private Dimension computeSize(Container target, boolean minimum)
             synchronized (target.getTreeLock())
                 int hgap = getHgap();
                 int vgap = getVgap();
                 int w = target.getWidth();
             // Let this behave like a regular FlowLayout (single row)
             // if the container hasn't been assigned any size yet     
                 if (w == 0)
                     w = Integer.MAX_VALUE;
                 Insets insets = target.getInsets();
                 if (insets == null)
                     insets = new Insets(0, 0, 0, 0);
                 int reqdWidth = 0;
                 int maxwidth = w - (insets.left + insets.right + hgap * 2);
                 int n = target.getComponentCount();
                 int x = 0;
                 int y = insets.top;
                 int rowHeight = 0;
                 for (int i = 0; i < n; i++)
                     Component c = target.getComponent(i);
                     if (c.isVisible())
                         Dimension d =
                             minimum ? c.getMinimumSize() :      
                          c.getPreferredSize();
                         if ((x == 0) || ((x + d.width) <= maxwidth))
                             if (x > 0)
                                 x += hgap;
                             x += d.width;
                             rowHeight = Math.max(rowHeight, d.height);
                         } else
                             x = d.width;
                             y += vgap + rowHeight;
                             rowHeight = d.height;
                         reqdWidth = Math.max(reqdWidth, x);
                 y += rowHeight;
                 return new Dimension(reqdWidth+insets.left+insets.right, y);
    }

  • I want to drag and drop a file to a JText area with its file icon

    I want to drag and drop a file to a JText area with its file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    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.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors.isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();
    }

    This appears to be a long-standing bug:
    https://bugzilla.mozilla.org/show_bug.cgi?id=634720
    and the accepted workaround is stated in comment 11.
    Oddly, it's possible to do the reverse, i.e. drag multiple eml files from Explorer to a TB folder.

  • JTextArea not showing

    I can get my first set of JScrollPane and JTextArea to appear, but the second just will not. Here is all my code refering to the frame. I hope you can find what I cannot.
            public Frame(){
                Object[] items={"Choose One","1","2","3","4","5","6","7","8","9","10"};
                JPanel c=(JPanel)getContentPane();
                JOptionPane jOpt=new JOptionPane();
                ImageIcon icon=new ImageIcon();
                jArea=new JTextArea();
                JScrollPane jScroll=new JScrollPane(jArea);
                jArea2=new JTextArea();
                JScrollPane jScroll2=new JScrollPane(jArea2);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(new Dimension(250, 500));
                setTitle("Towers Of Hanoi");
                //setResizable(false);
                setLocationRelativeTo(null);
                jScroll.setPreferredSize(new Dimension(125, 500));
                jScroll.setPreferredSize(new Dimension(125,500));
                jScroll.setViewportView(jArea);
                jScroll2.setViewportView(jArea2);
                c.setLayout(new BorderLayout());
                c.add(jOpt);
                jOpt.setVisible(false);
                c.add(jScroll, java.awt.BorderLayout.WEST);
                c.add(jScroll2, java.awt.BorderLayout.EAST);
                jScroll2.setVisible(true);
                boolean done=false;
                String s="";
                while(done==false){
                    s=(String)jOpt.showInputDialog(this,"How many disks should be used?","",jOpt.PLAIN_MESSAGE,icon,items,"Choose One");
                    if(!s.equals("Choose One"))
                        done=true;
                height=Integer.parseInt(s);
                show();
            }//Close Frame Constructor

    maybe
    setLocationRelativeTo(null);
    jScroll.setPreferredSize(new Dimension(125, 500));
    jScroll.setPreferredSize(new Dimension(125,500));//should be jScroll2.setPreferredSize(...)
    jScroll.setViewportView(jArea);

  • X (Close) icon doesn't work

    hi,
    I have one problem now. I tried to make 'X' (Close) icon work (i.e. the dialog window should be closed whenever clicking 'X' icon). I use:
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    but it does not work. Anybody could help me solve this problem? Thanks a lot.
    Jrabi

    Well, it is a part of a large project.
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import java.awt.*;
    import com.klg.jclass.field.*;
    import com.borland.dbswing.*;
    import java.awt.event.*;
    import java.util.*;
    public class CitrixAgent_Wiz extends WizardDialog implements SupportService {
    JPanel basePanel = new JPanel();
    WizardTopPanel topPanel = new WizardTopPanel();
    JPanel contentPanel = new JPanel();
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    CardLayout cardLayout = new CardLayout();
    WizardButtonBar buttonBar = new WizardButtonBar(cardLayout, contentPanel, topPanel);
    JScrollPane jScrollPane3 = new JScrollPane();
    GridBagLayout gridBagLayout7 = new GridBagLayout();
    JTextArea finishLabel = new JTextArea();
    JTextArea finishList = new JTextArea();
    JPanel lastPanel = new JPanel();
    TerminalServicesEnvironmentPanel terminalServicesEnvironmentPanel1 = new TerminalServicesEnvironmentPanel();
    TerminalServicesRemoteControlPanel terminalServicesRemoteControlPanel1 = new TerminalServicesRemoteControlPanel();
    TerminalServicesSessionPanel terminalServicesSessionPanel1 = new TerminalServicesSessionPanel();
    private String[] availableDriveLetters = {"D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "O:"};
    private String warning;
    private String warningMessage;
    private String advanced;
    private String defaultUserHomePath;
    private String defaultUserProfilePath;
    public CitrixAgent_Wiz() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    try{
    topPanel.setImage((ImageIcon)Global.imageResources.getDialogIcons().get("CitrixCompany"));
    advanced = Global.getString("WIZARD.TERMINAL.1.ADVANCED");
    warning = Global.getString("WIZARD.TERMINAL.1.WARNING");
    warningMessage = Global.getString("WIZARD.TERMINAL.1.WARNINGMESSAGE");
    catch(Exception e){
    System.out.println("Could not get icon " + e.toString());
    setSize(475, 450);
    String provision = Global.getString("WIZARD.COMMON.PROVISIONFOR");
    topPanel.setCreateLabel(provision);
    private void jbInit() throws Exception {
    this.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0); }
    this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    basePanel.setLayout(gridBagLayout1);
    contentPanel.setLayout(cardLayout);
    jScrollPane3.setBorder(BorderFactory.createLoweredBevelBorder());
    jScrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    finishLabel.setLineWrap(true);
    finishLabel.setWrapStyleWord(true);
    finishLabel.setBackground(new Color(212,208,200));
    finishLabel.setEditable(false);
    finishLabel.setText(Global.getString("WIZARD.TERMINAL.4.FINISH"));
    finishList.setDoubleBuffered(true);
    finishList.setBackground(Color.lightGray);
    finishList.setEditable(false);
    terminalServicesRemoteControlPanel1.requireCheckBox.setSelected(true);
    lastPanel.setLayout(gridBagLayout7);
    this.getContentPane().add(basePanel, new PaneConstraints("jPanel1", "jPanel1", PaneConstraints.ROOT, 1.0f));
    basePanel.add(topPanel, new GridBagConstraints(0, 0, 1, 1, 100.0, 5.0
    ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    basePanel.add(contentPanel, new GridBagConstraints(0, 1, 1, 1, 100.0, 90.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    contentPanel.add(terminalServicesEnvironmentPanel1, "terminalServicesEnvironmentPanel1");
    contentPanel.add(terminalServicesRemoteControlPanel1, "terminalServicesRemoteControlPanel1");
    contentPanel.add(terminalServicesSessionPanel1, "terminalServicesSessionPanel1");
    contentPanel.add(lastPanel, "lastPanel");
    lastPanel.add(finishLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 10, 2, 10), 0, 0));
    lastPanel.add(jScrollPane3, new GridBagConstraints(0, 1, 1, 1, 100.0, 105.0
    ,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 10, 0, 10), 0, 255));
    jScrollPane3.getViewport().add(finishList, null);
    basePanel.add(buttonBar, new GridBagConstraints(0, 2, 1, 1, 100.0, 5.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    buttonBar.addToActionListener();
    buttonBar.reset();
    public boolean validatePage(){
    int page = buttonBar.getCurrentPanel();
    switch(page){
    case 1: return true;
    return true;
    public void prepareNextPage(){
    int nextPage = buttonBar.getCurrentPanel() + 1;
    if (nextPage == buttonBar.getNumberOfPanels()){
    String environmentResult = terminalServicesEnvironmentPanel1.getReport();
    String remoteResult = terminalServicesRemoteControlPanel1.getReport();
    String sessionResult = terminalServicesSessionPanel1.getReport();
    finishList.setText("" + environmentResult + "\n\n" + remoteResult + "\n" + sessionResult);
    finishList.select(1, 1);
    void jButton2_actionPerformed(ActionEvent e) {
    DirectoryChooser chooser = new DirectoryChooser();
    chooser.show();
    if (chooser.isSuccessfulSelect()){
    String text = chooser.getDirectorySelected();
    void jButton3_actionPerformed(ActionEvent e) {
    DirectoryChooser chooser = new DirectoryChooser();
    chooser.show();
    if (chooser.isSuccessfulSelect()){
    String text = chooser.getDirectorySelected();
    * @return the drive letters available to be mapped
    public String[] getAvailableDriveLetters(){
    return availableDriveLetters;
    * Set the drive letters available to be mapped
    * @param letters an array of drive letters in the format [Character]':'
    public void show(){
    String message = Global.getString("WIZARD.TERMINAL.PROVISION.MESSAGE3");
    PTreeNode node = Global.getCurrentNode();
    super.show();
    public boolean provisionApplication(LicConfig app){
    * @todo provision application contained in LicConfig
    return true;
    public boolean deprovisionApplication(LicConfig app){
    * @todo provision application contained in LicConfig
    return true;
    private String getValue(Hashtable h, String key) {
    if (h.containsKey(key))
    return (String)h.get(key);
    return null;
    public void initPanel(Hashtable properties)
    public JComponent getFirstComponent(){
    int page = buttonBar.getCurrentPanel();
    switch(page){
    case 1:
    return terminalServicesEnvironmentPanel1.logonCheckbox;
    case 2:
         return terminalServicesRemoteControlPanel1.enableRemoteCheckBox;
    case 3:
         return terminalServicesSessionPanel1.endComboBox;
    case 4:
         return null;
    return null;
    public JComponent getLastComponent(){
    int page = buttonBar.getCurrentPanel();
    switch(page){
    case 1:
    return buttonBar;
    case 2:
         return buttonBar;
    case 3:
         return buttonBar;
    case 4:
         return null;
    return null;

Maybe you are looking for

  • Kernel Panics on Mac Mini late 2012

    I bought a Mac mini late 2012 this week. Changed the RAM to 2x 4GB. I have restored from a Time Machine Backup of my old Macbook 2006 with 10.6. I got several Kernel Panics during random use. Made the Apple Hardwaretest, it says that everything is ok

  • Playing video from a flash media server

    Can anyone point me to code to play streaming video from a Flash Media Server in Flex?

  • Changed HDD in NAS Drive, lost all links

    Hello world, I keep all photos in separate directory structure (16.000 photos in 140 directories), and have the mediathek on the local drive. Now I have changed the HDDs in my NAS drive (dLink DNS 323, connection via smb), and restored all folders fr

  • Pcd object "com.sap.pct.crm.core.valuehelp" cannot be accessed

    Hi dear gurus, We need your help. We are a company working with CRM 5.0 Sp 15 on EP 7.0. We have this problem: One of the BP's tabs shows the Marketing Attributes in the standard way: first of all you have to decide the attribute set ("Add"), then yo

  • X-Plane 9 Arch 64

    So I got X-Plane 9, but I'd really like to get it to work on my Arch 64 box.  It works fine on my Arch 32 box, but I haven't had any luck with the 64 bit one.  I installed all the 32 bit libraries I needed and got rid of all the error messages I was