Results 1 to 8 of 8
  1. #1
    Murdok@i is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Unhappy Copy text in auto created TextField

    Hello.
    I'm receiving data and generate tabs in jTabbedPane. This tabs contains jTextFields with data and my aim is to be able to copy this data after selecting it with mouse.
    Earlier I had only one tab with this code:
    Java Code:
    public void setClipboardContents(final String aString) {
    			final StringSelection stringSelection = new StringSelection(aString);
    			final Clipboard clipboard = Toolkit.getDefaultToolkit()
    					.getSystemClipboard();
    			clipboard.setContents(stringSelection, stringSelection);
    		}
    
    jTextPane04.addMouseListener(new java.awt.event.MouseAdapter() {
    			public void mouseReleased(final java.awt.event.MouseEvent evt) {
    				clip.setClipboardContents(jTextPane04.getSelectedText());
    			}
    		});
    But now it isn't working(it's copying data from the last created tab), I understand why, but can't figure out how to write working code.

    Maybe it is possible to write some MouseListener for all application that will get selectedText from Component that isSelected after MouseReleased?

    I'm braking my brains for three days now. Help me if you can or just show me the way... I have no ideas left but I need this to be done some way. :(

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Murdok@i is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default

    I need to copy selected text(from jTextField) to clipboard. And don't know how to do it because jTextField which contain this text is generated after compiling.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Murdok@i View Post
    I need to copy selected text(from jTextField) to clipboard. And don't know how to do it because jTextField which contain this text is generated after compiling.
    You need a reference to the JTextField, pure and simple.

    If you're creating JTabbedPanes I imagine you're creating JPanels and filling them with components. Why not give the class that holds the JTabbedPane or JPanel (whichever is the main class that creates all the components) getter methods to allow you to get the text from any and all JTextFields contained? For more details on exactly how this can be done, we'd need to see more of your code -- preferablly an SSCCE
    Last edited by Fubarable; 04-24-2011 at 03:15 PM.

  5. #5
    Murdok@i is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default

    I've tried to do like you sad. Hope that I've done it right.
    I know that I need reference to jTextField1, but it's creating after compilation so I don't know the name of component that I need to do reference to. :(
    If it's done like the way it's done below - text is copying only from the last tab.
    Java Code:
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.ClipboardOwner;
    import java.awt.datatransfer.StringSelection;
    import java.awt.datatransfer.Transferable;
    import java.io.ByteArrayOutputStream;
    import java.io.DataInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import javax.swing.JOptionPane;
    
    public class NewJFrame extends javax.swing.JFrame {
    	
    	public final class TextTransfer implements ClipboardOwner { // class to put string in to clipboard
    
    		public void setClipboardContents(final String aString) {
    			final StringSelection stringSelection = new StringSelection(aString);
    			final Clipboard clipboard = Toolkit.getDefaultToolkit()
    					.getSystemClipboard();
    			clipboard.setContents(stringSelection, stringSelection);
    		}
    
    		public void lostOwnership(final Clipboard clipboard,
    				final Transferable contents) {
    			throw new UnsupportedOperationException("Not supported yet.");
    		}
    	}
    	
    	public void createTab(String insert, int a, int i) { //creating tab
            jPanel1 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JTextField();
                  
            jTextField1.setText("jTextField1");  // My trouble is situated here! 
            jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
    			public void mouseReleased(final java.awt.event.MouseEvent evt) {
    				clip.setClipboardContents(jTextField1.getSelectedText());
    			}
    		});
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(279, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(163, Short.MAX_VALUE))
            );
    
            jTabbedPane1.addTab("tab1", jPanel1);
    	}
    
    	public void subst(final String sr) { //parsing string
    		int b = 38;
    		int a = 41;
    		int o = 1;
    		while (sr.length() >= 41 + b) {
    			createTab(sr, a, o);
    			b += 38;
    			a += 38;
    			o++;
    		}
    	}
    	
    	private void grpstr() throws IOException { //getting string
    		String temprez = "";
    		int i = 0;
    		final Socket clientSocket = new Socket("someip", port);
    		
    		final DataInputStream inFromServer = new DataInputStream(
    				clientSocket.getInputStream());
    		if (clientSocket.isConnected()) {
    			final byte[] buffer = new byte[1000];
    			final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    			lable1: while (true) {
    				i = inFromServer.read(buffer);
    				if (i > 0) {
    					temprez += new String(buffer, 0, i, "cp1251");
    				}
    				for (int ti = 0; buffer[ti] != 35;) {
    					break lable1;
    				}
    
    			}
    				subst(temprez);
    			
    
    			baos.flush();
    			baos.close();
    		}
    		inFromServer.close();
    		clientSocket.close();
    	}
    
    	
    	
    	
        public NewJFrame() {
            initComponents();
        }
    
        @SuppressWarnings("unchecked")
        private void initComponents() {
    
            jButton1 = new javax.swing.JButton();
            jTabbedPane1 = new javax.swing.JTabbedPane();
    
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jButton1.setText("jButton1");
    		jButton1.addActionListener(new java.awt.event.ActionListener() {
    			public void actionPerformed(final java.awt.event.ActionEvent evt) {
    				jButton1ActionPerformed(evt);
    			}
    		});
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
                    .addContainerGap())
            );
    
            pack();
        }
        
    	private void jButton1ActionPerformed(final java.awt.event.ActionEvent evt) {
    		try {
    			grpstr();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
        
        
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify
    	TextTransfer clip = new TextTransfer();
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JTabbedPane jTabbedPane1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    
    }
    P.S.: Sorry for my English, I'm trying to do my best. I need your help very much.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    As I thought, you can probably solve your problem by adding a FocusListener to your newly created JTextField, then on focusGained(...) get the text field's text and add it to the clipboard:


    e.g.,
    PHP Code:
          final JTextField textField = new JTextField("text field " + tabCount, 20);
          
          textField.addFocusListener(new FocusAdapter() {
             @Override // when the text field gains focus by mouse click or tab press
             public void focusGained(FocusEvent fe) {
                // get handle to textfield via FocusEvent's getSource method.
                String text = ((JTextField)fe.getSource()).getText();
                StringSelection strSelection = new StringSelection(text);
                clipboard.setContents(strSelection, null); // put its contents into clipboard
             }
          });

    Here's my SSCCE to demonstrate it (yours wasn't an SSCCE since the database requirement prevented all from being able to run your code):

    PHP Code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class NewJFrame2 extends JPanel {
       private static final int TAB_PANE_WIDTH = 400;
       private static final int TAB_PANE_HEIGHT = 250;
       private JButton addTabbedPaneBtn = new JButton("Add Tabbed Pane");
       private JTabbedPane tabbedPane = new JTabbedPane();
       private int tabCount = 0;
    
       private Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
       
       public NewJFrame2() {
          addTabbedPaneBtn.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                addTabbedPaneActionPerformed();
             }
          });
          JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
          northPanel.add(addTabbedPaneBtn);
          
          tabbedPane.setPreferredSize(new Dimension(TAB_PANE_WIDTH, TAB_PANE_HEIGHT));
          
          setLayout(new BorderLayout(10, 10));
          int eb = 8;
          setBorder(BorderFactory.createEmptyBorder(eb , eb, eb, eb));
          add(northPanel, BorderLayout.NORTH);
          add(tabbedPane, BorderLayout.CENTER);
       }
    
       private void addTabbedPaneActionPerformed() {
          JPanel panel = new JPanel();
          final JTextField textField = new JTextField("text field " + tabCount, 20);
          
          textField.addFocusListener(new FocusAdapter() {
             @Override // when the text field gains focus by mouse click or tab press
             public void focusGained(FocusEvent fe) {
                // get handle to textfield via FocusEvent's getSource method.
                String text = ((JTextField)fe.getSource()).getText();
                StringSelection strSelection = new StringSelection(text);
                clipboard.setContents(strSelection, null); // put its contents into clipboard
             }
          });
          
          panel.add(textField);
          tabbedPane.addTab("Tab " + tabCount, panel);      
          tabCount++;
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("NewJFrame2");
          frame.getContentPane().add(new NewJFrame2());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    Last edited by Fubarable; 04-24-2011 at 05:53 PM.

  7. #7
    Murdok@i is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default

    "yours wasn't an SSCCE" - I'm terribly sorry about that.
    Thank you very very much! Your code is working just like I need. You are genius!

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Replies: 3
    Last Post: 11-16-2010, 08:43 AM
  2. Replies: 7
    Last Post: 08-17-2010, 06:00 PM
  3. Replies: 2
    Last Post: 06-14-2010, 10:18 AM
  4. accessing the text of textfield of one class in another
    By vasavi.singh in forum Advanced Java
    Replies: 3
    Last Post: 04-05-2009, 02:54 PM
  5. Replies: 1
    Last Post: 08-07-2007, 05:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •