A component within JTabbedPane with overlay layout

Hi, I use the following solution to have a component within the upper right corner of the JTabbedPane: [http://forums.sun.com/thread.jspa?forumID=57&threadID=636289&start=2|http://forums.sun.com/thread.jspa?forumID=57&threadID=636289&start=2] . It works great, but when I'm resizing a window with the JTabbedPane with the JTabbedPane.WRAP_TAB_LAYOUT and width of all of the tabs is higher than size of the window the tabs are wrapped. But it should be wrapped when width of all tabs + width of the added component is higher than the size. I have no idea how to do this. Any ideas?
Please see the screenshot: [http://img150.imageshack.us/img150/5629/btn.png|http://img150.imageshack.us/img150/5629/btn.png]

Just a quick idea:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
class TabbedPaneTest {
  public JComponent makeUI() {
    UIManager.put("TabbedPane.tabAreaInsets",
                  new InsetsUIResource(6, 2, 0, 60));
    JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    sp.setTopComponent(makeTabPanel(new JTabbedPane()));
    sp.setBottomComponent(makeTabPanel(new ClippedTitleTabbedPane()));
    sp.setPreferredSize(new Dimension(320, 240));
    return sp;
  private JPanel makeTabPanel(final JTabbedPane tab) {
    tab.addTab("asdfasd", new JLabel("456746"));
    tab.addTab("1234123", new JScrollPane(new JTree()));
    tab.addTab("6780969", new JLabel("zxcvzxc"));
    tab.setAlignmentX(1.0f);
    tab.setAlignmentY(0.0f);
    JButton b = new JButton(new AbstractAction("add") {
      @Override public void actionPerformed(ActionEvent e) {
        tab.addTab("test", new JScrollPane(new JTree()));
    b.setAlignmentX(1.0f);
    b.setAlignmentY(0.0f);
    JPanel p = new JPanel();
    p.setLayout(new OverlayLayout(p));
    p.add(b);
    p.add(tab);
    return p;
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() { createAndShowGUI(); }
  public static void createAndShowGUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new TabbedPaneTest().makeUI());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
class ClippedTitleTabbedPane extends JTabbedPane {
  //XXX Nimbus NPE
  Insets tabInsets = UIManager.getInsets("TabbedPane.tabInsets");
  Insets tabAreaInsets = UIManager.getInsets("TabbedPane.tabAreaInsets");
  public ClippedTitleTabbedPane() {
    super(JTabbedPane.TOP);
    setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    addComponentListener(new ComponentAdapter() {
      @Override public void componentResized(ComponentEvent e) {
        initTabWidth();
  @Override
  public void insertTab(String title, Icon icon, Component component,
                        String tip, int index) {
    super.insertTab(title, icon, component, tip==null?title:tip, index);
    JLabel label = new JLabel(title, JLabel.CENTER);
    Dimension dim = label.getPreferredSize();
    label.setPreferredSize(
        new Dimension(0, dim.height+tabInsets.top+tabInsets.bottom));
    setTabComponentAt(index, label);
    initTabWidth();
  private void initTabWidth() {
    Insets insets = getInsets();
    int areaWidth = getWidth() - tabAreaInsets.left - tabAreaInsets.right
                               - insets.left        - insets.right;
    int tabCount = getTabCount();
    int tabWidth = 0;
    switch(getTabPlacement()) {
      case LEFT: case RIGHT:
      tabWidth = areaWidth/4;
      break;
      case BOTTOM: case TOP: default:
      tabWidth = areaWidth/tabCount;
    int gap = areaWidth - (tabWidth * tabCount);
    if(tabWidth>80) {
      tabWidth = 80;
      gap = 0;
    tabWidth = tabWidth - tabInsets.left - tabInsets.right - 3;
    for(int i=0;i<tabCount;i++) {
      JLabel l = (JLabel)getTabComponentAt(i);
      if(l==null) break;
      int h = l.getPreferredSize().height;
      l.setPreferredSize(new Dimension(tabWidth+((gap>0)?1:0), h));
      gap--;
    revalidate();
}

Similar Messages

  • Problems with Overlay Layout - can anyone spot something wrong/missing?

    Hi folks, I'm developing a tool that allows you to draw rectangles around objects on an image. The rectangles are then saved, and you can move between images. For some reason, though my rectangles are not drawing on the panel. I am using the Overlay Layout. Can anyone spot what I'm doing wrong? (The TopPanel canvas appears to be there, as it's taking input from the mouse - the problem is simply that the red rectangles are not drawing on the panel). Please help!!
    So you know, there is a JFrame in another class which adds an instance of the ObjectMarker panel to it. It also provides buttons for using the next and previous Image methods.
    Any other general advice is appreciated too.
    * Object_Marker.java
    * Created on 07 April 2008, 15:38
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.event.MouseEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import javax.imageio.ImageIO;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.OverlayLayout;
    import javax.swing.event.MouseInputAdapter;
    * @author Eric
    public class ObjectMarker extends javax.swing.JPanel {
         private static final long serialVersionUID = 6574271353772129556L;
         File directory;
         String directory_path;
         Font big = new Font("SansSerif", Font.BOLD, 18);
         List<File> file_list = Collections.synchronizedList(new LinkedList<File>());
         String[] filetypes = { "jpeg", "jpg", "gif", "bmp", "tif", "tiff", "png" };
         // This Hashmap contains List of Rectangles, allowing me to link images to collections of rectangles through the value 'index'.
         public static HashMap<Integer, List<Rectangle>> collection = new HashMap<Integer, List<Rectangle>>();
         BufferedImage currentImage;
         Thread thread;
         Integer index = 0;
         OverlayLayout overlay;
         private TopPanel top;
         private JPanel pictureFrame;
         String newline = System.getProperty("line.separator");
          * Creates new form Object_Marker
          * @throws IOException
         public ObjectMarker(File directory) {
              System.out.println("Got in...");
              this.directory = directory;
              File[] temp = directory.listFiles();
              directory_path = directory.getPath();
              // Add all the image files in the directory to the linked list for easy
              // iteration.
              for (File file : temp) {
                   if (isImage(file)) {
                        file_list.add(file);
              initComponents();
              try {
                   currentImage = ImageIO.read(file_list.get(index));
              } catch (IOException e) {
                   System.out.println("There was a problem loading the image.");
              // 55 pixels offsets the height of the JMenuBar and the title bar
              // which are included in the size of the JFrame.
              this.setSize(currentImage.getWidth(), currentImage.getHeight() + 55);
         public String getImageList() {
              // Allows me to build the string gradually.
              StringBuffer list = new StringBuffer();
              list.append("Image files found in directory: \n\n");
              for (int i = 0; i < file_list.size(); i++) {
                   list.append((((File) file_list.get(i))).getName() + "\n");
              return list.toString();
         private void initComponents() {
              top = new TopPanel();
              pictureFrame = new javax.swing.JPanel();
              OverlayLayout ol = new OverlayLayout(this);
              this.setLayout(ol);
              this.add(top);
              this.add(pictureFrame);
          * private void initComponents() {
          * javax.swing.GroupLayout pictureFrameLayout = new
          * javax.swing.GroupLayout(pictureFrame);
          * pictureFrame.setLayout(pictureFrameLayout);
          * pictureFrameLayout.setHorizontalGroup(
          * pictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addGap(0, 497, Short.MAX_VALUE) ); pictureFrameLayout.setVerticalGroup(
          * pictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addGap(0, 394, Short.MAX_VALUE) );
          * javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
          * this.setLayout(layout); layout.setHorizontalGroup(
          * layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addComponent(pictureFrame, javax.swing.GroupLayout.DEFAULT_SIZE,
          * javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) );
          * layout.setVerticalGroup(
          * layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          * .addComponent(pictureFrame, javax.swing.GroupLayout.DEFAULT_SIZE,
          * javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }
          * This function returns the extension of a given file, for example "jpg" or
          * "gif"
          * @param f
          *            The file to examine
          * @return String containing extension
         public static String getExtension(File f) {
              String ext = null;
              String s = f.getName();
              int i = s.lastIndexOf('.');
              if (i > 0 && i < s.length() - 1) {
                   ext = s.substring(i + 1).toLowerCase();
              } else {
                   ext = "";
              return ext;
         public String getDetails() {
              saveRectangles();
              StringBuffer sb = new StringBuffer();
              for (int i = 0; i < file_list.size(); i++) {
                   try{
                   int count = collection.get(i).size();
                   if (count > 0) {
                        sb.append(file_list.get(i).getPath() + " "); // Add the
                        // filename of
                        // the file
                        sb.append(count + " "); // Add the number of rectangles
                        for (int j = 0; j < collection.get(i).size(); j++) {
                             Rectangle current = collection.get(i).get(j);
                             String coordinates = (int) current.getMinX() + " "
                                       + (int) current.getMinY() + " ";
                             String size = ((int) current.getMaxX() - (int) current
                                       .getMinX())
                                       + " "
                                       + ((int) current.getMaxY() - (int) current
                                                 .getMinY()) + " ";
                             String result = coordinates + size;
                             sb.append(result);
                        sb.append(newline);
                   } catch (NullPointerException e){
                        // Do nothing.  "int count = collection.get(i).size();"
                        // will try to over count.
              return sb.toString();
         private boolean isImage(File f) {
              List<String> list = Arrays.asList(filetypes);
              String extension = getExtension(f);
              if (list.contains(extension)) {
                   return true;
              return false;
         /** Draw the image on the panel. * */
         public void paint(Graphics g) {
              if (currentImage == null) {
                   g.drawString("No image to display!", 300, 240);
              } else {
                   // Draw the image
                   g.drawImage(currentImage, 0, 0, this);
                   // Write the index
                   g.setFont(big);
                   g.drawString(index + 1 + "/" + file_list.size(), 10, 25);
         public void nextImage() throws IOException {
              if (index < file_list.size() - 1) {
                   printOutContents();
                   System.out.println("Index: " + index);
                   saveRectangles();
                   index++;
                   currentImage = ImageIO.read(file_list.get(index));
                   this
                             .setSize(currentImage.getWidth(),
                                       currentImage.getHeight() + 55);
                   top.setSize(this.getSize());
                   top.rectangle_list.clear();
                   if (collection.size() > index) {
                        loadRectangles();
                   repaint();
         private void saveRectangles() {
              // If the current image's rectangles have not been changed, don't do
              // anything.
              if (collection.containsKey(index)) {
                   System.out.println("Removing Index: " + index);
                   collection.remove(index);
              collection.put(index, top.getRectangleList());
              System.out.println("We just saved " + collection.get(index).size()
                        + " rectangles");
              System.out.println("They were saved in HashMap Location " + index);
              System.out.println("Proof: ");
              List<Rectangle> temp = collection.get(index);
              for (int i = 0; i < temp.size(); i++) {
                   System.out.println("Rectangle " + (i + 1) + ": " + temp.get(i));
              // If the rectangle list has changed, set the list the current index
              // as the new list.
         private void loadRectangles() {
              System.out.println("We just loaded index " + index
                        + " into temporary memory.");
              System.out.println("Proof: ");
              List<Rectangle> temp = collection.get(index);
              top.rectangle_list = collection.get(index);
              for (int i = 0; i < temp.size(); i++) {
                   System.out.println("Rectangle " + (i + 1) + ": " + temp.get(i));
         private void printOutContents() {
              System.out.println();
              System.out.println("Contents printout...");
              for (int i = 0; i < collection.size(); i++) {
                   for (Rectangle r : collection.get(i)) {
                        System.out.println("In collection index: " + i + " Rectangle "
                                  + r.toString());
              System.out.println();
         public void previousImage() throws IOException {
              if (index >= 1) {
                   printOutContents();
                   System.out.println("Index: " + index);
                   saveRectangles();
                   index--;
                   currentImage = ImageIO.read(file_list.get(index));
                   this
                             .setSize(currentImage.getWidth(),
                                       currentImage.getHeight() + 55);
                   top.setSize(this.getSize());
                   top.rectangle_list.clear();
                   if (index >= 0) {
                        loadRectangles();
                   repaint();
         public void removeLastRectangle() {
              // This method removes the most recent rectangle added.
              try {
                   int length = collection.get(index).size();
                   collection.get(index).remove(length - 1);
              } catch (NullPointerException e) {
                   try {
                        top.rectangle_list.remove(top.rectangle_list.size() - 1);
                   } catch (IndexOutOfBoundsException ioobe) {
                        JOptionPane.showMessageDialog(this, "Cannot undo any more!");
    * Class developed from SSCCE found on Java forum:
    * http://forum.java.sun.com/thread.jspa?threadID=647074&messageID=3817479
    * @author 74philip
    class TopPanel extends JPanel {
         List<Rectangle> rectangle_list;
         private static final long serialVersionUID = 6208367976334130998L;
         Point loc;
         int width, height, arcRadius;
         Rectangle temp; // for mouse ops in TopRanger
         public TopPanel() {
              setOpaque(false);
              rectangle_list = Collections
                        .synchronizedList(new LinkedList<Rectangle>());
              TopRanger ranger = new TopRanger(this);
              addMouseListener(ranger);
              addMouseMotionListener(ranger);
         public List<Rectangle> getRectangleList() {
              List<Rectangle> temporary = Collections
                        .synchronizedList(new LinkedList<Rectangle>());
              temporary.addAll(rectangle_list);
              return temporary;
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
              g2.setPaint(Color.red);
              // Draw all the rectangles in the rectangle list.
              for (int i = 0; i < rectangle_list.size(); i++) {
                   g2.drawRect(rectangle_list.get(i).x, rectangle_list.get(i).y,
                             rectangle_list.get(i).width, rectangle_list.get(i).height);
              if (temp != null) {
                   g2.draw(temp);
         public void loadRectangleList(List<Rectangle> list) {
              rectangle_list.addAll(list);
         public void addRectangle(Rectangle r) {
              rectangle_list.add(r);
    class TopRanger extends MouseInputAdapter {
         TopPanel top;
         Point offset;
         boolean dragging;
         public TopRanger(TopPanel top) {
              this.top = top;
              dragging = false;
         public void mousePressed(MouseEvent e) {
              Point p = e.getPoint();
              top.temp = new Rectangle(p, new Dimension(0, 0));
              offset = new Point();
              dragging = true;
              top.repaint();
         public void mouseReleased(MouseEvent e) {
              dragging = false;
              // update top.r
              System.out.println(top.getRectangleList().size() + ": Object added: "
                        + top.temp.toString());
              top.addRectangle(top.temp);
              top.repaint();
         public void mouseDragged(MouseEvent e) {
              if (dragging) {
                   top.temp.setBounds(top.temp.x, top.temp.y, e.getX() - top.temp.x, e
                             .getY()
                             - top.temp.y);
                   top.repaint();
    }Regards,
    Eric

    Alright so I fixed it! I created a new class called BottomPanel extends JPanel, which I then gave the responsibility of drawing the image. I gave it an update method which took the details of the currentImage and displayed it on the screen.
    If anybody's interested I also discovered/solved a problem with my mouseListener - I couldn't drag backwards. I fixed this by adding tests looking for negative widths and heights. I compensated accordingly by reseting the rectangle origin to e.getX(), e.getY() and by setting the to original_origin.x - e.getX() and original_origin.y - e.getY().
    No problem!

  • Remove component from JFrame with absolute layout

    I have a JFrame and JPanel inside the JFrame with absolute layout. I wanted to have a button when clicked the JPanel will be removed. I called jFrame.remove(jPanel);
    jFrame.repaint();
    jFrame.validate();
    I can't call jFrame.revalidate(), since JFrame doesn't provide revalidate() method. I try everything, but I can't get that JPanel removed. Could somebody help me please. Oh I tried jPanel.setBounds( 0,0,0,0); and the jPanel is disappeared, but I don't think this is the right solution. Is my problem with the absolute layout?
    Thanks

    public class MainGame
         public void game()
              GridBagLayout gridBagLayout = new GridBagLayout();
              GridBagConstraints constraints = new GridBagConstraints();
              final MainFrame mainFrame = new MainFrame();
              mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              mainFrame.setLayout( gridBagLayout );
              JPanel mainGamePanel = new JPanel();
              mainGamePanel.setLayout( new BorderLayout() );
              mainGamePanel.setBackground( Color.black );
              final Room mainEntrance = new Room( "at the main entrance of the deep forest" );
              mainEntrance.setBackground( Color.white );
              mainEntrance.setLayout( null );
              mainEntrance.setExit( Direction.UP, null );
              mainGamePanel.add( mainEntrance, BorderLayout.CENTER );
    //          c.fill = GridBagConstraints.CENTER;
              constraints.ipady = 800;      //make this component tall
              constraints.ipadx = 600;
              constraints.anchor = GridBagConstraints.WEST;
              constraints.gridx = 0;
              constraints.gridy = 0;
              gridBagLayout.setConstraints( mainGamePanel, constraints );
              mainFrame.getContentPane().add( mainGamePanel );
              thePlayer = new Human( "Cloud" , "The player" );
              thePlayer.setMaximumWeight( MAXIMUM_WEIGHT );
              thePlayer.setImage( Constants.CHARACTER_FRONT );
              thePlayer.setBounds(0 , 0, 40, 30 );
              thePlayer.setBorder( BorderFactory.createLineBorder( Color.black ) );
              mainEntrance.add( thePlayer );
              apple = new EdibleItem( "apple" , "Give more 10 HP" );
              apple.setHp( 100 );
              apple.setImage( Constants.APPLE );
              apple.setBounds( 40, 0, 40, 30 );
              apple.setBorder( BorderFactory.createLineBorder( Color.black ) );
              mainEntrance.add( apple );
              thePlayer.addItem( apple );
              apple1 = new JPanelWithBackground();
              apple1.setImage( Constants.APPLE );
              apple1.setBounds( 80, 60, 40, 30 );
              apple1.setBorder( BorderFactory.createLineBorder( Color.black ) );
              mainEntrance.add( apple1 );
    //          final Room forest = new Room( "at the main entrance of the deep forest" );
    //          forest.setBounds( 0, 0, 800, 600 );
    //          forest.setBackground( Color.white );
    //          forest.setLayout( null );
    //          forest.setExit( Direction.UP, null );
    //          // Add to list
              listOfItems.add( apple );
              listOfItems.add( apple1 );
               * Main Control Panel to control character and actions
              JPanel controlPanel = new JPanel();
              controlPanel.setBackground( Color.black );
              controlPanel.setBounds( 1000, 0, 600, 600 );
              controlPanel.setLayout( new GridLayout( 0, 1 ) );
              JButton eatButton = new JButton( "EAT" );
              // Set this button to setFocusable(false) to prevent this button being focused
              // So the focus will stay at JFrame
              eatButton.setFocusable( false );
              eatButton.addActionListener( new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent e)
                        JPanelWithBackground currentObject = mainGame.getFacingObject();
                        if( currentObject instanceof EdibleItem )
                             //EdibleItem apple = ( EdibleItem )currentObject;
              controlPanel.add( eatButton );
              JButton attackButton = new JButton( "ATTACK" );
              attackButton.setFocusable( false );
              attackButton.addActionListener( new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent e)
                        System.out.println( "Remove" );
                        mainFrame.getContentPane().remove( mainEntrance );
                        mainEntrance.setBounds( 0,0,0,0);
    //                    mainFrame.add( forest );
                        mainFrame.validate();
                        mainFrame.repaint();
              controlPanel.add( attackButton );
              mainFrame.setVisible( true );
              mainFrame.requestFocusInWindow();
    }I know that my code is a mess, because it is connected with many classes and the quality of the format is not very good. But I will refactor it later when I solved the problem.
    The problem is I have a JPanel with a character and an apple in it. I could not use any other layout, I have to use absolute layout, because I the user can control the character but arrow keys. And the character moves in pixels.
    Here what I wanted to do.
    final Room mainEntrance = new Room( "at the main entrance of the deep forest" );
              mainEntrance.setBackground( Color.white );
              mainEntrance.setLayout( null );
              mainEntrance.setExit( Direction.UP, null );Room extends JPanel, I wanted to delete this panel when I clicked this button
              JButton attackButton = new JButton( "ATTACK" );
              attackButton.setFocusable( false );
              attackButton.addActionListener( new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent e)
                        System.out.println( "Remove" );
                        mainFrame.getContentPane().remove( mainEntrance );
                        mainEntrance.setBounds( 0,0,0,0);
    //                    mainFrame.add( forest );
                        mainFrame.validate();
                        mainFrame.repaint();
              controlPanel.add( attackButton );Like I said before, I tried validate, repaint and setBounds to all 0s. Nothing happened with the Room class. How do I delete that Room.
    Thank you so much.

  • Is it possible to create a menu structure within iWeb with a so called tree layout? iWeb only provides automatically a horizontal layout

    Is it possible to create a menu structure within iWeb with a so called tree layout? iWeb only provides automatically a horizontal layout

    Not in iWeb itself.
    You have to create these menus yourself. Start here :
         A List Apart: Articles: Suckerfish Dropdowns
    Also, see podcast episode 9 of
         CSS Tricks and Tips
    and then add them to a webpage with the HTML Snippet.
    Or add the menu to the webpage with a JavaScript.
    Here's a sample page :
         http://www.wyodor.net/mfi/roodhout/
         http://www.wyodor.net/mfi/spelling/
         http://www.wyodor.net/mfi/Maaskant/Some_Menus.html
    The how-to-do page are here and here.
    More sample pages on my Made for iPad with iWeb pages.
         http://www.wyodor.net/mfi/
    You may have to learn HTML, CSS, JavaScript, AJAX, DOM and how iWeb creates its pages.

  • Custom ui component with default layout

    Hello,
    I am trying to develop custom swing components with default layout set.
    Both component class and its BeanInfo are written with NetBeans 6.1
    However, when trying to put this custom swing component into interface builder (matisse) of
    NetBeans 6.1, the default layout is always replaced with GroupLayout.
    Is there any way to correctly specify default layout manager used in a custom
    swing component?
    thanks a lot!

    Hi Jacek
    You can embed your custom component with IFrame element in WebDynpro view. IFrame element loads a content by URL which can be bound to controller's context. You can store your custom HTML content in MIME folder of the WebDynpro component. At runtime you can get the URL to the MIME content and initialize the IFrame with the URL.
    However, IFrame element is being reloaded by WebDynpro framework too often during each request/response cycle. This is a disadvantage of the solution.
    BR, Siarhei

  • JTabbedPane with close Icons

    Ok, so I was trying to get a JTabbedPane with 'X' icons on each tab. Searched this site, and found no answers, but loads of questions on how to do it. I've done it now, and here's my code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * A JTabbedPane which has a close ('X') icon on each tab.
    * To add a tab, use the method addTab(String, Component)
    * To have an extra icon on each tab (e.g. like in JBuilder, showing the file type) use
    * the method addTab(String, Component, Icon). Only clicking the 'X' closes the tab.
    public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListener {
      public JTabbedPaneWithCloseIcons() {
        super();
        addMouseListener(this);
      public void addTab(String title, Component component) {
        this.addTab(title, component, null);
      public void addTab(String title, Component component, Icon extraIcon) {
        super.addTab(title, new CloseTabIcon(extraIcon), component);
      public void mouseClicked(MouseEvent e) {
        int tabNumber=getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) return;
        Rectangle rect=((CloseTabIcon)getIconAt(tabNumber)).getBounds();
        if (rect.contains(e.getX(), e.getY())) {
          //the tab is being closed
          this.removeTabAt(tabNumber);
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
    * The class which generates the 'X' icon for the tabs. The constructor
    * accepts an icon which is extra to the 'X' icon, so you can have tabs
    * like in JBuilder. This value is null if no extra icon is required.
    class CloseTabIcon implements Icon {
      private int x_pos;
      private int y_pos;
      private int width;
      private int height;
      private Icon fileIcon;
      public CloseTabIcon(Icon fileIcon) {
        this.fileIcon=fileIcon;
        width=16;
        height=16;
      public void paintIcon(Component c, Graphics g, int x, int y) {
        this.x_pos=x;
        this.y_pos=y;
        Color col=g.getColor();
        g.setColor(Color.black);
        int y_p=y+2;
        g.drawLine(x+1, y_p, x+12, y_p);
        g.drawLine(x+1, y_p+13, x+12, y_p+13);
        g.drawLine(x, y_p+1, x, y_p+12);
        g.drawLine(x+13, y_p+1, x+13, y_p+12);
        g.drawLine(x+3, y_p+3, x+10, y_p+10);
        g.drawLine(x+3, y_p+4, x+9, y_p+10);
        g.drawLine(x+4, y_p+3, x+10, y_p+9);
        g.drawLine(x+10, y_p+3, x+3, y_p+10);
        g.drawLine(x+10, y_p+4, x+4, y_p+10);
        g.drawLine(x+9, y_p+3, x+3, y_p+9);
        g.setColor(col);
        if (fileIcon != null) {
          fileIcon.paintIcon(c, g, x+width, y_p);
      public int getIconWidth() {
        return width + (fileIcon != null? fileIcon.getIconWidth() : 0);
      public int getIconHeight() {
        return height;
      public Rectangle getBounds() {
        return new Rectangle(x_pos, y_pos, width, height);
    }You can also specify an extra icon to put on each tab. Read my comments on how to do it.

    With the following code you'll be able to have use SCROLL_TAB_LAYOUT and WRAP_TAB_LAYOUT. With setCloseIcons() you'll be able to set images for the close-icons.
    The TabbedPane:
    import javax.swing.Icon;
    import javax.swing.JComponent;
    import javax.swing.JTabbedPane;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.event.EventListenerList;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import javax.swing.plaf.metal.MetalTabbedPaneUI;
    * A JTabbedPane which has a close ('X') icon on each tab.
    * To add a tab, use the method addTab(String, Component)
    * To have an extra icon on each tab (e.g. like in JBuilder, showing the file
    * type) use the method addTab(String, Component, Icon). Only clicking the 'X'
    * closes the tab.
    public class CloseableTabbedPane extends JTabbedPane implements MouseListener,
      MouseMotionListener {
       * The <code>EventListenerList</code>.
      private EventListenerList listenerList = null;
       * The viewport of the scrolled tabs.
      private JViewport headerViewport = null;
       * The normal closeicon.
      private Icon normalCloseIcon = null;
       * The closeicon when the mouse is over.
      private Icon hooverCloseIcon = null;
       * The closeicon when the mouse is pressed.
      private Icon pressedCloseIcon = null;
       * Creates a new instance of <code>CloseableTabbedPane</code>
      public CloseableTabbedPane() {
        super();
        init(SwingUtilities.LEFT);
       * Creates a new instance of <code>CloseableTabbedPane</code>
       * @param horizontalTextPosition the horizontal position of the text (e.g.
       * SwingUtilities.TRAILING or SwingUtilities.LEFT)
      public CloseableTabbedPane(int horizontalTextPosition) {
        super();
        init(horizontalTextPosition);
       * Initializes the <code>CloseableTabbedPane</code>
       * @param horizontalTextPosition the horizontal position of the text (e.g.
       * SwingUtilities.TRAILING or SwingUtilities.LEFT)
      private void init(int horizontalTextPosition) {
        listenerList = new EventListenerList();
        addMouseListener(this);
        addMouseMotionListener(this);
        if (getUI() instanceof MetalTabbedPaneUI)
          setUI(new CloseableMetalTabbedPaneUI(horizontalTextPosition));
        else
          setUI(new CloseableTabbedPaneUI(horizontalTextPosition));
       * Allows setting own closeicons.
       * @param normal the normal closeicon
       * @param hoover the closeicon when the mouse is over
       * @param pressed the closeicon when the mouse is pressed
      public void setCloseIcons(Icon normal, Icon hoover, Icon pressed) {
        normalCloseIcon = normal;
        hooverCloseIcon = hoover;
        pressedCloseIcon = pressed;
       * Adds a <code>Component</code> represented by a title and no icon.
       * @param title the title to be displayed in this tab
       * @param component the component to be displayed when this tab is clicked
      public void addTab(String title, Component component) {
        addTab(title, component, null);
       * Adds a <code>Component</code> represented by a title and an icon.
       * @param title the title to be displayed in this tab
       * @param component the component to be displayed when this tab is clicked
       * @param extraIcon the icon to be displayed in this tab
      public void addTab(String title, Component component, Icon extraIcon) {
        boolean doPaintCloseIcon = true;
        try {
          Object prop = null;
          if ((prop = ((JComponent) component).
                        getClientProperty("isClosable")) != null) {
            doPaintCloseIcon = (Boolean) prop;
        } catch (Exception ignored) {/*Could probably be a ClassCastException*/}
        super.addTab(title,
                     doPaintCloseIcon ? new CloseTabIcon(extraIcon) : null,
                     component);
        if (headerViewport == null) {
          for (Component c : getComponents()) {
            if ("TabbedPane.scrollableViewport".equals(c.getName()))
              headerViewport = (JViewport) c;
       * Invoked when the mouse button has been clicked (pressed and released) on
       * a component.
       * @param e the <code>MouseEvent</code>
      public void mouseClicked(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when the mouse enters a component.
       * @param e the <code>MouseEvent</code>
      public void mouseEntered(MouseEvent e) { }
       * Invoked when the mouse exits a component.
       * @param e the <code>MouseEvent</code>
      public void mouseExited(MouseEvent e) {
        for (int i=0; i<getTabCount(); i++) {
          CloseTabIcon icon = (CloseTabIcon) getIconAt(i);
          if (icon != null)
            icon.mouseover = false;
        repaint();
       * Invoked when a mouse button has been pressed on a component.
       * @param e the <code>MouseEvent</code>
      public void mousePressed(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when a mouse button has been released on a component.
       * @param e the <code>MouseEvent</code>
      public void mouseReleased(MouseEvent e) { }
       * Invoked when a mouse button is pressed on a component and then dragged.
       * <code>MOUSE_DRAGGED</code> events will continue to be delivered to the
       * component where the drag originated until the mouse button is released
       * (regardless of whether the mouse position is within the bounds of the
       * component).<br/>
       * <br/>
       * Due to platform-dependent Drag&Drop implementations,
       * <code>MOUSE_DRAGGED</code> events may not be delivered during a native
       * Drag&Drop operation.
       * @param e the <code>MouseEvent</code>
      public void mouseDragged(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when the mouse cursor has been moved onto a component but no
       * buttons have been pushed.
       * @param e the <code>MouseEvent</code>
      public void mouseMoved(MouseEvent e) {
        processMouseEvents(e);
       * Processes all caught <code>MouseEvent</code>s.
       * @param e the <code>MouseEvent</code>
      private void processMouseEvents(MouseEvent e) {
        int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) return;
        CloseTabIcon icon = (CloseTabIcon) getIconAt(tabNumber);
        if (icon != null) {
          Rectangle rect= icon.getBounds();
          Point pos = headerViewport == null ?
                      new Point() : headerViewport.getViewPosition();
          Rectangle drawRect = new Rectangle(
            rect.x - pos.x, rect.y - pos.y, rect.width, rect.height);
          if (e.getID() == e.MOUSE_PRESSED) {
            icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
            repaint(drawRect);
          } else if (e.getID() == e.MOUSE_MOVED || e.getID() == e.MOUSE_DRAGGED ||
                     e.getID() == e.MOUSE_CLICKED) {
            pos.x += e.getX();
            pos.y += e.getY();
            if (rect.contains(pos)) {
              if (e.getID() == e.MOUSE_CLICKED) {
                int selIndex = getSelectedIndex();
                if (fireCloseTab(selIndex)) {
                  if (selIndex > 0) {
                    // to prevent uncatchable null-pointers
                    Rectangle rec = getUI().getTabBounds(this, selIndex - 1);
                    MouseEvent event = new MouseEvent((Component) e.getSource(),
                                                      e.getID() + 1,
                                                      System.currentTimeMillis(),
                                                      e.getModifiers(),
                                                      rec.x,
                                                      rec.y,
                                                      e.getClickCount(),
                                                      e.isPopupTrigger(),
                                                      e.getButton());
                    dispatchEvent(event);
                  //the tab is being closed
                  //removeTabAt(tabNumber);
                  remove(selIndex);
                } else {
                  icon.mouseover = false;
                  icon.mousepressed = false;
                  repaint(drawRect);
              } else {
                icon.mouseover = true;
                icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
            } else {
              icon.mouseover = false;
            repaint(drawRect);
       * Adds an <code>CloseableTabbedPaneListener</code> to the tabbedpane.
       * @param l the <code>CloseableTabbedPaneListener</code> to be added
      public void addCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
        listenerList.add(CloseableTabbedPaneListener.class, l);
       * Removes an <code>CloseableTabbedPaneListener</code> from the tabbedpane.
       * @param l the listener to be removed
      public void removeCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
        listenerList.remove(CloseableTabbedPaneListener.class, l);
       * Returns an array of all the <code>SearchListener</code>s added to this
       * <code>SearchPane</code> with addSearchListener().
       * @return all of the <code>SearchListener</code>s added or an empty array if
       * no listeners have been added
      public CloseableTabbedPaneListener[] getCloseableTabbedPaneListener() {
        return listenerList.getListeners(CloseableTabbedPaneListener.class);
       * Notifies all listeners that have registered interest for notification on
       * this event type.
       * @param tabIndexToClose the index of the tab which should be closed
       * @return true if the tab can be closed, false otherwise
      protected boolean fireCloseTab(int tabIndexToClose) {
        boolean closeit = true;
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        for (Object i : listeners) {
          if (i instanceof CloseableTabbedPaneListener) {
            if (!((CloseableTabbedPaneListener) i).closeTab(tabIndexToClose)) {
              closeit = false;
              break;
        return closeit;
       * The class which generates the 'X' icon for the tabs. The constructor
       * accepts an icon which is extra to the 'X' icon, so you can have tabs
       * like in JBuilder. This value is null if no extra icon is required.
      class CloseTabIcon implements Icon {
         * the x position of the icon
        private int x_pos;
         * the y position of the icon
        private int y_pos;
         * the width the icon
        private int width;
         * the height the icon
        private int height;
         * the additional fileicon
        private Icon fileIcon;
         * true whether the mouse is over this icon, false otherwise
        private boolean mouseover = false;
         * true whether the mouse is pressed on this icon, false otherwise
        private boolean mousepressed = false;
         * Creates a new instance of <code>CloseTabIcon</code>
         * @param fileIcon the additional fileicon, if there is one set
        public CloseTabIcon(Icon fileIcon) {
          this.fileIcon = fileIcon;
          width  = 16;
          height = 16;
         * Draw the icon at the specified location. Icon implementations may use the
         * Component argument to get properties useful for painting, e.g. the
         * foreground or background color.
         * @param c the component which the icon belongs to
         * @param g the graphic object to draw on
         * @param x the upper left point of the icon in the x direction
         * @param y the upper left point of the icon in the y direction
        public void paintIcon(Component c, Graphics g, int x, int y) {
          boolean doPaintCloseIcon = true;
          try {
            // JComponent.putClientProperty("isClosable", new Boolean(false));
            JTabbedPane tabbedpane = (JTabbedPane) c;
            int tabNumber = tabbedpane.getUI().tabForCoordinate(tabbedpane, x, y);
            JComponent curPanel = (JComponent) tabbedpane.getComponentAt(tabNumber);
            Object prop = null;
            if ((prop = curPanel.getClientProperty("isClosable")) != null) {
              doPaintCloseIcon = (Boolean) prop;
          } catch (Exception ignored) {/*Could probably be a ClassCastException*/}
          if (doPaintCloseIcon) {
            x_pos = x;
            y_pos = y;
            int y_p = y + 1;
            if (normalCloseIcon != null && !mouseover) {
              normalCloseIcon.paintIcon(c, g, x, y_p);
            } else if (hooverCloseIcon != null && mouseover && !mousepressed) {
              hooverCloseIcon.paintIcon(c, g, x, y_p);
            } else if (pressedCloseIcon != null && mousepressed) {
              pressedCloseIcon.paintIcon(c, g, x, y_p);
            } else {
              y_p++;
              Color col = g.getColor();
              if (mousepressed && mouseover) {
                g.setColor(Color.WHITE);
                g.fillRect(x+1, y_p, 12, 13);
              g.setColor(Color.black);
              g.drawLine(x+1, y_p, x+12, y_p);
              g.drawLine(x+1, y_p+13, x+12, y_p+13);
              g.drawLine(x, y_p+1, x, y_p+12);
              g.drawLine(x+13, y_p+1, x+13, y_p+12);
              g.drawLine(x+3, y_p+3, x+10, y_p+10);
              if (mouseover)
                g.setColor(Color.GRAY);
              g.drawLine(x+3, y_p+4, x+9, y_p+10);
              g.drawLine(x+4, y_p+3, x+10, y_p+9);
              g.drawLine(x+10, y_p+3, x+3, y_p+10);
              g.drawLine(x+10, y_p+4, x+4, y_p+10);
              g.drawLine(x+9, y_p+3, x+3, y_p+9);
              g.setColor(col);
              if (fileIcon != null) {
                fileIcon.paintIcon(c, g, x+width, y_p);
         * Returns the icon's width.
         * @return an int specifying the fixed width of the icon.
        public int getIconWidth() {
          return width + (fileIcon != null ? fileIcon.getIconWidth() : 0);
         * Returns the icon's height.
         * @return an int specifying the fixed height of the icon.
        public int getIconHeight() {
          return height;
         * Gets the bounds of this icon in the form of a <code>Rectangle<code>
         * object. The bounds specify this icon's width, height, and location
         * relative to its parent.
         * @return a rectangle indicating this icon's bounds
        public Rectangle getBounds() {
          return new Rectangle(x_pos, y_pos, width, height);
       * A specific <code>BasicTabbedPaneUI</code>.
      class CloseableTabbedPaneUI extends BasicTabbedPaneUI {
        * the horizontal position of the text
        private int horizontalTextPosition = SwingUtilities.LEFT;
         * Creates a new instance of <code>CloseableTabbedPaneUI</code>
        public CloseableTabbedPaneUI() {
         * Creates a new instance of <code>CloseableTabbedPaneUI</code>
         * @param horizontalTextPosition the horizontal position of the text (e.g.
         * SwingUtilities.TRAILING or SwingUtilities.LEFT)
        public CloseableTabbedPaneUI(int horizontalTextPosition) {
          this.horizontalTextPosition = horizontalTextPosition;
         * Layouts the label
         * @param tabPlacement the placement of the tabs
         * @param metrics the font metrics
         * @param tabIndex the index of the tab
         * @param title the title of the tab
         * @param icon the icon of the tab
         * @param tabRect the tab boundaries
         * @param iconRect the icon boundaries
         * @param textRect the text boundaries
         * @param isSelected true whether the tab is selected, false otherwise
        protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                                   int tabIndex, String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected) {
          textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
          javax.swing.text.View v = getTextViewForTab(tabIndex);
          if (v != null) {
            tabPane.putClientProperty("html", v);
          SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                             metrics, title, icon,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             //SwingUtilities.TRAILING,
                                             horizontalTextPosition,
                                             tabRect,
                                             iconRect,
                                             textRect,
                                             textIconGap + 2);
          tabPane.putClientProperty("html", null);
          int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
          int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
          iconRect.x += xNudge;
          iconRect.y += yNudge;
          textRect.x += xNudge;
          textRect.y += yNudge;
       * A specific <code>MetalTabbedPaneUI</code>.
      class CloseableMetalTabbedPaneUI extends MetalTabbedPaneUI {
        * the horizontal position of the text
        private int horizontalTextPosition = SwingUtilities.LEFT;
         * Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
        public CloseableMetalTabbedPaneUI() {
         * Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
         * @param horizontalTextPosition the horizontal position of the text (e.g.
         * SwingUtilities.TRAILING or SwingUtilities.LEFT)
        public CloseableMetalTabbedPaneUI(int horizontalTextPosition) {
          this.horizontalTextPosition = horizontalTextPosition;
         * Layouts the label
         * @param tabPlacement the placement of the tabs
         * @param metrics the font metrics
         * @param tabIndex the index of the tab
         * @param title the title of the tab
         * @param icon the icon of the tab
         * @param tabRect the tab boundaries
         * @param iconRect the icon boundaries
         * @param textRect the text boundaries
         * @param isSelected true whether the tab is selected, false otherwise
        protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                                   int tabIndex, String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected) {
          textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
          javax.swing.text.View v = getTextViewForTab(tabIndex);
          if (v != null) {
            tabPane.putClientProperty("html", v);
          SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                             metrics, title, icon,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             //SwingUtilities.TRAILING,
                                             horizontalTextPosition,
                                             tabRect,
                                             iconRect,
                                             textRect,
                                             textIconGap + 2);
          tabPane.putClientProperty("html", null);
          int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
          int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
          iconRect.x += xNudge;
          iconRect.y += yNudge;
          textRect.x += xNudge;
          textRect.y += yNudge;
    }The Listener:
    import java.util.EventListener;
    * The listener that's notified when an tab should be closed in the
    * <code>CloseableTabbedPane</code>.
    public interface CloseableTabbedPaneListener extends EventListener {
       * Informs all <code>CloseableTabbedPaneListener</code>s when a tab should be
       * closed
       * @param tabIndexToClose the index of the tab which should be closed
       * @return true if the tab can be closed, false otherwise
      boolean closeTab(int tabIndexToClose);
    }

  • JTabbedPane with FormLayout problems

    I created form which contain JTabbedPane within JPanel with FormLayout. In the JTabbedPane, I put JPanel with FormLayout. In Design Mode, there is nothing problem, I can put whatever item into the JPanel of JTabbedPane. But in Runtime Mode, JTabbedPane display nothing, many items I've put on it are not displayed. But when I change the Layout into another like XY Layout or FlowLayout, items are displayed correctly.
    any idea to solve this?
    and why JDeveloper doesn't implement SpringLayout?

    Hi user567546, i faced the same problem.
    Fortunately, I solved it by using PanelBuilder instead of Panel,
    take a look at this example:
    http://www.java2s.com/Code/Java/Swing-Components/DemonstratesthebasicFormLayoutsizesconstantminimumpreferred.htm
    Regards,
    Luis R.

  • How to center components horizontally in container with SpringLayout layout

    Hello,
    I've got a button and a text field in container with SpringLayout layout set. How can I center text field horizontally (buttong is the highest component)?
    I don't want use hacks like settings all heights manually.
    With regards,
    Pavel Krupets

    Sorry vertically!!!

  • Tool bar dock problem with grid layout

    I have a tool bar with grid layout. When i dock it to vertical location(west or east) the buttons inside tool bar keep one row. I want to know how do i do to make the buttons arraged vertically like the tool bar with default layout when dock it at west or east position.

    I had started a custom layout manager for toolbars a few months ago that I found a little easier to use than the default BoxLayout. I just modified it to allow optionally matching the button sizes (width, height, or both), so you can get the same effect as GridLayout. Note that this one doesn't collapse the toolbar like the one in the other thread. Here's the source code as well as a simple test app to demonstrate how to use it. Hope it helps.
    //     TestApp.java
    //     Test application for ToolBarLayout
    // package ***;
    import java.awt.*;
    import javax.swing.*;
    public class TestApp extends JFrame
         /////////////////////// Main Method ///////////////////////
         public static void main(String[] args)
              try { UIManager.setLookAndFeel(
                   UIManager.getSystemLookAndFeelClassName()); }
              catch(Exception ex) { }     
              new TestApp();
         public TestApp()
              setTitle("ToolBarLayout Test");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setSize(400, 300);
              setLocationRelativeTo(null);
              JToolBar tbar = new JToolBar();
              ToolBarLayout layout = new ToolBarLayout(tbar);
              // Comment these two lines out one at a time to see
              // how they affect the toolbar's layout...
              layout.setMatchesComponentDepths(true);
              layout.setMatchesComponentLengths(true);
              tbar.setLayout(layout);
              tbar.add(new JButton("One"));
              tbar.add(new JButton("Two"));
              tbar.add(new JButton("Three"));
              tbar.addSeparator();
              tbar.add(new JButton("Musketeers"));
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              c.add(tbar, BorderLayout.NORTH);
              setVisible(true);
    //     ToolBarLayout.java
    //     A simple layout manager for JToolBars.  Optionally resizes buttons to
    //     equal width or height based on the maximum preferred width or height
    //     of all components.
    // package ***;
    import java.awt.*;
    import javax.swing.*;
    public class ToolBarLayout implements LayoutManager, SwingConstants
         private JToolBar     oToolBar = null;
         private boolean     oMatchDepth = false;
         private boolean     oMatchLength = false;
         private int          oGap = 0;
         public ToolBarLayout(JToolBar toolBar)
              oToolBar = toolBar;
         public ToolBarLayout(JToolBar toolBar, boolean matchDepths)
              oToolBar = toolBar;
              oMatchDepth = matchDepths;
         public ToolBarLayout(JToolBar toolBar,
                        boolean matchDepths,
                             boolean matchLengths)
              oToolBar = toolBar;
              oMatchDepth = matchDepths;
              oMatchLength = matchLengths;
         // If true, all buttons in the row will be sized to
         // the same height (assuming horizontal orientation)
         public void setMatchesComponentDepths(boolean match)
              oMatchDepth = match;
         // If true, all buttons in the row will be sized to
         // the same width (assuming horizontal orientation)
         public void setMatchesComponentLengths(boolean match)
              oMatchLength = match;
         public void setSpacing(int spacing)
              oGap = Math.max(0, spacing);
         public int getSpacing()
              return oGap;
         ////// LayoutManager implementation //////
         public void addLayoutComponent(String name, Component comp) { }
         public void removeLayoutComponent(Component comp) { }
         public Dimension minimumLayoutSize(Container parent)
              return preferredLayoutSize(parent);
         public Dimension preferredLayoutSize(Container parent)
              synchronized (parent.getTreeLock())
                   int orientation = getOrientation();
                   Component[] components = parent.getComponents();
                   int w = 0, h = 0;
                   int totalWidth = 0, totalHeight = 0;
                   int maxW = getMaxPrefWidth(components);
                   int maxH = getMaxPrefHeight(components);
                   Dimension ps = null;
                   if (orientation == HORIZONTAL)
                        for (int i=0; i < components.length; i++)
                             ps = components.getPreferredSize();
                             if (oMatchLength) w = maxW;
                             else w = ps.width;
                             if (oMatchDepth) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = ps.width;
                                  h = 0;
                             totalWidth += w;
                             if (i < components.length - 1)
                                       totalWidth += oGap;
                             totalHeight = Math.max(totalHeight, h);
                   else
                        for (int i=0; i < components.length; i++)
                             ps = components[i].getPreferredSize();
                             if (oMatchDepth) w = maxW;
                             else w = ps.width;
                             if (oMatchLength) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = 0;
                                  h = ps.height;
                             totalHeight += h;
                             if (i < components.length - 1)
                                       totalHeight += oGap;
                             totalWidth = Math.max(totalWidth, w);
                   Insets in = parent.getInsets();
                   totalWidth += in.left + in.right;
                   totalHeight += in.top + in.bottom;
                   return new Dimension(totalWidth, totalHeight);
         public void layoutContainer(Container parent)
              synchronized (parent.getTreeLock())
                   int orientation = getOrientation();
                   Component[] components = parent.getComponents();
                   Insets in = parent.getInsets();
                   int x = in.left, y = in.top;
                   int w = 0, h = 0, maxW = 0, maxH = 0;
                   Dimension ps = null;
                   if (orientation == HORIZONTAL)
                        maxW = getMaxPrefWidth(components);
                        maxH = Math.max( getMaxPrefHeight(components),
                             parent.getHeight() - in.top - in.bottom );
                        for (int i=0; i < components.length; i++)
                             ps = components[i].getPreferredSize();
                             if (oMatchLength) w = maxW;
                             else w = ps.width;
                             if (oMatchDepth) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = ps.width;
                                  h = maxH;
                             components[i].setBounds(
                                  x, y + (maxH-h)/2, w, h);
                             x += w + oGap;
                   else
                        maxH = getMaxPrefHeight(components);
                        maxW = Math.max( getMaxPrefWidth(components),
                             parent.getWidth() - in.left - in.right );
                        for (int i=0; i < components.length; i++)
                             ps = components[i].getPreferredSize();
                             if (oMatchDepth) w = maxW;
                             else w = ps.width;
                             if (oMatchLength) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = maxW;
                                  h = ps.height;
                             components[i].setBounds(
                                  x + (maxW-w)/2, y, w, h);
                             y += h + oGap;
         //// private methods ////
         private int getOrientation()
              if (oToolBar != null) return oToolBar.getOrientation();
              else return HORIZONTAL;
         private int getMaxPrefWidth(Component[] components)
              int maxWidth = 0;
              int componentWidth = 0;
              Dimension d = null;
              for (int i=0; i < components.length; i++)
                   d = components[i].getPreferredSize();
                   componentWidth = d.width;
                   if (components[i] instanceof JSeparator)
                        componentWidth = Math.min(d.width, d.height);
                   maxWidth = Math.max(maxWidth, componentWidth);
              return maxWidth;
         private int getMaxPrefHeight(Component[] components)
              int maxHeight = 0;
              int componentHeight = 0;
              Dimension d = null;
              for (int i=0; i < components.length; i++)
                   d = components[i].getPreferredSize();
                   componentHeight = d.height;
                   if (components[i] instanceof JSeparator)
                        componentHeight = Math.min(d.width, d.height);
                   else maxHeight = Math.max(maxHeight, componentHeight);
              return maxHeight;

  • Color behind the tabbs of JTabbedPane in SCROLL layout

    Hi all, This is a repost as no one gave me a solution for this problem.
    When SCROLL_TAB_LAYOUT is specified, the color behind the tabbs is not the color of its container. With WRAP layout, the color behind the tabbs is the color of its container.
    Is this a bug? or am I doing wrong?
    If one can execute this code, it would be clear of what I am talking about. Just comment out the tabbPane.setTabLayoutPolicy line and run it again to see the actual behaviour.
    JTabbedPane tabbPane = new JTabbedPane();
    tabbPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    tabbPane.setBackground(Color.white);
    tabbPane.add("one",new JPanel());
    tabbPane.add("two",new JPanel());
    JPanel parentPanel = new JPanel(new BorderLayout());
    parentPanel.setBackground(Color.red); // the color i want to be appeared as the background for tabbed pane and not for tabbs.
    parentPanel.add(tabbPane,BorderLayout.CENTER);
    JFrame jf = new JFrame();
    jf.getContentPane().add(parentPanel);
    jf.pack();
    jf.setVisible(true);
    Thanks in advance.

    Maybe this:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4690946
    Bug ID:      4690946
    Votes      6
    Synopsis      REGRESSION: JTabbedPane.setBackground() and setOpaque() have no effect
    Category      java:classes_swing
    Reported Against      1.4
    Release Fixed      1.5(tiger)
    State      Closed, fixed

  • Problems with the Layout Priority in KM

    Hello, I have some problems with the Layout Priority in KM..
    I'm using a KM Navigation Iview with "<i>Layout Set</i>"=NewsBrowser (this Layout Set uses a Collection renderer that sorts the folder's contents by "last modified") and "<i>Layout Set Mode</i>"=exclusive.
    In the KM folder I setted in <i>Details->Settings->Presentation</i> as "<u>rndSortProperty</u>"=name because I need to order my files by FileName property.
    Despite that in see that the contents showed in my iview are ordered by Last Modified...
    The "<i>Layout Set Mode</i>" exclusive gives the higher priority to the Folder Settings..
    I don't understand..
    Thank you in advance.

    Thank you Shyja,
    your post was helpful, but another issue is occurred.
    Maybe en example could be useful..
    My scenario:
    - I need to show a km folder with layout set "<i>ConsumerExplorer</i>" on root folder (no "property of sorting" setted on its collection renderer) and "<i>TabExplorer</i>" (no "property of sorting" setted on its collection renderer).
    - I need to sort files and folders by "last modified". By default seems that they are sorted by "name".
    - With my administrator user I open my folder details (in Content Admin->KM Content is used the Layout "<i>AdminExplorer</i>"), and in "Settings->Presentation->Additional Parameters" I add two parameters "<i>rndSortOrder</i>=descending" and "<i>rndSortProperty</i>=modified" (the others are parameters of AdminExplorer Layout).
    - Then I check "Apply Settings to All Subfolders" and "Use Settings for All iViews (Preferred Presentation)".
    result:
    I see the "<i>ConsumerExplorer</i>" on root folder, the subfolder are sorted by "last modified" (everything ok).
    I click on a subfolder, the "TabExplorer" si showed, the Tabs and the content are sorted by "last modified" BUT..
    .. into the tabs are showed <u>nameFolders</u> (in link style), <u>the action command</u>, and the properties of "<u>author</u>" and "<u>last modified</u>" (normally into the tabs are showed just the folderNames in text style)...
    Why?? Is possible that the "AdminExplorer" parameters of the km folder affect the Tab component??
    Thank you

  • Adobe Content Viewer crashes with particular layout

    Hello all,
    I have two layouts I've added to a folio, the first is a smooth-scrolling layout and the second is a snap-to-page layout. It works perfectly until I add the horizontal layouts of the second set.
    What I found most unusual is that everything works fine viewed vertically, but crashes on trying to view the horizontal layouts ( horizontal layouts uploaded by other team members in the same folio work fine somehow ). It works fine horizontally until I add the second set of layouts. The crashes happen only on the iPad, and works fine viewed on Content Viewer from the desktop. It's not just me either, other members are also having crash issues with my layouts..
    The horizontal layout is identical to the vertical layouts, and I'm not getting any sort of error messages, so I can't tell what's causing the folio to crash. What's going on?

    My folio still does not work. I've isolated the problem to one particular layout. When this article is in landscape layout, it causes the Content Viewer to crash. I have no MSO with the same name, and I've checked all the interactive objects and overlays to see what's causing this problem. It worked perfectly before the update to the new Content Viewer and before I updated the tools. The article also works fine in portrait view, and it has the exact same objects and interactivity. This is extremely frustrating, and I could be looking for hours to find what the problem is. Any help would be greatly appreciated.

  • PartialTrigger point to Component within JSF Fragment

    i like know if it is possible to have component within mainPage.jspx with partialTrigger pointing to component within a JSF Fragment which is included in mainPage.jspx.
    A use case for it could be, for example, i have a tabbed panel with 2 tabs, each tab contains a JSF Fargment per jsp:include, in the first tab there is a table with search result and the second tab should show the detaisl of the selected table item by double-click or context menu of the item.
    Thanks in advanced.

    Hi,
    since you don't mention af:region, I assume you don't use it. In this case, have a look here: http://thepeninsulasedge.com/frank_nimphius/2008/02/14/adf-faces-how-to-issue-a-ppr-event-from-a-fsubview-and-how-to-ppr-of-subviews/
    Frank

  • Upload bank statements interface(with different layouts)

    HI
    My component is upload bank statements interface(with different layouts) .
    to which module it belongs exactly.And how to proceed with this....
    plz give u r sugessitions.................
    pavan kumar

    firstly go through the documentation and TRMs
    if you have any doubt in the coding . the send the code and errors encountered
    so, that we can help you.

  • JTabbedPane with two rows of tabs

    Hi,
    I need to create a JTabbedPane with layout policy as SCROLL_TAB_LAYOUT with two rows of tabs. The first level will have say 10 tabs and the all the remaining tabs (say 20) will be added in the next level. Please help me out on this, to how to proceed with it?
    Edited by: Soundarapandian on Nov 25, 2009 3:10 PM

    Soundarapandian wrote:
    I need to create a JTabbedPane with layout policy as SCROLL_TAB_LAYOUT with two rows of tabs. The first level will have say 10 tabs and the all the remaining tabs (say 20) will be added in the next level. Please help me out on this, to how to proceed with it?Try this (imho better) approach:
    create a new tabbedpane for each level and add each of these tabbedpanes to an upperlevel tabbedpane, thus allowing you to pre-select the desired level.

Maybe you are looking for

  • "iTunes has encountered a problem and needs to close-send error report-dont

    i have tried doing both and i cannot get itunes to open!! i have tried all the installation tips. it just wont' open in my computer! HELP! i just bought the 8 GB ipod nano today. i'm trying to get started but i've installed and uninstalled itunes ove

  • GT80 Titan Cooling Fans are on frequently than before

    I just purchased the new 18 inch Titan and love it. However, I just started noticing the that the fans that use to come on infrequently and very quiet are now coming on more frequently. I have a cooling fan that sits underneath laptop there is nothin

  • Open analysis report in BI Publisher in OBIEE plus

    Hi, I am unable to open a report in BI Publisher which was generated in analysis in OBIEE plus(11g). Previously I did it through Oracle BI Analysis+ in the Data Modle (Data Set). Now I am unbale to find the reports through same process. I noticed onl

  • Casting dataVector

    Hello, how can the following code be made generics compatible? import java.util.*; import javax.swing.*; import javax.swing.table.*; public class TableExample extends JFrame {   TableExample() {     DefaultTableModel dm = new DefaultTableModel() {   

  • Error message 06079

    Hi, I am trying to create a purchase order for a material (ME21N), when I receive the following error message: "Unit of measure EEA not defined for language ES Message no. 06079 Diagnosis Table 006A contains no entry for this unit of measure." Now, m