How to display a JPanel of JButtons on ImagePanel?

Hi
From the Swing Hacks examples, I can display a JButton on an ImagePanel no problem. But when I put this JButton in JPanel, then add the JPanel to the ImagePanel, the JPanel with the JButton is not displayed.
Can someone please explain why this is?
Here is the ImagePanel code:
import java.awt.*;
import javax.swing.*;
public class ImagePanel extends JPanel {
    private Image img;
    public ImagePanel(String img) {
        this(new ImageIcon(img).getImage());
    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null),img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    public void paintComponent(Graphics g) {
        g.drawImage(img,0,0,null);
}And here is the code to add a JButton to a JPanel, then add the JPanel to the ImagePanel:
import javax.swing.*;
import java.awt.event.*;
public class ImageTest {
    public static void main(String[] args) {
       ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
       JPanel buttonPanel = new JPanel()       
        JButton button = new JButton("Button");
        buttonPanel.add(button);
       JFrame frame = new JFrame("Hack #XX: Image Components");
        frame.getContentPane().add(button);    // WORKS!
        //frame.getContentPane().add(buttonPanel);   // NO BUTTON IS DISPLAYED???
       frame.pack();
        frame.setVisible(true);
}Thanks

setLayout(null);When you use a null layout then you are responsible for setting the size and location of any component added to the panel. The default location is (0,0) so thats ok, but the default size of the button panel is also (0,0) which is why nothing get painted.
Don't use a null layout. Let the layout manager layout any component added to it.
Also, I would override the getPreferredSize() method of your ImagePanel to return the size of the image, instead of setting the preferred size in the constructor.

Similar Messages

  • Can a JList display a JPanel with JButtons, JTextField, etc....  ?

    I've created a JPanel widget component that I hope could display on a line in a JList. The widget contains a JTextField, a JButton, a JCheckBox, etc...
    I'd like to insert these JPanel widgets into a JList, and have the JList box render them.
    The Widget does implement ListCellRenderer
    public class VOWidget2 extends javax.swing.JPanel implements ListCellRendereras the following
        public Component getListCellRendererComponent(JList list,
                                Object value, int index,
                                boolean isSelected, boolean cellHasFocus)
            return (JPanel)this;
        }I also set it in the JList as a DefaultListModel
    DefaultListModel model = new DefaultListModel();
    for(VideoOut curr: voList){
         VOWidget2 vow = new VOWidget2(curr,isHost);
         model.addElement(vow);
    jListVideoOutWidgets.setModel(model);I had hoped to see the JPanel rendered properly inside the JList, but instead it does a toString() on the Object and displays the text from that.
    Here is my question. Can you display a JPanel based widget inside a JList? Or should I just use a JTable instead.
    All the examples I find on the Internet only show example of JList rendering a JLable with an icon and text. Why? Why would the ListCellRenderer return a Component if the most complex thing it could display was a JLabel?

    Can you display a JPanel based widget inside a JList?Yes.
    but instead it does a toString() Implementing ListCellRenderer on your widget panel does not make it the renderer for the JList. You need to create a custom renderer that simply returns the "value" from the getListCellRendererComponent(...) method. Then you need to set this as the renderer for the JList.
    But as everyone else has mentioned you won't be able to edit any of the component or interact with them in any way. Attempting to do so would basically mean duplicating the code thats already available in JTable, which is why everybody is suggesting you just use a JTable.

  • How to display the context of a Jbutton to a JTextField

    Hi,
    There is a key pad (1-9) on a GUI where each key is represented by a JButton. There is also a data entry filed, implemented using JTextField.
    However, when the user enters the ID using the key pad buttons each number should be displayed in the data entry field correspondingly (similar to calculator). I have already written the handlers for each button just don't know how to display the contexts in the text field, e.g. if the button 1 is pressed the 1 should be appeared in the text filed immediately. Anyone can help me to get this done?
    Thanks in advance,
    RMP

    Reza_mp wrote:
    .. Anyone can help me to get this done?In the actioPerformed method, call textField.setText( textField.getText() + "new data" )

  • How to display rectangles with the following code in a JPanel?

    I am trying to make a bunch of random rectangles appear inside a JPanel on a GUI form. Im not sire how to display the form and panel with random rectangles. I have in my package the MyRectangle class, a blank JForm class called RectGUI and the class for the panel RectGUIPanel. The following code is from my panel and it should create random rectangles okay but how do I display them inside of a Panel on my RectGUI form? Thanks for the assistance.
    //Declare variables
        private int x;
        private int y;
        private int width;
        private int height;
        private Color color;
        Random rand = new Random();
        public class RectanglePanel extends JPanel
            public void displayRectangles()
                // Declare an arraylist of MyRectangles
                ArrayList<MyRectangle> myArray = new ArrayList<MyRectangle>();
                int maxNumber = 300;
               // Declare Frame and Panel
                JFrame frame = new JFrame();
                Container pane = frame.getContentPane();
                RectanglePanel rect = new RectanglePanel();
                // Set Frame attributes
                frame.setSize(700, 500);
                frame.setLocation(100,100);
                frame.setAlwaysOnTop(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setTitle(" Rectangle Program");
                frame.setVisible(true);
                for (int i = 0; i < maxNumber; i++)
                    MyRectangle rec = createRandomRec();
                    myArray.add(rec);
                    rect.repaint();
            public MyRectangle createRandomRec()  
                   x = rand.nextInt();
                   y = rand.nextInt();
                   width = rand.nextInt();
                   height = rand.nextInt();
                   color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
                   return new MyRectangle(x, y , width, height, color);
        }

    I am trying to make a bunch of random rectangles appear inside a JPanel on a GUI form. Im not sire how to display the form and panel with random rectangles. I have in my package the MyRectangle class, a blank JForm class called RectGUI and the class for the panel RectGUIPanel. The following code is from my panel and it should create random rectangles okay but how do I display them inside of a Panel on my RectGUI form? Thanks for the assistance.
    //Declare variables
        private int x;
        private int y;
        private int width;
        private int height;
        private Color color;
        Random rand = new Random();
        public class RectanglePanel extends JPanel
            public void displayRectangles()
                // Declare an arraylist of MyRectangles
                ArrayList<MyRectangle> myArray = new ArrayList<MyRectangle>();
                int maxNumber = 300;
               // Declare Frame and Panel
                JFrame frame = new JFrame();
                Container pane = frame.getContentPane();
                RectanglePanel rect = new RectanglePanel();
                // Set Frame attributes
                frame.setSize(700, 500);
                frame.setLocation(100,100);
                frame.setAlwaysOnTop(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setTitle(" Rectangle Program");
                frame.setVisible(true);
                for (int i = 0; i < maxNumber; i++)
                    MyRectangle rec = createRandomRec();
                    myArray.add(rec);
                    rect.repaint();
            public MyRectangle createRandomRec()  
                   x = rand.nextInt();
                   y = rand.nextInt();
                   width = rand.nextInt();
                   height = rand.nextInt();
                   color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
                   return new MyRectangle(x, y , width, height, color);
        }

  • Confused about how to display a rectangle on JFrame

    i'm a little confused about how to display a rectangle on a jframe.
    I know there is a class called Rectangle. is there a way to use it to display a rectangle on a JFrame? i couldn't find a way to do that.
    i found a way to display a rectangle in the internet:
    CODE:
    public class RectangleFrame extends JFrame {
        public RectangleFrame() {
            super("My Rectangle");
            setSize(300,400);
            setLocation(300,300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JButton button = new JButton("Button");
            JPanel panel = new JPanel();
            panel.add(button);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new Rect(), BorderLayout.CENTER);
            getContentPane().add(panel, BorderLayout.SOUTH);       
            setVisible(true);
        public static void main(String[] args) {
            new RectangleFrame();
    public class Rect extends JComponent {
        public void paint(Graphics g) {
            g.drawRect(50,50,200,200);
    }is this the only way to do that? isn't there an easier way? do i have to write this new class Rect i wrote?
    i don't really know how this Rect class i wrote works. could someone explain?
    then another question: can i put a rectangle on a JPanel or do i have to add it directly onto the ContentPane as i did above?
    i hope everything i asked is clear enough.
    thanks for your effort.

    Take a look at the 2D graphics tutorial:
    http://java.sun.com/docs/books/tutorial/2d/index.html

  • How to make a JPanel selectable

    When extending a JPanel and overriding the paintComponent() method the custom JPanel can not be selected so that it gets for example KeyEvents.
    But if I make the new Class extend a JButton it gets of course selected and able to receive for example KeyEvents.
    My question is therefore; what does the JButton implement that a JPanel doesn&#8217;t so that a JButton gets selectable? Or in other words; how to make a JPanel selectable?
    Aleksander.

    Try this extended code. Only the first panel added can get the Focus.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test extends JFrame
      public Test()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        ImagePanel imgPanel = new ImagePanel();
        panel1.setFocusable(true);
        panel2.setFocusable(true);
        panel1.setPreferredSize(new Dimension(0, 50));
        panel2.setPreferredSize(new Dimension(0, 50));
        panel1.setBorder(BorderFactory.createLineBorder(Color.RED,     4));
        panel2.setBorder(BorderFactory.createLineBorder(Color.CYAN,    4));
        imgPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
        panel1.add(new JLabel("Panel 1"), BorderLayout.CENTER);
        panel2.add(new JLabel("Panel 2"), BorderLayout.CENTER);
        getContentPane().add(panel1, BorderLayout.NORTH);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        getContentPane().add(imgPanel, BorderLayout.CENTER);   
        pack();
        panel1.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel1");}});
        panel2.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel2");}});
      public static void main(String[] args){new Test().setVisible(true);}
    class ImagePanel extends JPanel
      Image img;
      public ImagePanel()
        setFocusable(true);
        setPreferredSize(new Dimension(400,300));
        try{img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));}
        catch(Exception e){/*handled in paintComponent()*/}
        addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            System.out.println("ImagePanel");}});
      public void paintComponent(Graphics g)
        if(img != null)
          g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
        else
          g.drawString("This space for rent",50,50);
    }

  • How to display a pdf file

    hello,
    I want to display a pdf document, but I don't find anything which could really help me...
    I want to parse the pdf file into a jpanel or something like that and then displaying that jpanel.
    has anyone please any idea how I could do that? how do I get the pdf file into the jpanel? examples would be very great...
    bye

    You can visit http://itextdocs.lowagie.com/
    perhaps this web can help you to display pdf file..
    and..I find an example for this...
    see the linked:http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/HelloSystemOut.java
    but I don't know if it is really what that you wanna get...
    best regards.

  • How to display a StyledDocument? (not in JTextComponent)

    I have read the following tutorials and relevant API's from the Swing Connection:
    Text overview: http://java.sun.com/products/jfc/tsc/articles/text/overview/index.html
    Text attributes: http://java.sun.com/products/jfc/tsc/articles/text/attributes/index.html
    The Element interface: http://java.sun.com/products/jfc/tsc/articles/text/element_interface/index.html
    .. and still don't get how to display a simple DefaultStyledDocument!
    The Text Overview tutorial has a brief discussion on Views, and the use of them.
    Let's say the doc is my DefaultStyledDocument. If I do a doc.getDefaultRootElement(0) this will give me the secion, which contains the children of all the paragraphs.
    I'd like to get all these paragraphs, put them into ParagraphViews and display them in my paint() method.
    I understand that the children of these paragraphs contain the Attribute information.
    The only way I'm able to dispay something is if I get the child of the first paragraph (eg. root>child>child) - which should be the style run (attribute information)) and then insert it into a LabelView.
    If I were to add all the different text's (each element in a paragraph) and display them, then the only way I can think of is to create a LinkedList or something of LabelView's, keep track of positions etc. myself, and then do a paint() on each one of them in a for-loop. Surely, this isn't the way it should be done.
    If I try to call paint() on eg. a BoxView (which I have given the doc.getDefaultRootElement()), or a ParagraphView (which I have given the first element - the paragraph) - nothing is displayed. I can't find anything in the API on how to add children to a paragraph, or display it's children (I found paintChild() but it is protected)..
    Does anyone know of a tutorial describing how to display a DefaultStyledDocument through one of the javax.swing.text.view's, or have an explanation on how to do it? It would be greatly appreciated!! :)

    You can extract hierarchy of views (tree) from TextUI
    like this
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.plaf.*;
    public class Test
    JFrame frame;
    public static void main(String args[])
    new Test();
    public Test()
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JEditorPane edit=new JEditorPane();
    edit.setEditorKit(new StyledEditorKit());
    edit.setText("test");
    TextUI ui=edit.getUI();
    View v=ui.getRootView(edit);
    Panel p=new Panel();
    p.bv=v;
    JScrollPane scroll=new JScrollPane(p);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(scroll,BorderLayout.CENTER);
    frame.setSize(300,200);
    frame.setVisible(true);
    class Panel extends JPanel {
    public View bv;
    public void paint(Graphics g) {
    super.paint(g);
    bv.paint(g,new Rectangle(0,0,100,100));
    best regards
    Stas

  • Having trouble displaying a JPanel on a JFrame

    Hello all,
    I'm fairly new to Java and I am having trouble displaying a JPanel on a JFrame. Pretty much I have a class called Task which has a JPanel object. Everytime the user creates a new task, a JPanel with the required information is created on screen. However, I cannot get the JPanel to display.
    Here is some of the code I have written. If you guys need to see more code to help don't hesitate to ask.
    The user enters the information on the form and clicks the createTask button. If the information entered is valid, a new task is created and the initializeTask method is called.
    private void createTaskButtonMouseClicked(java.awt.event.MouseEvent evt) {                                             
        if (validateNewTaskEntry())
         String name = nameTextField.getText().trim();
         Date dueDate = dueDateChooser.getDate();
         byte hourDue = Byte.parseByte(hourFormattedTextField.getText());
         byte minuteDue = Byte.parseByte(minuteFormattedTextField.getText());
         String amOrPm = amPmComboBox.getSelectedItem().toString();
         String group = groupComboBox.getSelectedItem().toString();
         numberTasks++;
    //     if (numberTasks == 1)
    //     else
         Task newTask = new Task(mainForm, name, dueDate, hourDue, minuteDue,
             amOrPm, group);
         newTask.initializeTask();
         this.setVisible(false);
    }This is the code that I thought would display the JPanel. If I put this code in anther form's load event it will show the panel with the red border.
    public void initializeTask()
         taskPanel = new JPanel();
         taskPanel.setVisible(true);
         taskPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
         taskPanel.setBounds(0,0,50,50);
         taskPanel.setLayout(new BorderLayout());
         mainForm.setLayout(new BorderLayout());
         mainForm.getContentPane().add(taskPanel);
    }I was also wondering if this code had anything to do with it:
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new AddTaskForm(new MainForm()).setVisible(true);
        }As you can see I create a new MainForm. The MainForm is where the task is supposed to be drawn. This code is from the AddTaskForm (where they enter all the information to create a new task). I had to do this because AddTaskForm needs to use variables and methods from the MainForm class. I tried passing the mainForm I already created, but I get this error: non-static variable mainForm cannot be referenced from a static context. So to allow the program to compile I passed in new MainForm() instead. However, in my AddTaskForm class constructor, I pass the original MainForm. Here is the code:
    public AddTaskForm(MainForm mainForm)
       initComponents();
       numberTasks = 0;
       this.mainForm = mainForm;
    }Is a new mainForm actually being created and thats why I can't see the JPanel on the original mainForm? If this is the case, how would I pass the mainForm to addTaskForm? Thanks a ton for any help/suggestions!
    Brian

    UPDATE
    While writing the post an idea popped in my head. I decided to not require a MainForm in the AddTaskForm. Instead to get the MainForm I created an initializeMainForm method.
    This is what I mean by not having to pass new MainForm():
        public static void main(String args[])
         java.awt.EventQueue.invokeLater(new Runnable()
             public void run()
              new MainForm().setVisible(true);
        }Even when I don't create the new MainForm() the JPanel still doesn't show up.
    Again, thanks for any help.
    Brian

  • How to display a drop down list

    how to display a drop down list when the user clicked (right click) on a JPanel or a JFrame

    how to display a drop down list when the user clicked
    (right click) on a JPanel or a JFrameI've not done it my self, I just looked it up:
    JComponent.setComponentPopupMenu(JPopupMenu popup).
    The menu doesn't showed automatically when I added it to a JComponent and tried to right click.
    I guess you could add a listener and call setVisible and setLocation for the menu in the listener, but there has to be an easier way...

  • Question on using JSplitPane to display 2 JPanels(thats has been drawn on)

    im currently doing a project in which the user is able to draw on 2 panels and the last step is to display the 2 panels with all the text and images that were drawn on it.
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
    splitPane.setOneTouchExpandable(true);
    splitPane.setContinuousLayout(true);
    c.add(splitPane, BorderLayout.CENTER);i want to call repaint on the 2 panels so when it goes through paintComponent my array of text/images will be redrawn on the splitpane accordingly.
    any suggestions on how this can be done since its my first time display 2 jpanels on a splitpane im out of ideas.
    thanks in advance

    Just call repaint on each panel.

  • Idoc-xi-file scenario.  how to display file in html format

    I am not sure whether this is a valid question.........but want to confirm as it was asked by somebody
    In idoc-xi-file scenario.......  how to display file in html format ??
    Thanks in advance
    Kumar

    Hi Vijayakumar,
    Thanks for your reply !! You mean to say I got to use XSLT mapping and also .htm and .html extension together to produce the html file ?? or it is sufficient to use any one of them to produce the html file ??
    Regards
    Kumar

  • In sap scripts how to display the driver program

    Hi,
        I Want to know the sap scripts How to display the output to driver program

    Hi,
    Go to NACE Transaction.
    Select application for ex: if sales V1.
    Click on output types.
    Select the output type for ex : BA00
    Double click on Processing routines.
    There you can find the Driver Program name and Script/smart form name.
    Reward if useful.
    Thanks,
    Raju

  • How to display username in RTF BI publisher report?

    Please advice how to display username in RTF BI publisher report?
    May be this can be done via hidden parameter of BIP report which default value will be set up with macro like {$username$} (or smth like)?
    Thanks in advance!

    Thanks. That worked. I was trying to get it as part of a multi-table query, aliasing dual. But that doesn't work in SQL Plus either so I guess I can't do that.
    I was trying
    select o.*, d.:xdo_user_name
    from oblix_audit_events o, dual d
    Before that I was trying
    select
    :xdo_user_name as USER_ID,
    :xdo_user_roles as USER_ROLES,
    :xdo_user_report_oracle_lang as REPORT_LANGUAGE,
    :xdo_user_report_locale as REPORT_LOCALE,
    :xdo_user_ui_oracle_lang as UI_LANGUAGE,
    :xdo_user_ui_locale as UI_LOCALE
    from dual
    but I must have fat fingered something because that works now too. Thanks.
    So if I need to do this in it's own query and I'm using an RTF template, how do I make that work?
    If I have to do it with it's own

  • How to display and edit the clob datatype column from Data base

    Hi ,
    I have a requiremsnt as below
    1) One Table having some columns with CLOB data type along with varchar columns
    2) need to display the data from DB in search screen and need to be edited clob column in edit screen
    I created EO and VO with that Table and how to display the clob value into the input box for editing.
    using Jdev 11.1.1.5.0 version.
    Can you please help on this.
    THanks & REgards,
    Madhu

    Hi,
    If you are using an inputText component to display a Character Large Object (CLOB), then you will need to create a custom converter that converts the CLOB to a String.
    For custom convertor refer below link,
    http://docs.oracle.com/cd/E2438201/web.1112/e16181/af_validate.htm#BABGIEDH
    (section7.4 Creating Custom JSF Converters)
    Thanks,
    Santosh M E

Maybe you are looking for

  • What specs/ upgrades should I get for a Macbook pro that I'm buying?

    I don't want to spend a ton of money but enough that the macbok pro will be really fast. I browse the web a lot I watch youtube and netflix on it I will need it to do college assignments I will need to do basic video and picture editing

  • HT3702 I Have been charged twice for the song download.

    Thank you for using your HDFC bank CREDIT card ending 9563 for Rs.120.00 in ITUNES.COM at APPLE ITUNES STORE-INR on 2013-03-04:00:41:48. Thank you for using your HDFC bank CREDIT card ending 9563 for Rs.60.00 in ITUNES.COM at APPLE ITUNES STORE-INR o

  • Apple Devices ISE GUEST REDIRECT

    Dears, All our devices connecting to corporate SSID and Guest SSID when connecting to Guest SSID all devices connect and  been redirected to  ISE Guert portal BUT APPLE devices just stays on loading page to Ise server page for guest portal and nothin

  • WUT-121 error on 9iAS

    Using WebUtil, I successfully opened an image file in a form in 9iDS. When we moved to the app server, we encountered the WUT-121 error. The temporary directory space is not restricted, and this is in the file webutil.cfg: transfer.database.enabled=T

  • On a canceled appointment can I configure so that it shows with a line through, rather than disappearing, when I accept the change?

    When my assistant deletes in her outlook, it comes as a notification that the appointment is canceled, with the option of accepting the update.  If I don't accept the update, there is a line through the appointment, which I like.  If I do, the appoin