FlowLayout in JPanels, and Container

I set the FlowLayout alignment to RIGHT justify on my Container. I also want to control individual FlowLayouts in JPanels that are added to the Container. I want some panels to be center, and others LEFT or LEADING alignments, etc.
So far everything I try on the JPanel LayoutManager Alignment has no effect. Only the changes I make to the Container layout alignment have an effect. All of the JPanels are RIGHT justified when I run this program.
          rightLayout = new FlowLayout();
          rightLayout.setAlignment(FlowLayout.RIGHT);
          centerLayout = new FlowLayout();
          centerLayout.setAlignment(FlowLayout.CENTER);
          leftLayout = new FlowLayout();
          leftLayout.setAlignment(FlowLayout.LEADING);
          container.setLayout(rightLayout);
          titlePanel = new JPanel(centerLayout);
          twoPanel = new JPanel();
          threePanel = new JPanel(leftLayout);
          fourPanel = new JPanel();
          text1Panel = new JPanel(centerLayout);
          text2Panel = new JPanel(centerLayout);
          buttonPanel = new JPanel(centerLayout);
Thanks, rjw

Okay i think that to use GrisBagLayout takes away all the hastle,you can get things where you want them,
i think people don't use cause it seems like it's more complex to use,if you put this helper method in your code then you only need one line in your code to place a component.
This is the line of code to place a component
        addComp(theButton,theContainer,gb1,gbc,       0,1,1,1,1,1,gbc.WEST);Place this at the start of your CODE also
         GridBagLayout gb1 = new GridBagLayout();
         GridBagConstraints gbc = new GridBagConstraints();
         setLayout(gb1);/*
     * This is a helper method for GridBagConstraint Layout
     public void addComp(Component comp,Container cont, GridBagLayout gb1,GridBagConstraints gbc,
                    int row,int col, int numRows, int numCols, double weightx, double weighty,int theAnchor)
          gbc.gridx = col;
          gbc.gridy = row;
          gbc.gridwidth = numCols;
          gbc.gridheight = numRows;
          gbc.weightx = weightx;
          gbc.weighty = weighty;
                                           gbc.anchor = theAnchor
          cont.add(comp,gbc);
     }If you try and understand and it's not quite hard then it makes GUI building a lot easier and more efficient i think,let me know if you give this a go.

Similar Messages

  • Urgent!! about the JPanel and Container!!!!

    good day to all!!. i would like to ask is it posible to set the location for some component like button and button which inside the panel or container (other than use North ,south, east )?? and is the posible to set the size and location for JPanel or Jbutton??
    eg.
    JPanel buttonPanel = new JPanel();
    JButton button = new JButton();
    button.setBounds(20,20,20,20);
    buttonPanel.add(button);
    buttonPanel.setSize(200,200);
    buttonPanel.setBounds(200,200,10,10);
    frame.add(buttonPanel);
    is this coding working ???
    thank you to help me !!!

    my excact coding is like this
    i would like to move the textfield and button
    how to make it ??
    ===================================================
    Keypad.java
    public class KeyPad extends JPanel
    JPanel ButtonPanel;
    public KeyPad()
         //setLayout(null);
         JPasswordField display = new JPasswordField(5);
         ButtonPanel = new JPanel();
         //ButtonPanel.setLayout(null);
         addButton("7");
         addButton("8");
         addButton("9");
         addButton("4");
         addButton("5");
         addButton("6");
         addButton("1");
         addButton("2");
         addButton("3");
         addButton(".");
         addButton("0");
         addButton("?");
         ButtonPanel.setBounds(20,20,20,20);
         ButtonPanel.setSize(200,200);
         add(display);
         add(ButtonPanel);
         private void addButton(final String label)
              JButton button =new JButton(label);
              ButtonPanel.add(button);
    class DigitButtonListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   //if (label.equals(".") && display.getText().indexOf(".") != 1)
                   //     return;
                   //display.setText(display.getText() + label);
    ActionListener listener = new DigitButtonListener();
    button.addActionListener(listener);
    ============================================================
    Runapplication.java
    class RunApplication extends JFrame
    KeyPad pad;     
         public RunApplication()
              //setLayout(null);
              Container contentPane = getContentPane();
              pad = new KeyPad();
              contentPane.setBounds(200,200,200,200);
              contentPane.add(pad,BorderLayout.CENTER);
    ===========================================
    test.java
    public class test
    public static void main (String[] args)
    {   JFrame f = new RunApplication();
    f.setSize(800,600);
    f.setVisible(true);
    f.show();

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

  • Canvas3D JPanel and Behavior

    Hello,
    I am a student’s geomatic and I do my memory on 3D object implementation in a data base.
    To do that, I have a 3D graphic interface. I use Java 3D and Swing.
    Now, my program load only 3D points. There are 3 parts:
    - a 3D viewer,
    - a table,
    - buttons for the actions.
    I would like to get the 3D mouse coordinates in my 3D world.
    I succeed in a first program’s version. There were two windows JFrame, one included the Canevas3D and the other the table with the buttons.
    For the mouse’s action, I modify this source code :
    http://deven3d.free.fr/telechargements/fichiers/java3d/chap07/SimpleBehavior/SimpleBehavior.java
    Then, I put the Canevas3D in a JPanel (and neither in a separate window). And I add this JPanel to the JFram (those contain the table and the buttons for the actions).
    And after that my class Behavior don’t work.
    I think it’s due to my ActionListener (it’s use to catch the buttons’ press) who intercept the mouse action.
    This is my class Behavior :
    import java.awt.AWTEvent;
    import java.awt.Point;
    import java.awt.event.*;
    import java.util.Enumeration;
    import javax.media.j3d.*;
    import javax.vecmath.Point3d;
    public class InterGraph3d extends Behavior {
           // Condition qui va declencher le stimulus
           private WakeupCondition wakeupCondition =
                new WakeupOnAWTEvent(MouseEvent.MOUSE_PRESSED);
           private Canvas3D caneva;
           InterGraph3d (Canvas3D cane){
                   this.caneva = cane;
         public void initialize() {
             this.wakeupOn(wakeupCondition);
         public void processStimulus(Enumeration criteria) {
              WakeupCriterion critere;
             AWTEvent[] events;
             MouseEvent evt;
             // On boucle sur les critères ayant declenche le comportement
             while (criteria.hasMoreElements()) {
               // On recupere le premier critere de l'enumeration
               critere = (WakeupCriterion)criteria.nextElement();
               // On ne traite que les criteres correspondant a un evenement AWT
               if (critere instanceof WakeupOnAWTEvent) {
                 // On récupère le tableau des evements AWT correspondant au critere
                 events = ((WakeupOnAWTEvent)critere).getAWTEvent();
                 if (events.length > 0) {
                   // On récupère l'événement
                   evt = (MouseEvent)events[events.length-1];
                   // Traitement au cas par cas selon la touche pressée
                   switch(evt.getButton()) {
                   // Obtenir les coordonnées 3D du point cliqué
                     case MouseEvent.BUTTON1: // clic gauche
                     // pour avoir les coordonnées du point cliqué dans l'univers en 3D
                     // on déclare un point 3D
                     Point3d ptSourie = new Point3d();
                     // on utilise la fonction pour avoir les coordonnées de la sourie en 3D.
                     ptSourie = obtenirPointSourieCaneva(caneva, evt.getPoint());
                     // ici faire une liaison avec l'interface graphique
                     System.out.println("Coor sourie");
                       System.out.println(ptSourie.x);
                       System.out.println(ptSourie.y);
                       System.out.println(ptSourie.z);
                       break;
              // Une fois le stimulus traite, on réinitialise le comportement
             this.wakeupOn(wakeupCondition);
         // fonction pour récupérer les coordonnées de la sourie dans le
         public Point3d obtenirPointSourieCaneva(Canvas3D myCanvas, Point clickPos)
              Point3d mousePos = new Point3d();
              //pixel value in image-plate coordinates and copies that value into the object provided.
             myCanvas.getPixelLocationInImagePlate(clickPos.x, clickPos.y, mousePos);
              //This block of code converts our image plate coordinates out to virtual world coordinates
              Transform3D motion = new Transform3D();
              myCanvas.getImagePlateToVworld(motion);
              //We do this convertion the mouse position.
              motion.transform(mousePos);
              return mousePos;
    }

    The ScrollDemo uses the column and row header as well as the corner to create the rulerIt adds a component to the colum and row header and the corner. That component may or may not be a JPanel, or JComponent which they have used for custom painting.
    Can I change the ScrollDemo to use a JPanel instead?Makes no sense. There are 9 areas to add a Component. Any of those 9 areas can hold a JPanel.
    Does a JPanel provide the same elements A panel uses a LayoutManager to place components. Check the scroll pane source code to see what LayoutManager it uses.

  • Displaying image in JPanel and scroll it through JScrollpanel

    Can any one will help me,
    I need to draw a image in a JPanel and, this JPanel is attached with a Jscrollpanel.
    I need to scroll the this JPanel to view the image.

    Here is my code for that
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PicPanel extends javax.swing.JPanel implements WindowListener{
    /** Creates new form PicPanel */
    public PicPanel() {
    initComponents();
    // this.setOpaque(true);
    JFrame myFrame = new JFrame("Panel Tiler");
    myFrame.addWindowListener( this );
    myFrame.setSize(new Dimension(1000,300));
    setPreferredSize(new Dimension(1000,300));
    Container cp = myFrame.getContentPane();
    cp.add( this, BorderLayout.CENTER );
    tk = Toolkit.getDefaultToolkit();
    im =tk.getImage("smple.jpg");
         jPanel1.im=im;
    // jPanel1.setSize(new Dimension(1000,300));
    myFrame.pack();
    myFrame.show();
    jPanel1.repaint();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
         jPanel1=new JPanelC();
    jScrollPane1 = new javax.swing.JScrollPane(jPanel1);
    setLayout(new java.awt.GridBagLayout());
    jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setOpaque(false);
         gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.gridheight = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 378;
    gridBagConstraints.ipady = 298;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jScrollPane1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.ipadx = 372;
    gridBagConstraints.ipady = 280;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jPanel1, gridBagConstraints);
    public static void main(String[] args)
    new PicPanel();
    public void windowOpened(WindowEvent e) {}
    public void windowClosing(WindowEvent e)
    // myFrame.dispose();
    System.exit(0);
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    private JPanelC jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private Icon iiBackground;
    private Toolkit tk;
    private Image im;
    class JPanelC extends javax.swing.JPanel{
    public Image im;
    public void paintComponent(Graphics g){
              //super.paintComponent(g);
    if(im!=null)
                   imageobserver io = new imageobserver();
         System.out.println(im.getHeight(io));
         if(im.getHeight(io)!=-1)
    setSize(im.getWidth(io), im.getHeight(io));
    g.drawImage(im,0,0,null);
         // setOpaque(false);
    super.paintComponent(g);
    class imageobserver implements java.awt.image.ImageObserver{
    public boolean imageUpdate(Image img, int infoflags, int x, int y,int width, int height) {
              if ((infoflags & java.awt.image.ImageObserver.ALLBITS) != 0) {
    repaint();
    return false;
    //repaint();
    return true;
    Here i need to scroll the image in the panel but it is not working out.

  • About JPanel and JTabbedPane

    I have a JPanel and i want to know how any tab buttons it contain.
    We have a method in JTabbedPane to find it out ,so how can i type cast the JPanel to JTabbedPane.
    Thanks

    JTabbedPane does not extend JPanel, so you can't cast JPanel to JTabbedPane.
    A JPanel does not contain any tabs.
    I think you might need to rephrase the question.

  • Help me to solve it, JPanel and object reference

    Hi, friends,
    please help to solve this problem
    I have array of objects, let's say
    JLabel a[][] = new JLabel[4][4];then i add them into a JPanel(new GridLayout(4,4));
    public void buildLayout(){
       lfMouse lf = new lfMouse(); //MouseListener
          for(int i=0;i<4;i++){
         for(int j=0;j<4;j++){
                             lbl[i][j] = new JLabel(i*10+j+"");
             lbl[i][j].addMouseListener(lf);
             pane.add(lbl[i][j]);
    }What i need is when user click the label, the label will change to another JLabel's object, and the panel can immediately update itself.
    Here's my assumption:
    class lfMouse extends MouseAdapter{
            public void mouseClicked(MouseEvent e){
                      JLabel temp = (JLabel)e.getSource(); //get the clicked object
                       temp = new JLabel("Hihi"); //change its address to other    
                                                                        //object's reference
                       pane.revalidate();
    }But it didn't work...can anyone help me to understand object reference concept in Java? And how can i update the UI of JPanel immediately?
    I don't use setText(), because i need to change to another object...
    All i can do is to remove all the label in JPanel, and add the label to JPanel again..but i think it's not the effective way...
    please help me to solve it....
    Thanks for your help.... :)

    Creating a new Object does not add the Object to the panel. Its just an Object sitting in memory.
    I don't use setText(), because i need to change to another object...setText(...) is the obvious solution
    If you need to keep the original text String in your array then your array should be an array of Strings. Then you would build your JLabels using the Strings contained in the array. This way when you update the text of the label you are not touching the original array String values.
    All i can do is to remove all the label in JPanel, and add the label to JPanel again..but i think it's not the effective way...Its the only other way if you don't want to use setText(...);

  • Painting JPanels and graphics

    I have a JPanel into which want to display boxes of data connected by lines. The boxes are JPanels (with a ScrollPane and JList) and the lines simply Graphics2D objects. I have overridden the paint(g) method of the enclosing panel to call super.paint(g) followed by my graphics calls. This works fine on start-up and repaint (from maximizing), but when I resize the main panel, the middle of the panel doesn't show the graphics (the inner panels display fine). I think I see the graphics being drawn then erased, but I'm not sure. Reviewing the Painting in AWT and Swing articles hasn't helped. I've tried various versions of paintComponent(), paintChildren(), etc. as alternatives, but the problem remains (or I never see the graphics at all). This seems like a timing and clipping problem but I can't figure it out. Can anyone explain what resize is doing that is different than a normal paint? How should one combine JPanels and graphics?Thanks.

    Unfortunately, overriding paintComponent() causes the graphics to be completely over-written for some reason. The problem is apparently when the inner Panels are written (I guess by paintChildren()). I'm following the directions in Doing Without a Layout Manager in the Java Tutorial: setting the outer JPanel's layout to null, explicitly setting the bounds of the inner JPanels and overwriting paint() with super.paint() (which paints the inner panels correctly) followed by my graphics code. All is well until I resize.
    Now the Doing Without a Layout Manager page states "However, creating containers with absolutely positioned containers can cause problems if the window containing the container is resized." Guess they're right ;-) Anyone know how to get around this problem?

  • JPanels and SplitPanes difficulty

    Hi there, I am playing around with swing at the moment, and am having some difficulty with JPanels and split panes.
    What I would like to get eventually is a JFrame split up like this:
    |             |            |
    |             | -----------|
    |             |            |
    |             |            | 
    |             |            |
    |             | -----------|
    ----------------------------Just in case that v poor diagram does not suffice - The JFrame should be split roughly in half with a vertical line, then the right hand panel should be split into thirds (roughly) with two horizontal lines.
    The code that I have is this:
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
         public class ccssc  {
              private JPanel jsp2;
              private JPanel jsp1;
              private JPanel jsp3;
              private JPanel jsp4;
              private JLabel jl = new JLabel("HELLO JLABEL");
              public ccssc(){
                   JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame frame = new JFrame("Self Contained Example");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setPreferredSize(new Dimension(1200, 900));
              //init
              jsp2 = new JPanel();
              jsp1 = new JPanel();
              jsp3 = new JPanel();
              jsp4 = new JPanel();
              jsp3.setSize(350, 50);
              jsp4.setSize(350, 50);
              jsp1.setSize(900, 1000);
              jsp3.add(jl); //Frame with the JLabel on it.
              jsp1.setBackground(Color.BLUE);
              jsp2.setBackground(Color.BLACK);
              jsp3.setBackground(Color.RED);
              jsp4.setBackground(Color.GREEN);
              JSplitPane splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                     true, jsp3, jsp2);
              JSplitPane splitPane3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                     true, splitPane2, jsp4 );
              JSplitPane splitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                     true, jsp1, splitPane2);
             splitPane2.setDividerLocation(50);
             splitPane3.setDividerLocation(700);
             splitPane1.setDividerLocation(850);
             frame.add(splitPane3);
             frame.add(splitPane1);
             frame.setResizable(true);
             frame.pack();
              frame.setVisible(true);
              public static void main(String[] args) throws Exception{
                   new ccssc();
         }My thinking is that the JSplitPane3 should have as its top half JSplitPane2, and as its bottom half, the new JPanel (jsp4) however, this does not work, it runs fine, but only displays the first 3 JPanels, and only the JSplitPanes 1 and 2.
    I am confused, is there something I am missing here?
    Thanks for your time,
    beccy

    Two issues with your code:
    You know that you are adding components to JFrame twice without specifying where. When doing this, you are actually adding components to the JFrame's contentPane, and the default layout for the contentPane is a BorderLayout. Thus when you add two things without specifying a location, both are added to the BorderLayout.CENTER position, and thus the second component will completely obscure the first one added.
    The other issue is that the API for the JSplitPane.setDividerLocation( ) method states that it only will have an effect after the split pane is correctly realized and on the screen. This will only occur after setVisible(true) has been called. You may want to move these method calls to after the frame has been set visible. If done correctly, you won't have to call setSize on the JPanels (somethiing that shouldn't be done anyways). Something like so:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.SwingUtilities;
    class MyCcssc2 extends JPanel
        public static final Dimension PANEL_SIZE = new Dimension(800, 650);
        private static final long serialVersionUID = 1L;
        private JPanel leftPanel = new JPanel();
        private JPanel rightTopPanel = new JPanel();
        private JPanel rightMidPanel = new JPanel();
        private JPanel rightBottomPanel = new JPanel();
        private JSplitPane rightBottomSP = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                rightMidPanel, rightBottomPanel);
        private JSplitPane rightSP = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                rightTopPanel, rightBottomSP);
        private JSplitPane mainSP = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                leftPanel, rightSP);
        MyCcssc2()
            setLayout(new BorderLayout());
            setPreferredSize(PANEL_SIZE);
            leftPanel.setBackground(Color.blue);
            rightTopPanel.setBackground(Color.red);
            rightMidPanel.setBackground(Color.black);
            rightBottomPanel.setBackground(Color.green);
            add(mainSP);
        public void setDividerLocation()
            mainSP.setDividerLocation(0.5);
            rightSP.setDividerLocation(0.3333);
            rightBottomSP.setDividerLocation(0.3333);
        private static void createAndShowGUI()
            JFrame frame = new JFrame("Swing Application");
            MyCcssc2 ccssc2 = new MyCcssc2();
            frame.getContentPane().add(ccssc2);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            ccssc2.setDividerLocation();
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }Also, try to use variable names that are more meaningful. It will make your code that much easier for us to read. Good luck!
    Edited by: Encephalopathic on Dec 26, 2007 7:42 AM

  • Difference between panel and container

    if both panel and container can contain components inside , then that is the defference between them?
    thanks in advanced.

    if both panel and container can contain components insideJPanel inherits this ability because it extends Container. The point of extending classes is to provide additional functionality. Read the API to see what additional functionality JPanel provides.
    The main difference is that JPanel is a Swing component. You should always use Swing components in a Swing application. This will ensure painting of the panel and all its child components are done correctly.

  • Extending JPanel to contain a JRootPane - problems with scroll panes

    I am trying to write a JPanel subclass that contains a JRootPane, similar to the way that JFrame contains a JRootPane. The reason that I am doing this is that I would like to be able to intercept mouse events using the JGlassPane facility, but adding the glasspane to the JFrame is problematic since it then intercepts mouse events over all components in the JFrame, including the menu bar. It seems simpler to me to have the JRootPane owned by a JPanel, to give me better control over intercepting events. I've got an implementation working with the JFrame case, but have had to handle many small "gotchas", and at least one more exists. I'm hoping to simplify things by moving away from this way of doing things.
    I wrote a straightforward RootPanePanel class that extends JPanel and implements RootPaneContainer, delegating all of the add methods to the JRootPane's content pane. Here's the constructor for RootPanePanel:
    public RootPanePanel (LayoutManager layout) {
            rootPane = new JRootPane ();
            rootPane.setOpaque(true);
            rootPane.getContentPane().setLayout(layout);
            super.add (rootPane);
    }RootPanePanel also delegates calls like getContentPane/setContentPane to the JRootPane.
    To test my implementation, I wrote a main method that looks like the following:
    public static void main (String[] args) {
      SwingUtilities.invokeLater(new Runnable () {
        public void run () {
          try {
            JEditorPane editorPane = new JEditorPane ("http://www.archives.gov/exhibits/charters/print_friendly.html?page=declaration_transcript_content.html&title=NARA%20%7C%20The%20Declaration%20of%20Independence%3A%20A%20Transcription");
            JScrollPane scrollPane = new JScrollPane (editorPane);
            JFrame frame = new JFrame ("Test RootPanePanel");
            RootPanePanel panel = new RootPanePanel ();                    
            panel.add(scrollPane);
            frame.add(panel, BorderLayout.CENTER);
            scrollPane.setPreferredSize(new Dimension(800, 600));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize (640, 480);
            frame.pack ();
            frame.setVisible(true);
          } catch (Exception e) {
            e.printStackTrace();
      });Note that I'm not actually using JEditorPane in my application, but it is the simplest component that displays the problem I'm encountering.
    When this code runs, it is fine, as long as the JFrame is big enough to display the scrollbars for the JScrollPane. If the JFrame is made small enough, the scrollbars are not displayed.
    If I instead add the JScrollPane to the JFrame directly, it behaves as you would expect.
    Is this a problem of mixing heavyweight and lightweight components? It doesn't seem like it should be; in both cases the JScrollPane is handling the same client component, the JEditorPane.
    Any suggestions/ideas are welcome!

    Here's the full RootPanePanel class in case people want to try it out
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.HeadlessException;
    import java.awt.LayoutManager;
    import java.io.IOException;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JRootPane;
    import javax.swing.JScrollPane;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    public class RootPanePanel extends JPanel implements RootPaneContainer {
         private JRootPane rootPane;
         public RootPanePanel () {
              this (new BorderLayout());
         public RootPanePanel (LayoutManager layout) {
              rootPane = new JRootPane ();
              rootPane.setOpaque(true);
              rootPane.getContentPane().setLayout(layout);
              super.add (rootPane);
         public Container getContentPane() {
              return rootPane.getContentPane();
         public Component getGlassPane() {
              return rootPane.getGlassPane();
         public JLayeredPane getLayeredPane() {
              return rootPane.getLayeredPane();
         public void setContentPane(Container arg0) {
              rootPane.setContentPane(arg0);
         public void setGlassPane(Component arg0) {
              rootPane.setGlassPane(arg0);
         public void setLayeredPane(JLayeredPane arg0) {
              rootPane.setLayeredPane(arg0);
         @Override
         protected void addImpl(Component comp, Object constraints, int index)
              if (comp == rootPane) {
                   super.addImpl(comp, constraints, index);
              else {
                   getContentPane().add(comp, constraints, index);
         @Override
         public Component add(Component comp, int index) {
              return rootPane.getContentPane().add(comp, index);
         @Override
         public void add(Component comp, Object constraints, int index) {
              rootPane.getContentPane().add(comp, constraints, index);
         @Override
         public void add(Component comp, Object constraints) {
              rootPane.getContentPane().add(comp, constraints);
         @Override
         public Component add(Component comp) {
              return rootPane.getContentPane().add(comp);
         @Override
         public Component add(String name, Component comp) {
              return rootPane.getContentPane().add(name, comp);
         public static void main (String[] args) {
              SwingUtilities.invokeLater(new Runnable () {
                   public void run () {
                        try {
                             JEditorPane editorPane = new JEditorPane ("http://www.archives.gov/exhibits/charters/print_friendly.html?page=declaration_transcript_content.html&title=NARA%20%7C%20The%20Declaration%20of%20Independence%3A%20A%20Transcription");
                             JScrollPane scrollPane = new JScrollPane (editorPane);
                             JFrame frame = new JFrame ("Test RootPanePanel");
                             RootPanePanel panel = new RootPanePanel ();                    
                             panel.add(scrollPane);
                             frame.add(panel, BorderLayout.CENTER);
                             scrollPane.setPreferredSize(new Dimension(800, 600));                                                                                                                                                 
                             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                             frame.setSize (640, 480);
                             frame.pack ();
                             frame.setVisible(true);                                                                                                    
                        } catch (HeadlessException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
         public JRootPane getRootPane() {
              return rootPane;
    }

  • Zoom JPanel and all its components

    Folkses,
    I have a JPanel which contains a lot of different components, containers with components, etc.
    The components are either images or drawn 'by hand' (overwritten paintComponent).
    Is there a simple way of zooming in/out to get the whole picture larger/smaller? I know Graphics2D.scale() but I'm hestitant to implement this in each and every component of my JPanel.
    Thanx,
    Thomas
    PS: searching the forum I only found answers on zooing images...

    Hello camickr,
    I am also very much interested in this.
    Well, you can create an image of a panel and then zoom the image.But I think this will not increase the components' bounds and components would not respond mouse events etc. correctly. Am I right? Then, what is the way of zooming such that all the components respond to events correctly.
    I hope you have done something like this before and help us.
    Thanks!

  • HT204268; I have purchases on an aol login pre 2008 and all recent stuff under an apple id. I currently see and use everything when i login with the apple id. After March 31st will my apple id account still show and contain all?

    HT204268; I have purchases on an aol login pre 2008 and all recent stuff under an apple id. I currently see and use everything when i login with the apple id. After March 31st will my apple id account still show and contain all?
    I understand the instructions to create a new account id (apple id) from the old aol account. However, does this mean my purchases will be split into 2 accounts; or does the fact that I currently see everything under my apple id (regardless of the purchased by username) mean this will all still appear in my current account as it does now?

    You see them where when you login your non-AOL account ?
    If you currently have two accounts (the AOL username account and an email address account) then you will continue to have two accounts, and nothing should change when you update the AOL account to be an email address (apart from how you access that account).
    You will just be renaming the account to have an email address for accessing it, not creating a new account.

  • ResultList and Container objects

    The Java ResultList and Container objects are used in SAP Mapping UDF's ...does anyone know which specific jar files contain these object definitions ?
    Thanks,
    Rod.

    For PI 7.0(3.0) you need the libraries: aii_mt_rt.jar, aii_map_api.jar, aii_utilxi_misc.jar
    For PI 7.1 you need the libraries: com.sap.xi.mapping.tool.lib_api.jar, com.sap.xpi.ib.mapping.lib.jar, com.sap.aii.utilxi.server.jar
    /people/stefan.grube/blog/2005/12/30/test-user-defined-functions-for-the-xi-graphical-mapping-tool-in-developer-studio

  • Array of JPanel and Array of JTextField?

    Hi,
    I try to create array of jpanel and inizialize it in "for" , but when run it give me this error message:
    "Exception in thread "main" java.lang.NullPointerException"
    at the row: "panInsCantante.add(panInsNCC);"
    why?
    (ps. i tried in another code to create array of jtextfield and it give me same error message..)
    here part of code :
          JPanel [] panInsCantante = new JPanel[3];
          for(int i=0;i<=N;i++){
               JPanel panInsNCC= new JPanel();
               panInsNCC.setLayout( new GridLayout(3,1) );
               panInsNCC.add(campoTesto1);
               panInsNCC.add(campoTesto2);
               panInsNCC.add(campoTesto3);
               //panInsCantante[i] = new JPanel();
               //panInsCantante.setLayout( new GridLayout(1,1) );
         panInsCantante[i].add(panInsNCC);

    a question (theoric...)A VERY important question I may add.
    what's the difference between ..
    this instance :
    JPanel [] panInsCantante = new
    JPanel[3];This declares and initializes the array itself, nothing more. No JPanels have been initialized as yet, just the array. It's as if you have now built the shelves to hold the books, but you have no books up there yet...
    and this instance of panInsCantante? :
    panInsCantante[i] = new JPanel();and this initializes each JPanel in the array as you loop through the array. .... and now you have filled the shelves with the books and can use the books.
    You will need them both.
    In all likelihood, the reason for your confusion is that all of your previous arrays were arrays of primative types: int, double, float, and char. In this situation, you don't need to go through the step of initializing the variable.
    But now you are faced for the first time with an array of reference type, an array of Objects. This is a different situation and requires the steps that we have gone through.
    Message was edited by:
    petes1234

Maybe you are looking for