Adding JButton to JTextAreas

I'm publishing reports from data onto an uneditable JTextArea (so the user can save it as a text doc if they wish).
I'd like to have a button next to each report so the user can view the data for that report, but presumably this can't be done on a JTextArea?
Anyone have any suggestions as to how I can have a 'View data' button, but still be able to save the text of the report?
Many thanks.

If you are trying to produce a panel that has a JTextArea and a JButton on it, that is relatively easy to do.
You cannot put a JButton into a text area but it is easy enough to put it either next to or below the text area and provide the functionality that you are looking for.

Similar Messages

  • Adding scrollbars in jtextarea

    can any one tell me the method of adding scrollbars in jtextarea such that they are enabled when required means initially disabled but when the text goes long they are enabled.
    farhan

    Add ur JTextArea in a JScrollPane by doing this :
    JScrollPane jsp = new JScrollPane(JScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    //then add ur Jtext hereMaz -

  • Using JCheckBox, JButton and JTextArea with JDBC

    Hello shlumph and SoulTech2012.
    thanks for the reply. I�m wondering do any of you have links to web pages that include tutorials and source code on using JCheckBox, JButton and JTextArea with JDBC. would any of you who have experience with using JCheckBox, JButton, JTextArea and JDBC together be able to give me a few tips on how to select certain data from a table using JCheckBox, JButton and display the data in a JTextArea? examples of such data could be CD/DVD/Game data - i want users of my video library system to be able to view CD/DVD/Game information by name, age category, type and year. Users should be able to click on a check box (e.g. view by name, age category, type or year) and press a button. What would happen then is that data from the Product table would appear in the text area (which could be placed beneath the check box + button inside a frame and/or panel).
    Thank you very much for your help.

    Quit triple posting and cross posting your questions all over the forum. You already have a posting in this forum on this topic and another posting in the Swing forum and another posting in the Programming forum.

  • Adding JButton, JTextField to scroll pane...

    I have developed an appln in which I have added JPanel to JFrame.
    To this JPanel I m adding JButton & JTextField. But the JButton & JTextField are increasing dynamically in my appln[according to DBMS query]. So I wanted to use scrolpane or something like so that the window can be scrolled vertically to view all the components[JButton & JTextField]. I m developing this as a standalone appln.
    Plz help..
    Thanking in advance.

    Thanx fouadk ,
    But my problem still persists. Now though I m able to add JPanel to JScrollPane, but when the components in the JPanel increase than the height of the Pane, the components at the dowm are not visible unless I resize the window by manually dragging the corners. Actually I wanted to keep the size of the window constant and make use of the VERTICAL SCROLLBAR.
    Plz help.
    Thanking in advance.
    Following is code:
    import javax.swing.*;
    public class testt extends JFrame {
    private JPanel p = new JPanel();
    private JScrollPane sp = new JScrollPane(p
    ,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
    ,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    private JButton b[] = new JButton[15];
    public testt() {
    super("TEST");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(500, 400);
    setLocation(50, 20);
    this.add(sp);
    p.setLayout(null);
    sp.setAutoscrolls(true);
    for(int i = 0, y = 10; i < 15; i++, y += 40)
         b[i] = new JButton("BUTTON "+ (i+1));
         b.setBounds(10,y,100,20);
         p.add(b[i]);
    public static void main(String[] args) {
    testt t = new testt();
    t.setVisible(true);

  • Adding JButtons to a Java2d Graphics program

    Hi,
    I apologise to all you seasoned programmers if this seems an easy question, but I can't seem to see the solution to this one.
    I'm trying to add 2 JButtons to an existing Java2D graphics program. When I run the program I get the following error,
    'java.lang.IllegalArgumentException: adding a window to a container'
    I can't seem to see how to correct this error. My current code is as follows,
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class PacMan2Clicks extends JFrame implements ActionListener {
        public static int mode = 0;
        private static JButton rightButton;
        private static JButton leftButton;
        public PacMan2Clicks() {
            Container contentPane = getContentPane();
            JPanel panel = new JPanel();
            leftButton = new JButton("Leftt");
            leftButton.addActionListener(this);
            panel.add(leftButton);
            rightButton = new JButton("Right");
            rightButton.addActionListener(this);
            panel.add(rightButton);
            contentPane.add(panel, BorderLayout.SOUTH);
        public void paintComponent(Graphics g) {
            Dimension d = getSize();
            Graphics2D g2 = (Graphics2D)g;
            int size = 100;
            Ellipse2D.Double head =
                    new Ellipse2D.Double(0, 0, size, size);
            Ellipse2D.Double eye =
                    new Ellipse2D.Double(size/2-1, size/5-1,
                    size/10, size/10);
            GeneralPath mouth = new GeneralPath();
            mouth.moveTo(size, size/4);
            mouth.lineTo(size/8, size/2);
            mouth.lineTo(size, size*3/4);
            mouth.closePath();
            Area pacman = new Area(head);
            pacman.subtract(new Area(eye));
            pacman.subtract(new Area(mouth));
            g2.setPaint(Color.yellow);
            g2.fill(pacman);
            g2.setPaint(Color.black);
            g2.draw(pacman);
        public void actionPerformed(ActionEvent event) {
            if(event.getSource().equals(rightButton)) {
            } else if(event.getSource().equals(leftButton)) {
        public static void main(String[] args) {
            JFrame frame = new JFrame("Drawing stuff");
            frame.add(new PacMan2Clicks());
            frame.setSize(600, 600);
            //frame.setContentPane(new PacMan2Clicks());
            frame.setVisible(true);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
    }Any help appreciated. Thank you.

    Your public class extends JFrame so it is a JFrame. In your main method you create a new JFrame and try to add the enclosing class (a JFrame by extension) to it. So you can either:
    1 &#8212; remove the JFrame extension from the class declaration and leave the code in the main method as&#8212;is:
    public class PM2C implements ActionListener {or,
    2 &#8212; leave the JFrame extension and remove the new JFrame instance in the main method.
    public class PM2C extends JFrame implements ActionListener {
        public PM2C(String title) {
            super(title);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            Container contentPane = getContentPane();
            JPanel panel = new JPanel();
            leftButton = new JButton("Leftt");
            leftButton.addActionListener(this);
            panel.add(leftButton);
            rightButton = new JButton("Right");
            rightButton.addActionListener(this);
            panel.add(rightButton);
            contentPane.add(panel, BorderLayout.SOUTH);
            setSize(600, 600);
            setVisible(true);
        public static void main(String[] args) {
            new PM2C("Drawing stuff");
    }

  • Adding JButton in JList

    Hi
    I wonder if it is possible to add JButton in a JList? Or how can I produce a list of JButtons? Each button represents a person (an object), is there anyway to add listener to the buttons so i can get the person thats represnted by the button? I can decide in advance how many button ther will be...that depends on the number of person in the db.

    Use a panel with a GridLayout. The Panel can be added to a JScrollPane. Read this section on "Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

  • Adding Image to JTextArea

    Hello All,
    I need to add an Image to a JTextArea. Any ideas plz.
    best wishes
    Issac

    But I have read that all Swing Components, which extend from JComponent >can have other components added to them, because the JComponent class >extends from java.awt.Container and thus have a add method. I tried using t>he add method, but it didnt work. So I tried it here.Don't believe everything you read!!!!! JTextArea is meant to be a simple editor and is not meant to handle what you are trying to do.

  • Adding actionlistener to JTextArea

    I'm trying to add an actionListener to my JTextArea, so that when the user hits 'enter', the action occurs.
    sort of like this:
    JTextArea.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ??????) {
    doSomethingToTextArea();
    but I'm having problems (e.g. how to make enter the action event, and some problem that says JTextArea can't use actionlisteners???)
    any ideas?
    thanks,
    n00bProgrammer

    Like serveral of the more complex swing gadgets the JTextarea uses model/view architecture. In this case the model behind the textarea is a Document, and the text change listener needs to be added to the Document, not the gadget itself. i.e. area.getModel().addDocumentListener();
    However JTextArea still inherits the methods of java.awt.Component including addKeyListener();

  • Adding JButtons to JTable

    Hello all,
    How can I add JButtons to a JTable?
    I found an article that is supposed to show you how to do just that:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I downloaded the code in the article and it works to an extent - I can see the buttons in the table but the buttons seem as if they are disabled :( Since I used this code in my application, I get the same behavior too.
    Is there a bug in the code? Is there a simpler solution? What am I missing?
    Raj

    Thanks. That makes the button clickable. But now the button changes back to it's old value when you click on another cell. I suppose that's because we have 2 buttons, one for rendering and one for editing. So I added a setValueAt(Object value, int row, int column) to MyModel. This works throws class cast exception.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class ButtonInTable extends JFrame {
        JTable t=new JTable(new MyModel());
        public ButtonInTable() {
            this.getContentPane().add(new JScrollPane(t));
            this.setBounds(50,50,300,200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            t.setDefaultEditor(Object.class,new ButtonEditor());
            t.setDefaultRenderer(Object.class,new ButtonRenderer());      
        public static void main(String[] args) {
            ButtonInTable buttonInTable1 = new ButtonInTable();
            buttonInTable1.show();
        class ButtonEditor extends JButton implements TableCellEditor {
            Object currentValue;
            Vector listeners=new Vector();
            public ButtonEditor() {
                            this.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    currentValue=JOptionPane.showInputDialog("Input new value!");
                                    if (currentValue!=null) {
                                        setText(currentValue.toString());
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                currentValue=value;
    //            this.setText(value.toString());
                this.setText( ((JButton)value).getText() );
                return this;
            public Object getCellEditorValue() {
                return currentValue;
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingStopped(ce);
                return true;
            public void cancelCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingCanceled(ce);
            public void addCellEditorListener(CellEditorListener l) {
                listeners.add(l);
            public void removeCellEditorListener(CellEditorListener l) {
                listeners.remove(l);
        class ButtonRenderer extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent
                    (JTable table, Object button, boolean isSelected, boolean hasFocus, int row, int column) {
                return (JButton)button;
        class OldModel extends DefaultTableModel {
            public OldModel() {
                super(new String[][]{{"1","2"},{"3","4"}},new String[] {"1","2"});
        class MyModel extends AbstractTableModel {
            private String[] titles = { "A", "B" };
            private Object[][] summaryTable =
                    { new JButton("11"), new JButton("12") },
                    { new JButton("21"), new JButton("22") }
            public MyModel(){
                super();
            public int getColumnCount() {
                return titles.length;
            public String getColumnName(int col) {
                return titles[col];
            public int getRowCount() {
                return summaryTable.length;
            public Object getValueAt(int row, int col) {
                return summaryTable[row][col];
            public void setValueAt(Object value, int row, int column) {
                summaryTable[row][column] = value;
                fireTableCellUpdated(row, column);
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                return true;
    }

  • Adding JButton to JScrollPane

    Hi there,
    Just a quick request to look at this piece of code and see what I might be doing wrong... I'm trying to add a JButton to the bottom left of a JScrollPane using this code...
    private JScrollPane resultsPane;
    private JTextArea resultsArea;
    private JButton saveResultsButton;
    Container container = getContentPane();
    resultsPane = new JScrollPane(resultsArea);
    resultsPane.add(saveResultsButton);
    container.add(topPanel) // this is a JPanel containing 2 other panels...
    container.add(resultsPane, Borderlyout.SOUTH);The problem is that my 'saveResultsButton' is simply not being displayed. Anyone have any idea from this code what my error could be?
    Any help appreciated.

    Hi there,
    Just a quick request to look at this piece of code
    and see what I might be doing wrong... I'm trying to
    add a JButton to the bottom left of a JScrollPane
    using this code...
    private JScrollPane resultsPane;
    private JTextArea resultsArea;
    private JButton saveResultsButton;
    Container container = getContentPane();
    resultsPane = new JScrollPane(resultsArea);
    resultsPane.add(saveResultsButton);The JScrollPane merely adds the up and down scroll bars. You can't really add anything to a scrollbar. You probably don't want to add a JButton to the JTextArea either! Create another JPanel and add(resultsPane) to it then add(saveResultsButton) to it. Then add the JPanel to the container.

  • Adding JButton in a JTable

    hi
    i know this has been discussed quite a number of times before, but i still couldn't figure it out..
    basically i just want to add a button to the 5th column of every row which has data in it.
    this is how i create my table (partially)
         private JTable clientTable;
         private DefaultTableModel clientTableModel;
    private JScrollPane scrollTable;
    clientTableModel = new DefaultTableModel(columnNames,100);
              clientTable = new JTable(clientTableModel);
              TableColumn tblColumn1 = clientTable.getColumn("Request ID");
              tblColumn1.setPreferredWidth(70);
              tblColumn1 = clientTable.getColumn("Given Name");
              tblColumn1.setPreferredWidth(300);
              tblColumn1 = clientTable.getColumn("Address");
              tblColumn1.setPreferredWidth(350);
              tblColumn1 = clientTable.getColumn("Card Serial");
              tblColumn1.setPreferredWidth(100);
              tblColumn1 = clientTable.getColumn("Print Count");
              tblColumn1.setPreferredWidth(70);
              tblColumn1 = clientTable.getColumn("Print?");
              tblColumn1.setPreferredWidth(40);
              clientTableModel.insertRow(0,data);
              //clientTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              scrollTable = new JScrollPane(clientTable);and i call this function void listInfoInTable(){
              JButton cmdPrint[];
              Vector columnNames = new Vector();
              Object[] data={"","","","","",""};
              Statement stmt=null;
              ResultSet rs=null;
              PreparedStatement ps;
              String query=null;
              String retrieve=null;
              int i,j=0;
              TableColumnModel modelCol = clientTable.getColumnModel();
              try{
                   con = DriverManager.getConnection(url);
                   JOptionPane.showMessageDialog(null,"Please wait while the program retrieves data.");
                   query="select seqNo, givenName, address1, address2, address3, address4, cardSerNr, PIN1, PrintFlag from PendPINMail where seqNo<250;";
                 ps = con.prepareStatement(query);
                 rs=ps.executeQuery();
                 while (rs.next()){
                      data[0]= rs.getString("seqNo");
                      data[1]= rs.getString("givenName");
                      data[2]= rs.getString("address1");
                      data[3]= rs.getString("cardSerNr");
                      data[4]= rs.getString("PrintFlag");
    //                  modelCol.getColumn(5).setCellRenderer();
                      clientTableModel.insertRow(j,data);
                      j++;
              }catch (SQLException ex){
                   JOptionPane.showMessageDialog(null,"Database error: " + ex.getMessage());
         } to display data from database inside the table.
    How do I add JButton to the 5th column of each row? This documentation here http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#width says that i need to implement TableCellEditor to put JButton in the table. How do i really do it? I want the button to call another function which prints the data from the row (but this is another story).
    Any help is greatly appreciated. Thanks

    you would need CellRenderer i think that it is in
    javax.swing.table.*;
    see if you can get started with that.
    Davidthanks, i'll try and have a look at it
    Yes, that's definitely what you need to start with,
    but you also need a CellEditor to return the
    button as well, otherwise the button will not be
    clickable (the renderer just paints the cell for
    display, it doesn't allow you to interact with it).
    You could maintain a list of components for rendering
    each cell of the table so that your
    CellRenderer and CellEditor always
    return the same object (i.e. a JButton for any
    given cell).
    CB.thanks for the info.. could you point me to some examples? is sounds quite complicated for me....
    thanks again

  • Adding JButton in BorderLayout

    Hi everyone,
    I have a question about Panel. I want to know how can we add 2 button at the bottom of panel2 and then add panel2 into panel1. here is what I did.
         // 2 buttons for panel2
         JButton b1 = new JButton ("Start");
         b1.addActionListener(this);
         JButton b2= new JButton("Stop");
         b2.addActionListener(this);
         panel2.add(b1);
         panel2.add(b2);
         //now add panel2 to panel1
         panel1.add(panel2, Borderlayout.SOUTH);
         getContentPane().add(panel1, Borderlayout.CENTER);
    but this code is not compiling.
    it gives me these error. where can i be wrong?
    test.java:33: cannot resolve symbol
    symbol : class add
    location: package panel2
    panel2.add(b1);
    ^
    test.java:34: cannot resolve symbol
    symbol : class add
    location: package panel2
    panel2.add(b2);
    ^
    test.java:38: cannot resolve symbol
    symbol : class add
    location: package panel1
    panel1.add(panel2, Borderlayout.SOUTH);
    Thanks

    This may help u
    import javax.swing.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Test1 extends JFrame implements ActionListener
         JPanel panel1,panel2;
         public void init()
    JButton b1 = new JButton ("Start");
    b1.addActionListener(this);
    JButton b2= new JButton("Stop");
    b2.addActionListener(this);
    panel2.add(b1);
    panel2.add(b2);
    //now add panel2 to panel1
    panel1.setLayout(new BorderLayout());
    panel1.add(panel2, BorderLayout.SOUTH);
    this.getContentPane().add(panel1, BorderLayout.CENTER);
    public void actionPerformed(ActionEvent e)

  • Adding JButton into JTable cells

    Hi there!!
    I want to add a JButton into JTable cells.In fact I have got two classes.Class2 has been extended from the AbstractTableModel class and Class1 which is using Class2's model,,,here's the code,,
    Class1
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Class1 extends javax.swing.JFrame {
       //////GUI specifications
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestTableButton().setVisible(true);
            Class2 model=new Class2();
            jTable1=new JTable(model);
            jScrollPane1.setViewportView(jTable1);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration                  
        private javax.swing.JTable jTable1;
    }Class2
    import javax.swing.table.*;
    public class Class2 extends AbstractTableModel{
        private String[] columnNames = {"A","B","C"};
        private Object[][] data = {
        public int getColumnCount() {
            return columnNames.length;
        public int getRowCount() {
            return data.length;
        public String getColumnName(int col) {
            return columnNames[col];
        public Object getValueAt(int row, int col) {
            return data[row][col];
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         * Don't need to implement this method unless your table's
         * editable.
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
                return false;
         * Don't need to implement this method unless your table's
         * data can change.
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
    }what modifications shud I be making to the Class2 calss to add buttons to it?
    Can anybody help plz,,,,,??
    Thanks in advance..

    Hi rebol!
    I did search out a lot for this but I found my problem was a bit different,,in fact I want to use another class's model into a class being extended by JFrame,,so was a bit confused,,,hope you can give me some ideas about how to handle that scenario,,I know this topic has been discussed before here many a times and also have visited this link,,
    http://forum.java.sun.com/thread.jspa?threadID=465286&messageID=2147913
    but am not able to map it to my need,,,hope you can help me a bit...
    Thanks .....

  • Adding JButton onto a Rectangle

    Hi All,
    Is there any way to add a JButton onto the Rectangle..???
    I have drawed a rectangle by using Graphics class and i need a button to be embedded onto that.
    Thanks in advance.
    regards,
    Viswanadh

    A Rectangle is not a Component so no you can't "add" it to a Rectangle.
    Is the Rectangle the same size as the button so only one button fits in the rectangle. Or do you have multiple buttons in the Rectangle.
    In the first case you could just add a Border to the button. In the second case you add a Border to a JPanel and then add the buttons to the panel.
    I suggestion you start by reading the [Swing tutorial|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]. Maybe the section on Layout Managers so you learn how to control the positioning of Components in a Container.

  • Adding JButton

    I'm trying to add a JButton to my JApplet using the following code, I can't seem to figure out what's wrong.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Driver extends JApplet implements ActionListener
    JButton easy;
    public void init()
      easy = new JButton("Easy");
      getContentPane().add(easy);
      easy.setBounds(0,0,0,0);
    public void start()
    public void stop()
    public void paint(Graphics g)
    public void destroy()
    // For the ActionListener interface.
    public void actionPerformed(ActionEvent event)
    }

    You can use those codes below:
    import java.awt.*;
    import javax.swing.*;
    public class SwingWindow extends JApplet
         public SwingWindow()
         Container contentArea=getContentPane();
         FlowLayout flowManager=new FlowLayout();
         contentArea.setLayout(flowManager);
         JButton playButton=new JButton("Play");
         JButton stopButton=new JButton("Stop");
         contentArea.add(stopButton);
         contentArea.add(playButton);
         setContentPane(contentArea);
    }

Maybe you are looking for