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.

Similar Messages

  • Adding text to a rectangle

    hi, i am making a hierachical tree . i think the best way to do this is via rectangles and lines using java 2d. i was just wondering if there was any way of adding text to a rectangle apart from the drawstring method from the 2d api. or does anyone know of any other way to do this? the tree needs to be interactive so i cant use jlabels and jbuttons are quite ugly
    thanks for any help

    yeah, thanks, it did help. it's just i'm new to layout algorithms and there was a couple of things i wasn't too sure on.
    i have used defaultmutabletreenodes instead of creating my own class as you did but i don't think that matters too much. i wasn't too sure about how you worked out the spacing for each node. i have done a breadth first traversal through all the nodes so i would know how many nodes are on each level and could work out the spacing needed for each level based on this i.e. look at the next level and place the current level in proportion. did you do something similar in the treelayout class?
    would this approach work even if the amount of nodes is large, could the container containing the tree be in a scrollpane?
    the problem i found with drawstring is that you need to provide coordinates for where to draw the text instead of just adding it to the rectangle (like you could in a jlabel) so it could look untidy. could you make a jlabel interactive or add text to a rectangle?
    sorry my reply is so long but any help would be much appreciated

  • 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 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 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.

  • 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

  • Win Server 2012 Failover Cluster - Error when adding disk onto a cluster (The error code was '0x1' ('Incorrect function.').)

    Hi Techies
    I'm currently running running 2 VMs Win Server 2012 and would like to test Failover Clustering for one of our FTP server
    I've added on both servers an additional partition, formatted and Online, but cannot bring the disk online from the cluster manager
    Assistance would be greatly appreciated
    Thank you
    Jabu

    You posted this in the Exchange Forum, your best bet for an answer would be to post this in the Windows Server Forum.
    https://social.technet.microsoft.com/Forums/en-US/home?forum=winserverClustering
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread

  • Adding rows onto a new page in a table

    Hi,
    I have created a form that had the last page as a subform with a table on it, flowed western so that the cells expand with content./ Also added a add new row button to it (as per the scripting given in the Livecycle help), all of which was working fine. I then moved the subform with the table to the middle of my document instead of the last page and now when I add rows, it doesn't create a new page when it reaches the end, but just continues down off the end of the existing page. The following pages are just information set it their own sub forms.. do I need to change the subform pagination or hte scripting or the table settings to make it add an extra page and keep adding rows in the middle of the form?
    Many thanks for any assistance
    Jackie

    No the issue is with the page subform ...it must be flowed as well .....make sure you wrap all of the other content in Positioned subforms or it will be flowed also.
    Paul

  • How do i get my recently added folder onto my iPhone?

    my recently added folder and most listened to folders wont show up on my iPhone, why?

    Hey man!
    Basically those playlists were just 'Smart Playlists' created by iTunes.
    To re-create them, click File > New Smartlist. Then select 'Date Added', 'in the last', '2' and 'weeks. Live updating should be checked!
    Then name the playlist 'Recently Added'
    Hope it helps!

  • 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 macs onto a window network for schools

    Hello
    Im David and i work in a school in ICT support. at the moment with have an entire windows network. the art, media and music department are planing on getting Imacs. The ICT team and I are wondering how to get macs on the network to have users logon to just like an XP machine so they can get to home directories and use networked printers and have the applied security from active directory and ranger and so on. We are also planning on getting a Xserve to run a new domain for macs and act as the go between to the windows domain.
    Is this an option?
    Can anyone please help us and give us any ideas or point me onto the right path?
    Thanks
    David

    David
    http://www.edugeek.net/forums/mac/
    http://www.howtomac.co.uk/
    http://www.wazmac.com/serversnetwork/networks/windows_macintegration.htm
    http://www.afp548.com/search.php?query=AD-OD&type=all&mode=search
    http://macwindows.com/
    Are just a few. Googling 'AD-OD Integration' should get you more?
    Tony

  • Adding Paypal onto your site?

    Hi,
    I'm just learning iWeb and am working on creating a website for my soap and beauty products. When I'm done I will be publishing to my own domain name and I do not have a Mac account. Is it possible to add paypal onto my site? If so does anyone know how you go about doing this or the basics?
    Thanks,
    S.

    Varkgirl,
    Your website is so colourful and fun, I love it. Did you make that using iWeb? Thanks for the link. Between both these answers I'm sure I'll find out how to export my pages (I know I have to use an FTP server like Cyberduck) to an site other than .Mac and how to place pictures in properly. I'm having problems with that already. They don't seem to fit in the template boxes right and I've tried dragging in and out on both picture and the frame itself.
    S.

Maybe you are looking for