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);
}

Similar Messages

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

  • Fishy: NullPointerException upon adding JButton to JTextField

    Hi all,
    Does anyone know why this code is throwing a NullPointerException?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicArrowButton;
    import javax.swing.plaf.metal.MetalScrollButton;
    public class fishy extends JTextField {
        JButton chooseBut;
        public fishy() {
         chooseBut = new MetalScrollButton(SwingConstants.SOUTH, 15, false);
         Dimension s = getPreferredSize();
         chooseBut.setMaximumSize(new Dimension(30, s.height));
         setLayout(new BorderLayout());
         add(chooseBut, BorderLayout.EAST);
         setMaximumSize(new Dimension(800,28));
        public void setEditable(boolean b) {
         chooseBut.setEnabled(b);
         super.setEditable(b);
        public static void main(String[] args) {
         try {
             UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
             JFrame fr = new JFrame("fishy");
             fishy f = new fishy();
             fr.getContentPane().add(f);
             f.setEditable(true);
             fr.pack();
             fr.setVisible(true);
         } catch (Exception e) {
             e.printStackTrace();
    }Thanks.

    I guess that the constructor of JTextField is calling setEditable() before your class is fully constructed.
    Workaround: change your setEditable() method to
    public void setEditable(boolean b) {
                                       if(chooseBut != null) {
         chooseBut.setEnabled(b);
    super.setEditable(b);
    regards

  • Adding Dynamic JButtons & JLabels on the JTool

    On occerance of certain ActionEvent i need to add dynamic JButtons & JLabels on the JToolBar. Initially JToolBar will be empty.
    Code below is not working properly...
    It is creating buttons dynamiclly but i cant set any property for that one.
    class DeviceAction extends AbstractAction
         public DeviceAction()
         // Add this action to the toolbar resulting
         // in a new button getting added to the
         // toolbar
         JButton jbutton = xmlFilesToolBar.add( this);
         xmlFilesToolBar.addSeparator();
         jbutton.setActionCommand( "Dynamic" );
    I will call " new DeviceAction(); " when ever ActionEvent occurs.
    I need to have controle over the dynamically added JButtons & JLables, bcoz each JButtons shld do some Actions when it is clicked.
    Plz do the needful.
    Reg,
    Bha.

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=725394&tstart=0

  • Custom JButton for JPopupMenu

    I need to make a custom PopupMenu Button . This button needs to be added to the custom JPopupmenu . This custom button must have the look and feel of a typical menu item. Basically it should have a typical features of a checkboxmenuitem where I have an check.jpg for check and uncheck of the button. How do I reproduce the look and feel of a menuitem. What changes do i make in the below code. Basically no border, button press should not be there. It should not look like we are adding JButtons to the user
    import javax.swing.Action;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.border.EmptyBorder;
    public class XCheckedButton
            extends JButton {
        private boolean flag;
        private ImageIcon checkedIcon;
        public XCheckedButton() {
            super();
        public XCheckedButton(Action a) {
            this();
            setAction(a);
        public XCheckedButton(Icon icon) {
            super(icon);
        public XCheckedButton(String text, Icon icon) {
            super(text, icon);
        public XCheckedButton(String text) {
            super(text);
         public ImageIcon getCheckedIcon() {
              return checkedIcon;
         public void setCheckedIcon(boolean state) {
              this.checkedIcon = checkedIcon;
    }

    Thanks a lot. Here are my 2 java files and right below is the probelm I am facing when USing JMenuItems. Thats the reason why i switched over to JButtons.
    JframePopupMenu.java
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class JFramePopupMenu extends JFrame  {
         private static final long serialVersionUID = 1;
         private JPanel jContentPane = null;
         private JButton jbnPopup = null;
         private JTextField jtfNumOfMenus = null;
         private JLabel lblNumElem = null;
         JTextArea output;
        JScrollPane scrollPane;
        String newline = "\n";
        ScrollablePopupMenu scrollablePopupMenu = new ScrollablePopupMenu(JFramePopupMenu.this.getGraphicsConfiguration());
         private JButton getBtnPopup() {
              if (jbnPopup == null) {
                   jbnPopup = new JButton();
                   jbnPopup.setText("View Popup");
                   jbnPopup.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             int n = Integer.parseInt(getTxtNumElem().getText());
                             JCheckBoxMenuItem cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
                             cbMenuItem.addActionListener(new ActionListener(){
                                  public void actionPerformed(ActionEvent e) {
                                       System.out.println( e );
                                       scrollablePopupMenu.hidemenu();
                           cbMenuItem.setMnemonic(KeyEvent.VK_C);
                           scrollablePopupMenu.add(cbMenuItem);
                             for (int i=0;i<n;i++){
                                  JMenuItem xx = new JMenuItem(" JMenuItem  " + (i+1));
                                       xx.addActionListener(new ActionListener(){
                                       public void actionPerformed(ActionEvent e) {
                                            System.out.println( e );
                                            scrollablePopupMenu.hidemenu();
                             //     scrollablePopupMenu.add(new JButton(" JMenuItem  " + (i+1)));
                                  scrollablePopupMenu.add(xx);
                             scrollablePopupMenu.show(jbnPopup, jbnPopup.getWidth()*3, 0);
              return jbnPopup;
         private JTextField getTxtNumElem() {
              if (jtfNumOfMenus == null) {
                   jtfNumOfMenus = new JTextField();
                   jtfNumOfMenus.setColumns(3);
                   jtfNumOfMenus.setText("60");
              return jtfNumOfMenus;
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        JFramePopupMenu thisClass = new JFramePopupMenu();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
         public JFramePopupMenu() {
              super();
              initialize();
         private void initialize() {
              this.setSize(274, 109);
              this.setContentPane(getJContentPane());
              this.setTitle("Scrollable JPopupMenu");
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   lblNumElem = new JLabel();
    //               lblNumElem.setText("N�mero de elementos del Men�");
                   FlowLayout flowLayout = new FlowLayout();
                   flowLayout.setHgap(8);
                   flowLayout.setVgap(8);
                   jContentPane = new JPanel();
                   jContentPane.setLayout(flowLayout);
                   jContentPane.add(getBtnPopup(), null);
                   jContentPane.add(lblNumElem, null);
                   jContentPane.add(getTxtNumElem(), null);
              return jContentPane;
    ScrollablePopupMenu.java
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsConfiguration;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JSeparator;
    public class ScrollablePopupMenu extends JPopupMenu {
         private static final long serialVersionUID = 1;
         private JPanel panelMenus = null;
         private JScrollPane scroll = null;
         public ScrollablePopupMenu(GraphicsConfiguration gc) {
              super();
              scroll = new JScrollPane();
              panelMenus = new JPanel();
              panelMenus.setLayout(new GridLayout(0,1));
              scroll.setViewportView(panelMenus);
              scroll.setBorder(null);
              scroll.setMaximumSize(new Dimension(scroll.getMaximumSize().width,
                        this.getToolkit().getScreenSize().height -
                        this.getToolkit().getScreenInsets(gc).top -
                        this.getToolkit().getScreenInsets(gc).bottom - 4));
              super.add(scroll);
         public void show(Component invoker, int x, int y) {
              this.pack();
              panelMenus.validate();
              int maxsize = scroll.getMaximumSize().height;
              int realsize = panelMenus.getPreferredSize().height;
              int sizescroll = 0;
              if (maxsize < realsize) {
                   sizescroll = scroll.getVerticalScrollBar().getPreferredSize().width;
              scroll.setPreferredSize(new Dimension(
                        scroll.getPreferredSize().width + sizescroll,
                        scroll.getPreferredSize().height));
              this.setLocation( x, y);
              this.setVisible(true);
         public void hidemenu(){
              if(this.isVisible()){
                   this.setVisible(false);
         public JMenuItem add(JMenuItem menuItem) {
              panelMenus.add(menuItem);
              return menuItem;
         public void addSeparator() {
              panelMenus.add(new JSeparator());
    Problem 1: Not able to Scroll down when frame is Large
    My application is a large frame and when I invoke the JPopupMenu on it I am not able to scroll.
    In the example application also I found the same problem when I maximize the frame. I am able to see the JPopupMenu but not able to scroll on it.

  • Circle JButton

    Hi everybody,
    I'm doing a constraints solver program for my studies and I have made a graphical interface but I want to make it more funny by adding JButton but not rectangular .
    If somebody have an idea to help me...
    Thanks

    This question has been asked before. Learn how to search the forum.
    http://forum.java.sun.com/thread.jsp?forum=31&thread=227950

Maybe you are looking for

  • List of iOS 6 bugs for iPhone 4s

    Ever since I updated my iPhone 4s to iOS 6, there have been some unfixed bugs and some new ones. Where do we direct these bugs to? Is it to this forum? I just want to reach out to Apple so that these bugs can be looked at and be fixed. Lets all share

  • Inaccessible parts of image size dialog

    We have PS CS3 10.0.1 on two machines here.  Twice now when the person at the other machine has tried to change the image size of an image she is working on, the image size dialog has come up with the pixel dimensions read only and the size and resol

  • Periodically doing "stuff", how do I...

    I am working on a senior design program at NCSU and need some help. I am writing a program that will periodically retrieve data from several different counters attached to motion sensors and then update a database with these counts on an hourly basis

  • Service Order

    what is difference between service order with contract (SM01) and Service order with Revenue (SM02) Please reply in your own simple language its easy to understand thanx

  • Sales order to Billing status is completed, we can add  more SKU

    Hi Friends,    Even then one ful cycle of sales order to billing is completed and accouting is also cleared. Still we can add one more SKU in sales order through T Code - VA02. and process one more delivery and billing to accouting.   My question is.