BoxLayout in component of a splitPane

Hi there,
How can i put a BoxLayout in one of components of a splitPane?
Have any code or samples?
Regards

How do you use a BoxLayout on any Component? Its no different because you are using a split pane.
Create a panel with a BoxLayout. Add the panel to the split pane.
Read the Swing tutorial on [How to Use Box Layout|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].

Similar Messages

  • **URGENT** Hide/Show component on JSpliPane

    Hi,
    I have a JFrame and a Jsplit pane on it and a toolbar.I want to make one button of the toolbar to show/hide the left-top/right-bottom component of the splitpane.I used the following code on actionedPerformed of the button. The code works but the divider is disapeared after first hide of a component.
    int l_lastDividerLocation = splitpane.getDividerLocation();
    int l_lastOrientation = splitpane.getOrientation();
    splitpane.removeAll();
    splitpane.setOrientation(l_lastOrientation);
    if(m_firstComponent != null && m_firstComponent.mb_showComponent == true){
    // m_firstComponent.setSize(m_firstComponentSize);
    splitpane.add(m_firstComponent);
    if(m_secondComponent != null && m_secondComponent.mb_showComponent == true){
    // m_secondComponent.setSize(m_secondComponentSize);
    splitpane.add(m_secondComponent);
    splitpane.setOneTouchExpandable(true);
    splitpane.setDividerLocation(l_lastDividerLocation);

    You could invoke the initialization method during on load of the page fragment as follows:
    Assume that you have the view SampleView.jsff:
    SampleView.jsff:
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <af:outputText value="#{pageFlowScope.InitializationText}" id="ot1"/>
    </jsp:root>
    SampleViewPageDef.xml:
    <?xml version="1.0" encoding="UTF-8" ?>
    <pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel" version="11.1.2.60.17" id="SampleViewPageDef"
    Package="com.subbanasolutions.view.pageDefs"
    ControllerClass="com.subbanasolutions.view.bean.SampleViewBean">
    <parameters/>
    <executables>
    <variableIterator id="variables"/>
    </executables>
    <bindings/>
    </pageDefinition>
    SampleViewPageBean.java:
    package com.subbanasolutions.view.bean;
    import oracle.adf.model.RegionBinding;
    import oracle.adf.model.RegionContext;
    import oracle.adf.model.RegionController;
    import oracle.adf.view.rich.context.AdfFacesContext;
    public class SampleViewBean implements RegionController {
    public SampleViewBean() {
    super();
    @Override
    public boolean refreshRegion(RegionContext regionContext) {
    int refreshFlag = regionContext.getRefreshFlag();
    if (refreshFlag == RegionBinding.PREPARE_MODEL) {
    // Invoke Initialization method
    System.out.println(":::: Initialization Method Invoked");
    this.initializeMethod();
    regionContext.getRegionBinding().refresh(refreshFlag);
    return false;
    @Override
    public boolean validateRegion(RegionContext regionContext) {
    regionContext.getRegionBinding().validate();
    return false;
    @Override
    public boolean isRegionViewable(RegionContext regionContext) {
    return false;
    @Override
    public String getName() {
    return null;
    public void initializeMethod() {
    // HAVE YOUR CUSTOM LOGIC
    The sample application can be downloaded from
    http://adfsampleapplications.googlecode.com/svn/trunk/FragmentOnLoad.rar
    Thanks,
    Navaneeth

  • How can add the thrid frame in JSplitPane?

    Hi,
    I want to know how can I add the thrid or more frame in a JSplitPane. As I know it only can add right-left or top-bottom frames. Thanks

    Well, actually it's piece of cake to put a three way divider to work (e.g. like Netscapes display in the mail window)
    Create a vertical splitted JSplitPane, put your left component into that SplitPane
    Create another JSplitPane (horizontal split) and put it into the first SplitPane on the right hand side.
    Now put the upper right component as the upper component into the second split pane and put the lower right component as the lower component into the scond split pane as wel.
    That's it. No big deal.
    Thomas

  • Read file into a table

    Is there a way of reading content of a file into a table? what if that file is overwritten each x minutes for update?

    yes sure.
    JSplitPane's can hold two components - so your table can be one of the components, and some other feature e.g. a JPanel (which is containing other components in turn) is the other component.
    e.g.
    JSplitPane mainSplitPane_LeftRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // or JSplitPane.VERTICAL_SPLIT
    mainSplitPane_LeftRight.setOneTouchExpandable(true); // set whether you want to be able to maximize one of the components in the JSplitPane using a button on the divider
    // component 1 of splitpane
    JTable yourTable = new JTable(); // initialise with your code here
    // component 2 of splitpane
    JTree tree = new JTree(); // example component
    yourTable.setMinimumSize(new Dimension(10, 10)); // this ensures we can always move the dividers
    tree.setMinimumSize(new Dimension(10, 10)); // this ensures we can always move the dividers
    // add the components
    mainSplitPane_LeftRight.setLeftComponent(yourTable);
    mainSplitPane_LeftRight.setRightComponent(tree);
    // then now we have a populated JSplitPane which you may wanna shove into a JFrame??
    JFrame frame = new JFrame("Tester");
    frame.getContentPane().add(mainSplitPane_LeftRight);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show(); // show it.Hope that helped.

  • How to set SplinPane Borders like MS Outlook?

    Hi All, this is my 2nd Topic :-)
    Platform: Win2000 SVP2, 512 MB, P IV 1,5
    JDK 1.3.002
    I think that a lot of people the MS Outlook Layout knows.
    I build currently a prototype for a Buisness Application.
    My Problem is:
    2 SplitPanes
    SP1 = a Bitmap Menu (like MS Outlook)
    | P1 | P2 |
    | | | |
    SP2 = a Tree & a Table
    I try a lot of thinks to "disable" the Bitmapmenu on the right side of the first Splitpane.
    Problem: i can hidden the Bitmapmenu but i can�t resize
    the Splitpane2 so that she use the room of the Bitmap menu, SP2 is still on the same position and on the left side is only a gray panel. For a Solution i will give 3 Duke Dollars!

    I just solved such a problem...
    what you need is an auto resize jsliptpane: that meens it removes a component from the split pane if not viewed and then recalculate its size.
    here is the class:
    import javax.swing.JSplitPane;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import java.awt.Component;
    import java.awt.BorderLayout;
    * This class extends the JSplitPane class in order to offer a split pane that
    * resizes itself automatically if a component is added or removed.
    * @author Taoufik Romdhane
    * @version 1.0
    public class AutoResizeSplitPane extends JPanel
    * Vertical split indicates the <code>Component</code>s are
    * split along the y axis. For example the two
    * <code>Component</code>s will be split one on top of the other.
    public final static int VERTICAL_SPLIT = 0;
    * Horizontal split indicates the <code>Component</code>s are
    * split along the x axis. For example the two
    * <code>Component</code>s will be split one to the left of the
    * other.
    public final static int HORIZONTAL_SPLIT = 1;
    * The split pane orientation.
    private int orientation;
    * The internal split pane.
    private JSplitPane splitPane;
    * The right component.
    private JComponent rightComponent;
    * The left component.
    private JComponent leftComponent;
    * The split pane state, if showing the splitter or not.
    private boolean isSplitterVisible;
    * The auto resize split pane ui.
    private BorderLessSplitPaneUI borderLessSplitPaneUI;
    * Creates a new <code>AutoResizeSplitPane</code> configured with the
    * specified orientation and no continuous layout.
    * @param newOrientation <code>AutoResizeSplitPane.HORIZONTAL_SPLIT</code> or
    * <code>AutoResizeSplitPane.VERTICAL_SPLIT</code>
    * @exception IllegalArgumentException if <code>orientation</code>
    *          is not one of HORIZONTAL_SPLIT or VERTICAL_SPLIT.
    public AutoResizeSplitPane(int newOrientation)
    super(new BorderLayout());
    splitPane = new BorderLessSplitPane(newOrientation);
    orientation = newOrientation;
    borderLessSplitPaneUI = new BorderLessSplitPaneUI();
    splitPane.setUI(borderLessSplitPaneUI);
    splitPane.setDividerSize(3);
    isSplitterVisible = false;
    * Removes the child component, <code>component</code> from the
    * pane. Resets the <code>leftComponent</code> or
    * <code>rightComponent</code> instance variable, as necessary.
    * @param component the <code>Component</code> to remove
    public void remove(Component component)
    splitPane.remove(component);
    super.remove(splitPane);
    update();
    * Sets the component to the left (or above) the divider.
    * @param comp the <code>Component</code> to display in that position
    public void setLeftComponent(Component comp)
    leftComponent = (JComponent)comp;
    splitPane.setLeftComponent(comp);
    * Returns the component to the left (or above) the divider.
    * @return the <code>Component</code> displayed in that position
    * @beaninfo
    * preferred: true
    * description: The component to the left (or above) the divider.
    public Component getLeftComponent()
    return splitPane.getLeftComponent();
    * Sets the component above, or to the left of the divider.
    * @param comp the <code>Component</code> to display in that position
    * @beaninfo
    * description: The component above, or to the left of the divider.
    public void setTopComponent(Component comp)
    leftComponent = (JComponent)comp;
    splitPane.setLeftComponent(comp);
    * Returns the component above, or to the left of the divider.
    * @return the <code>Component</code> displayed in that position
    public Component getTopComponent()
    return splitPane.getTopComponent();
    * Sets the component to the right (or below) the divider.
    * @param comp the <code>Component</code> to display in that position
    * @beaninfo
    * preferred: true
    * description: The component to the right (or below) the divider.
    public void setRightComponent(Component comp)
    rightComponent = (JComponent)comp;
    splitPane.setRightComponent(comp);
    * Returns the component to the right (or below) the divider.
    * @return the <code>Component</code> displayed in that position
    public Component getRightComponent()
    return splitPane.getRightComponent();
    * Sets the component below, or to the right of the divider.
    * @param comp the <code>Component</code> to display in that position
    * @beaninfo
    * description: The component below, or to the right of the divider.
    public void setBottomComponent(Component comp)
    rightComponent = (JComponent)comp;
    splitPane.setRightComponent(comp);
    * Returns the component below, or to the right of the divider.
    * @return the <code>Component</code> displayed in that position
    public Component getBottomComponent()
    return splitPane.getBottomComponent();
    * Updates the layout.
    * If one child component is empty or an empty splitpane then remove the split
    * and add this child to the content pane.
    public void updateLayout()
    if ((rightComponent != null)
    && (rightComponent instanceof AutoResizeSplitPane))
    ((AutoResizeSplitPane)rightComponent).updateLayout();
    if ((leftComponent != null)
    && (leftComponent instanceof AutoResizeSplitPane))
    ((AutoResizeSplitPane)leftComponent).updateLayout();
    if (isEmpty())
    if (isSplitterVisible)
    isSplitterVisible = false;
    remove(splitPane);
    update();
    else if ((!isEmpty(leftComponent)) && (!isEmpty(rightComponent)))
    //if (!isSplitterVisible)
    removeAll();
    isSplitterVisible = true;
    splitPane.setLeftComponent(leftComponent);
    splitPane.setRightComponent(rightComponent);
    add(splitPane);
    splitPane.revalidate();
    splitPane.repaint();
    update();
    else if (isEmpty(leftComponent))
    isSplitterVisible = false;
    removeAll();
    add(rightComponent);
    update();
    else if (isEmpty(rightComponent))
    isSplitterVisible = false;
    removeAll();
    add(leftComponent);
    update();
    * Gets the preferred width.
    int getPreferredWidth()
    if (isEmpty())
    return 0;
    if (orientation == HORIZONTAL_SPLIT)
    JComponent component;
    if (isEmpty(rightComponent))
    component = leftComponent;
    else
    component = rightComponent;
    if (component instanceof AutoResizeSplitPane)
    AutoResizeSplitPane pane = (AutoResizeSplitPane)component;
    return pane.getPreferredWidth();
    else
    return component.getPreferredSize().width;
    else
    int w1 = 0;
    int w2 = 0;
    JComponent component;
    if (isEmpty(rightComponent))
    component = leftComponent;
    if (component instanceof AutoResizeSplitPane)
    AutoResizeSplitPane pane = (AutoResizeSplitPane)component;
    w1 = pane.getPreferredWidth();
    else
    w1 = component.getPreferredSize().width;
    else
    component = rightComponent;
    if (component instanceof AutoResizeSplitPane)
    AutoResizeSplitPane pane = (AutoResizeSplitPane)component;
    w2 = pane.getPreferredWidth();
    else
    w2 = component.getPreferredSize().width;
    if (w1 == 0)
    return w2;
    else if (w2 == 0)
    return w1;
    else
    return w1 + w2 + 7;
    * Updates the split pane.
    private final void update()
    splitPane.doLayout();
    if (orientation == VERTICAL_SPLIT)
    splitPane.setDividerLocation(getPreferredWidth());
    revalidate();
    repaint();
    * Gets if this component is empty or not.
    * @return The component state.
    public boolean isEmpty()
    return (isEmpty(leftComponent) && isEmpty(rightComponent));
    * Gets if a component is empty or not.
    * @param component The component to check.
    * @return If the component is empty or not.
    private final boolean isEmpty(JComponent component)
    if (component == null)
    return true;
    else if ((component instanceof AutoResizeSplitPane)
    && (((AutoResizeSplitPane)component).isEmpty()))
    return true;
    else
    return false;
    and here is a very usefull ui for nested auto resize split panes
    import javax.swing.plaf.basic.BasicSplitPaneUI;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.UIResource;
    import javax.swing.JComponent;
    import javax.swing.LookAndFeel;
    import javax.swing.UIManager;
    import javax.swing.JSplitPane;
    import javax.swing.border.Border;
    * This class represents a border less split pane ui nedd to enhance the look of
    * nested AutoResizeSplitPanes.
    * @author Taoufik Romdhane
    * @version 1.0
    public class BorderLessSplitPaneUI extends BasicSplitPaneUI
    * Creates a new BorderLessSplitPaneUI instance.
    * @param component The component to install the ui for.
    * @return The border less split pane ui.
    public static ComponentUI createUI(JComponent component)
    return new BorderLessSplitPaneUI();
    * Installs the UI defaults.
    protected void installDefaults()
    //LookAndFeel.installBorder(splitPane, "SplitPane.border");
    if (divider == null) divider = createDefaultDivider();
    divider.setBasicSplitPaneUI(this);
    Border b = divider.getBorder();
    if (b == null || !(b instanceof UIResource))
    divider.setBorder(UIManager.getBorder("SplitPaneDivider.border"));
    setOrientation(splitPane.getOrientation());
    // This plus 2 here is to provide backwards consistancy. Previously,
    // the old size did not include the 2 pixel border around the divider,
    // it now does.
    splitPane.setDividerSize(((Integer) (UIManager.get(
    "SplitPane.dividerSize"))).intValue());
    divider.setDividerSize(splitPane.getDividerSize());
    dividerSize = divider.getDividerSize();
    splitPane.add(divider, JSplitPane.DIVIDER);
    setContinuousLayout(splitPane.isContinuousLayout());
    resetLayoutManager();
    /* Install the nonContinuousLayoutDivider here to avoid having to
    add/remove everything later. */
    if (nonContinuousLayoutDivider == null)
    setNonContinuousLayoutDivider(
    createDefaultNonContinuousLayoutDivider(),
    true);
    else
    setNonContinuousLayoutDivider(nonContinuousLayoutDivider, true);
    * Uninstalls the UI defaults.
    protected void uninstallDefaults()
    if (splitPane.getLayout() == layoutManager)
    splitPane.setLayout(null);
    if (nonContinuousLayoutDivider != null)
    splitPane.remove(nonContinuousLayoutDivider);
    LookAndFeel.uninstallBorder(splitPane);
    Border b = divider.getBorder();
    if (b instanceof UIResource)
    divider.setBorder(null);
    splitPane.remove(divider);
    divider.setBasicSplitPaneUI(null);
    layoutManager = null;
    divider = null;
    nonContinuousLayoutDivider = null;
    setNonContinuousLayoutDivider(null);
    I encountred the same problem as you.
    Plz contact me if there still be some pbs.
    Good luck
    Taoufik

  • Can you hide the divider of a split pane ?

    I have a split pane, the application also has menu options that allow the user to turn off one of the panes if they like, this results in the pane disappearing but the splitpane divider still exists.
    Can this be removed, and if not is it acceptable look for the divider to exist when only one side of the splitpane is visible, or do I have to remove the splitpane from its parent and just add the visible component of the splitpane to the parent directly when only one is selected, reversing the code when user wishes to have both visible.

    Thanks that works fine. Although it is a shame there is no splitpane.getDivider() method, I assume there is no explicit guarantee that the LAF being used actually subclasses BasicSplitPaneUI, so I need to make appropriate checks.

  • Add Component to SplitPane (FX 2.0)

    Hello (:
    How I can add any component (for example button) to SplitPane (javafx.scene.control.SplitPane)? )

    aidreamer wrote:
    I'm not sure due to the incomplete documentation and my inability to use JavaFX 2.0 myself as a Linux user, but you might want to try adding Nodes to the ObservableList retrieved by this method: http://download.oracle.com/javafx/2.0/api/javafx/scene/control/SplitPane.html#getItems%28%29
    Your guess is spot on. Also, the FX 2.0 SplitPane can evidently have multiple dividers.
    import java.util.List;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.SplitPane;
    import javafx.stage.Stage;
    public class FXApp1 extends Application {
        public static void main(String[] args) {
            Application.launch(FXApp1.class, args);
        @Override
        public void start(Stage primaryStage) {
            primaryStage.setTitle("SplitPane Demo");
            Group root = new Group();
            Scene scene = new Scene(root, 300, 50);
            SplitPane splitPane = new SplitPane();
            splitPane.setPrefSize(300,50);
            List<Node> items = splitPane.getItems();
            items.add(new Button("Left"));
            items.add(new Button("Center"));
            items.add(new Button("Right"));
            List<SplitPane.Divider> dividers = splitPane.getDividers();
            for (int i = 0; i < dividers.size(); i++) {
                dividers.get(i).setPosition((i + 1.0) / (dividers.size() + 1.0));
            root.getChildren().add(splitPane);
            primaryStage.setScene(scene);
            primaryStage.setVisible(true);
    }db

  • Custom BoxLayouted component

    Hello Flex team and members.
    I'm trying to create a custom component using a BoxLayout (horizontal) . This component should display a linkbutton (iconized) along with a label. I wanted to use a BoxLayout to easy up all the positionning thing. So i copied the Box class and kept only the important thing to me.
    Here is what i have:
    package common
      import flash.events.Event;
      import flash.events.MouseEvent;
      import mx.containers.BoxDirection;
      import mx.containers.utilityClasses.BoxLayout;
      import mx.controls.Label;
      import mx.controls.LinkButton;
      import mx.core.Container;
      import mx.core.IUIComponent;
      public class TagLabel3 extends Container
         private var layoutObject:BoxLayout = new BoxLayout();
         [Embed(source="cancel.png")]
         protected var iconSymbol:Class;
         protected var tagLabel:Label;
         protected var closeButton:LinkButton;
         private var labelChanged:Boolean = false;
         private var _displayCloseButton:Boolean = true;
         private var _text:String;
         public function TagLabel3()
             super();
             layoutObject.target = this;
             layoutObject.direction = BoxDirection.HORIZONTAL;
             setStyle("cornerRadius", 4);
             setStyle("borderStyle", "solid");
             setStyle("borderThickness", 2);
             setStyle("backgroundColor", "#D4D4D4");
             setStyle("verticalAlign", "middle");
             // other setStyle()...
         override protected function createChildren():void
             super.createChildren();
             if (!closeButton)
               closeButton = new LinkButton();
               closeButton.setStyle("icon", iconSymbol);
               closeButton.addEventListener("heightChanged",
                  function (e:Event):void {
                      minHeight = closeButton.height + 10;
               addChild(closeButton);
             if (!tagLabel)
               tagLabel = new Label();
               addChild(tagLabel);
         override protected function commitProperties():void
             if (closeButton.visible != displayCloseButton)
               closeButton.includeInLayout = displayCloseButton;
               closeButton.visible = displayCloseButton;
         override protected function measure():void
             super.measure();
             layoutObject.measure();
         override protected function updateDisplayList(unscaledWidth:Number,
                                                       unscaledHeight:Number):void
             super.updateDisplayList(unscaledWidth, unscaledHeight);
             layoutObject.updateDisplayList(unscaledWidth, unscaledHeight);
             if (labelChanged)
                  tagLabel.text = text;
                  labelChanged = false;
         public function get text():String
             return _text;
         public function set text(value:String):void
             if (_text != value)
                 _text = value;
                 labelChanged = true;
                 invalidateSize();
                 invalidateDisplayList();
         public function get displayCloseButton():Boolean
             return _displayCloseButton;
         public function set displayCloseButton(value:Boolean):void
             if (_displayCloseButton != value)
                 _displayCloseButton = value;
                 invalidateProperties();
                 invalidateSize();
                 invalidateDisplayList();
    And now I am facing 2 problems:
    - when i play with the 'text' and 'displayCloseButton' properties, the things are being updated correctly but not the size of the whole container. How can i asked the layout to resize correctly.
    - the initial style is taking very long to initialize. I can really first see my container with no border and background color (but with the inner component displayed) and then 1.5 sec later the style is being set.
    I first did the same component by extending an HBox but i didn't want the user to be able to wrongly add something to the HBox by calling addChild on my component.
    Thank you

    Hi Evgeny,
    Try by clearing the browser cache and the [navigation cache|http://help.sap.com/saphelp_nw04/helpdata/en/a2/19edcf16474a9798a5681ce4fe4b25/frameset.htm]
    Hope this helps.
    Cheers!
    Sandeep Tudumu

  • Component maximumsize within nested splitpane

    Hi,
    I have a JSplitPane that contains another JSplitPane within it's right component. I want to constrict the right component of the internal JSplitPane to have a certain maximum size, meaning you can't slide the second divider left of a certain value. Any ideas on how I should implement this?
    Thanks,
    Max

    I solved this by setting a minimum size for the left component of the inner JSplitPane upon a ComponentResized Event based on the total size - the size of the right component

  • Scrollpane ABOVE splitpane divider and left component

    I have a tree in the lefthand side of a splitpane. When the user takes actions on the tree nodes, the righthand side of the splitpane is set to a new panel containing related info. The righthand panel sits on top of a scrollpane. Now the problem: when i move the divider or resize and scoll the righthand side, the added panel is on TOP of the divider and lefthand side tree! Does anyone know why this happens and how to fix it? I've read about the layers and such and i'm sure it's related to that topic, but i can't find a call or param to get the righthand panel to the right "z order". Help!! (thx)

    My guess is that you have some problem with the layout you are using, but without code it's impossible to say.

  • JSplitPane: Panel from bottom component comes back in top component

    Hi,
    In the next program I have added a small Panel (called smallPanel) to a Panel containing what I call a problem. The smallPanel is meant as a place holder for a checkbox that in my program is to be added when needed. So either the smallPanel is added, or a checkbox.
    The smalLPanel is added to a panel in the bottomPanel. The bottomPanel is together with a topPanel added to a JSplitPane. What I found out is that if you scroll the bottomPanel downwards, the smallPanel shines through in the topPanel. My question is, is this a bug?
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class JSplitPaneProblem extends Canvas implements ActionListener
        static Color background;
        static String[] csdEngineers = {"jdoe1", "jdoe2", "jdoe3", "jdoe4", "jdoe5", "jdoet", "amacadam"};
        static String[] engineers = {"Choose one", "jdoe1", "jdoe2", "jdoe3", "jdoe4", "jdoe5", "jdoet", "amacadam"};
        static int width;
        static int height;
        static int remainingWidth;
        static int insets;
        static int labelWidth;
        static JScrollPane problemPane;
        static JPanel bottomPanel;
        static Panel smallPanel;
        static final int FAKE_CHECKBOX_SIZE = 10;
        static JSplitPane splitPane;
        static int BIGNUMBER = 100;
        public JSplitPaneProblem(JFrame frame)
            // Get the image to use.
            ImageIcon trafficLight = createImageIcon("any.gif");
            JLabel trafficLightLabel = new JLabel(trafficLight);
            if (trafficLight != null)
                width = trafficLight.getIconWidth();
                height = trafficLight.getIconHeight();
            else
                width = 100;
                height = 300;
            JPanel topPanel = new JPanel();
            JScrollPane trafficLightPane = new JScrollPane (ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            trafficLightPane.setViewportView(topPanel);
            topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.LINE_AXIS));
            for (int i = 0; i < BIGNUMBER; i++)
                trafficLight = createImageIcon("any.gif");
                trafficLightLabel = new JLabel(trafficLight);
                topPanel.add(trafficLightLabel);
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
            width = dimension.width;
            trafficLightPane.setPreferredSize(new Dimension(width, height));
            trafficLightPane.setMinimumSize(new Dimension(width, height+10)); // <-- Die doet ut
            height = 36;
            insets = 4; // Number of pixels to left and/or right of a component
            labelWidth = 40;
              frame.setBounds (0, 0, dimension.width, dimension.height);
            // And a new problem pane, to which the problem panel is added
            bottomPanel = new JPanel();
            bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
            JScrollPane problemPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            problemPane.setViewportView(bottomPanel);
            // Set up the JSlitPane
            splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, trafficLightPane, problemPane);
            splitPane.setOneTouchExpandable(true);
            splitPane.resetToPreferredSizes();
            frame.add(splitPane);
         * The screen is divided in two equal sized halves, a left and a right side. Each half is divided into 3 parts.
         * remainingWidth is used to calculate the remaining width inside a half.
        public static JPanel addProblem(String organisation, String problem, int i)
            JPanel panel = new JPanel(); // JPanel has FlowLayout as default layout
            panel.setPreferredSize(new Dimension(width, height));
            // First half, containing serverId, customer name, and problem title
            // serverId
            JTextArea serverId = new JTextArea();
            if (i < 10)
                serverId.setText("9999" + i);
            else
                serverId.setText("999" + i);
            Font usedFont = new Font("SanSerif", Font.PLAIN, 12);
            serverId.setFont(usedFont);
            serverId.setPreferredSize(new Dimension(labelWidth, height));
            serverId.setBackground(background);
            panel.add(serverId);
            // Organisation name. Gets 1/3 of remaining width
            remainingWidth = (width / 2 - (int) serverId.getPreferredSize().getWidth()) / 3 - insets;
            JTextArea organisationArea = new JTextArea(organisation);
            organisationArea.setPreferredSize(new Dimension(remainingWidth, height));
            organisationArea.setAlignmentX(SwingConstants.LEFT);
            organisationArea.setBackground(background);
            organisationArea.setLineWrap(true);
            organisationArea.setWrapStyleWord(true);
            organisationArea.setEditable(false);
            panel.add(organisationArea);
            // Problem title
            JTextArea problemArea = new JTextArea(problem);
            problemArea.setPreferredSize(new Dimension(remainingWidth * 2, height));
            problemArea.setBackground(background);
            problemArea.setLineWrap(true);
            problemArea.setWrapStyleWord(true);
            problemArea.setEditable(false);
            panel.add(problemArea);
            // Second half, containing severity, CSD and Engineer
            // Severity
            JTextArea severity = new JTextArea("WARN");
            severity.setFont(usedFont);
            severity.setBackground(background);
            severity.setPreferredSize(new Dimension(labelWidth, height));
            panel.add(severity);
            // CSD
            JLabel csdField = new JLabel("CSD:");
            csdField.setFont(usedFont);
            JComboBox csdList = new JComboBox(csdEngineers);
            csdList.setFont(usedFont);
            csdList.setSelectedIndex(6);
            //csdList.addActionListener(this);
            panel.add(csdField);
            panel.add(csdList);
    // Add "invisible" panel, used instead of checkbox (which is not added in this example)
            smallPanel = new Panel();
            smallPanel.setPreferredSize(new Dimension (FAKE_CHECKBOX_SIZE,
                        FAKE_CHECKBOX_SIZE));
            panel.add(smallPanel);
            // Solver, another ComboBox
            JLabel engineerField = new JLabel("Solver:");
            engineerField.setFont(usedFont);
            JComboBox engineerList = new JComboBox(engineers);
            engineerList.setFont(usedFont);
            engineerList.setSelectedIndex(0);
            //engineerList.addActionListener(this);
            panel.add(engineerField);
            panel.add(engineerList);
            // Empty panel to be added after this panel
            JPanel emptyPanel = new JPanel();
            emptyPanel.setPreferredSize(new Dimension(width, 15));
            return panel;
         * ActionListener
         * @param args
        public void actionPerformed(ActionEvent event)
            System.out.println("Burp");
        private static ImageIcon createImageIcon(String path)
            java.net.URL imgURL = JSplitPaneProblem.class.getResource(path);
            if (imgURL != null)
                return new ImageIcon(imgURL);
            else
                System.err.println("Couldn't find file: " + path);
                return null;
        private static void createAndShowGUI()
             Vector myVector = new Vector();
            // Create and set up the window.
            JFrame frame = new JFrame("JSlitPaneProblem");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Set the size of the window so in covers the whole screen
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setBounds(0, 0, dimension.width, dimension.height);
            // Create and set up the content pane.
            JSplitPaneProblem newContentPane = new JSplitPaneProblem(frame);       
            // Add panels to vector
            bottomPanel.setPreferredSize(new Dimension(dimension.width, dimension.height - height));
            for (int i = 0; i < BIGNUMBER; i++)
                myVector
                    .add(addProblem(
                        "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch Computer Shop",
                        "expected string or buffer, but that is not everyting, as this problem description is extremely long. And as I am chatty, I add some more length",
                        i));
                myVector.add(addProblem("My Company", "I have no problem", i));
            System.out.println ("adding problems to bottomPanel for the first time");
            for (int j = 0; j < 2 * BIGNUMBER; j++) {
                 bottomPanel.add((JPanel)myVector.get(j));
            bottomPanel.removeAll();
            bottomPanel.revalidate();
            System.out.println ("adding problems to bottomPanel for the second time");
            for (int j = 0; j < 2 * BIGNUMBER; j++) {
                 bottomPanel.add((JPanel)myVector.get(j));
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }If you need an image to try out this problem, you can find it here.
    Abel
    Edited by: Abel on 22-apr-2008 11:41
    When you don't see anything in the topPanel, scroll it a bit to the right, and the bottomPanel upwards.

    Use a JPanel, not a Panel, so you don't mix heavyweight and lightweight components.

  • Can't use BoxLayout more than once in a class?

    I have a JPanel inside of a JPanel. I am using a BoxLayout
    manager on the main JPanel, and I used to use a GridLayout on the
    sub JPanel. Yesterday I changed the Layout Manager of the subPanel
    to BoxLayout, and now I get this strange error at runtime. Why can't I use
    2 Box Layouts? Why is Java trying to share them?
    Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
            at javax.swing.BoxLayout.checkContainer(BoxLayout.java:408)
            at javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:195)
            at java.awt.Container.invalidate(Container.java:851)
            at java.awt.Component.addNotify(Component.java:5398)
            at java.awt.Container.addNotify(Container.java:1852)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at java.awt.Container.addNotify(Container.java:1859)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at java.awt.Container.addNotify(Container.java:1859)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at java.awt.Container.addNotify(Container.java:1859)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at java.awt.Container.addNotify(Container.java:1859)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at java.awt.Container.addNotify(Container.java:1859)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at java.awt.Container.addNotify(Container.java:1859)
            at javax.swing.JComponent.addNotify(JComponent.java:4270)
            at javax.swing.JRootPane.addNotify(JRootPane.java:658)
            at java.awt.Container.addNotify(Container.java:1859)
            at java.awt.Window.addNotify(Window.java:395)
            at java.awt.Frame.addNotify(Frame.java:479)
            at java.awt.Window.pack(Window.java:413)
            at CDBTest.main(CDBTest.java:246)I need help.
    Thanks
    Josh

    hmm, the following's my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class PreferencesPane extends JPanel {
    //Main pane to be added to the class
    private JTabbedPane mainPane;
    //the options pane
    private JPanel optionsPane;
    //the accounts list
    private JPanel accountsPane;
    //the personal information display
    private JPanel perInfoPane1;
    private JPanel perInfoPane2;
    //labels
    private JLabel usernameLabel;
    private JLabel newPassLabel;
    private JLabel confPassLabel;
    private JPanel separatorLabel;
    private JLabel nameLabel;
    private JLabel emailLabel;
    private JLabel titleLabel;
    private JLabel companyLabel;
    private JLabel homePhoneLabel;
    private JLabel workPhoneLabel;
    private JLabel cellPhoneLabel;
    private JLabel faxLabel;
    private JLabel homeAddLabel;
    private JLabel workAddLabel;
    private JLabel notesLabel;
    //Textfields
    private JTextField usernameField;
    private JPasswordField newPassField;
    private JPasswordField confPassField;
    private JPanel separatorField;
    private JTextField nameField;
    private JTextField emailField;
    private JTextField titleField;
    private JTextField companyField;
    private JTextField homePhoneField;
    private JTextField workPhoneField;
    private JTextField cellPhoneField;
    private JTextField faxField;
    private JTextArea homeAddField;
    private JTextArea workAddField;
    private JTextArea notesField;
    //Save information button
    private JButton saveInfoButton;
    private JPanel perInfoPane;
    public PreferencesPane() {
    optionsPane = new JPanel();
    accountsPane = new JPanel();
    //labels
    usernameLabel = new JLabel("Username:");
    newPassLabel = new JLabel("New Password:");
    confPassLabel = new JLabel("Confirm New Password:");
    separatorLabel = new JPanel();
    nameLabel = new JLabel("Name:");
    emailLabel = new JLabel("Email:");
    titleLabel = new JLabel("Title:");
    companyLabel = new JLabel("Company:");
    homePhoneLabel = new JLabel("Home Phone:");
    workPhoneLabel = new JLabel("Work Phone:");
    cellPhoneLabel = new JLabel("Cell Phone:");
    faxLabel = new JLabel("Fax:");
    homeAddLabel = new JLabel("Home Address:");
    workAddLabel = new JLabel("Work Address:");
    notesLabel = new JLabel("Notes:");
    //Textfields
    usernameField = new JTextField(20);
    newPassField = new JPasswordField(20);
    confPassField = new JPasswordField(20);
    separatorField = new JPanel();
    nameField = new JTextField(20);
    emailField = new JTextField(20);
    titleField = new JTextField(20);
    companyField = new JTextField(20);
    homePhoneField = new JTextField(20);
    workPhoneField = new JTextField(20);
    cellPhoneField = new JTextField(20);
    faxField = new JTextField(20);
    homeAddField = new JTextArea(10,20);
    workAddField = new JTextArea(10,20);
    notesField = new JTextArea(10,20);
    //Panel to contain the textfield and labels
    perInfoPane1 = new JPanel(new GridLayout(12,2));
    perInfoPane1.add(usernameLabel);
    perInfoPane1.add(usernameField);
    perInfoPane1.add(newPassLabel);
    perInfoPane1.add(newPassField);
    perInfoPane1.add(confPassLabel);
    perInfoPane1.add(confPassField);
    perInfoPane1.add(separatorLabel);
    perInfoPane1.add(separatorField);
    perInfoPane1.add(nameLabel);
    perInfoPane1.add(nameField);
    perInfoPane1.add(emailLabel);
    perInfoPane1.add(emailField);
    perInfoPane1.add(titleLabel);
    perInfoPane1.add(titleField);
    perInfoPane1.add(companyLabel);
    perInfoPane1.add(companyField);
    perInfoPane1.add(homePhoneLabel);
    perInfoPane1.add(homePhoneField);
    perInfoPane1.add(workPhoneLabel);
    perInfoPane1.add(workPhoneField);
    perInfoPane1.add(cellPhoneLabel);
    perInfoPane1.add(cellPhoneField);
    perInfoPane1.add(faxLabel);
    perInfoPane1.add(faxField);
    perInfoPane2 = new JPanel(new GridLayout(3,2));
    perInfoPane2.add(homeAddLabel);
    perInfoPane2.add(homeAddField);
    perInfoPane2.add(workAddLabel);
    perInfoPane2.add(workAddField);
    perInfoPane2.add(notesLabel);
    perInfoPane2.add(notesField);
    //save button
    saveInfoButton = new JButton("Save information");
    perInfoPane = new JPanel(new BoxLayout(perInfoPane,BoxLayout.Y_AXIS));
    perInfoPane1.setAlignmentX(Component.LEFT_ALIGNMENT);
    perInfoPane2.setAlignmentX(Component.LEFT_ALIGNMENT);
    saveInfoButton.setAlignmentX(Component.LEFT_ALIGNMENT);
    perInfoPane.add(perInfoPane1);
    perInfoPane.add(perInfoPane2);
    perInfoPane.add(saveInfoButton);
    //adds components to the TabbedPane
    mainPane = new JTabbedPane(JTabbedPane.LEFT);
    mainPane.add("Options",optionsPane);
    mainPane.add("Accounts",accountsPane);
    mainPane.add("Personal Information",perInfoPane);
    setLayout(new BorderLayout());
    add(mainPane,BorderLayout.CENTER);
    As you can see, the only time I use BoxLayout is the following line:
    perInfoPane = new JPanel(new BoxLayout(perInfoPane,BoxLayout.Y_AXIS));
    As far as I can tell, that's correct, but I'm still getting this at runtime:
    Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
    Anyone have any ideas?

  • Using my new GUI component in an applet :Help!!!

    I am seeking help for the following
    Define class MyColorChooser as a new component so it can be reused in other applications or applets. We want to use the new GUI component as part of an applet that displays the current Color value.
    The following is the code of MyColorChooser class
    * a) We define a class called MyColorChooser that provides three JSlider
    * objects and three JTextField objects. Each JSlider represents the values
    * from 0 to 255 for the red, green and blue parts of a color.
    * We use wred, green and blue values as the arguments to the Color contructeur
    * to create a new Color object.
    * We display the current value of each JSlider in the corresponding JTextField.
    * When the user changes the value of the JSlider, the JTextField(s) should be changed
    * accordingly as weel as the current color.
    * b)Define class MyColorChooser so it can be reused in other applications or applets.
    * Use your new GUI component as part of an applet that displays the current
    * Color value.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public class MyChooserColor extends JFrame{
         private int red, green, blue;  // color shade for red, green and blue
         private static Color myColor;  // color resultant from red, green and blue shades
         private JSlider mySlider [];      
         private JTextField textField [];
    // Panels for sliders, textfields and button components
         private JPanel mySliderPanel, textFieldPanel, buttonPanel;
    // sublcass objet of JPanel for drawing purposes
         private CustomPanel myPanel;
         private JButton okButton, exitButton;
         public MyChooserColor ()     
              super( "HOME MADE COLOR COMPONENT; composition of RGB values " );
    //       setting properties of the mySlider array and registering the events
              mySlider = new JSlider [3];
              ChangeHandler handler = new ChangeHandler();
              for (int i = 0; i < mySlider.length; i++)
              {     mySlider[i] = new JSlider( SwingConstants.HORIZONTAL,
                               0, 255, 255 );
                   mySlider.setMajorTickSpacing( 10 );
                   mySlider[i].setPaintTicks( true );
    //      register events for mySlider[i]
                   mySlider[i].addChangeListener( handler);                     
    //      setting properties of the textField array           
              textField = new JTextField [3];          
              for (int i = 0; i < textField.length; i++)
              {     textField[i] = new JTextField("100.00%", 5 );
                   textField[i].setEditable(false);
                   textField[i].setBackground(Color.white);
    // initial Background color of each slider and foreground for each textfield
    // accordingly to its current color shade
              mySlider[0].setBackground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );
              textField[0].setForeground(
                        new Color ( mySlider[0].getValue(), 0, 0 ) );           
              mySlider[1].setBackground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              textField[1].setForeground(
                        new Color ( 0, mySlider[1].getValue(), 0 ) );
              mySlider[2].setBackground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
              textField[2].setForeground(
                        new Color ( 0, 0, mySlider[2].getValue() ) );
    // initialize myColor to white
              myColor = Color.WHITE;
    // instanciate myPanel for drawing purposes          
              myPanel = new CustomPanel();
              myPanel.setBackground(myColor);
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
    //      instanciate exitButton with its inanymous class
    //      to handle its related events           
              exitButton = new JButton("Exit");
              exitButton.setToolTipText("Exit the application");
              exitButton.setMnemonic('x');
              exitButton.addActionListener(
                        new ActionListener(){
                             public void actionPerformed (ActionEvent e)
                             {     System.exit( 0 );     
    // define the contentPane
              Container c = getContentPane();
              c.setLayout( new BorderLayout() );
    //     panel as container for sliders
              mySliderPanel = new JPanel(new BorderLayout());
    //      panel as container for textFields           
              textFieldPanel = new JPanel(new FlowLayout());
    //      panel as container for Jbuttons components           
              buttonPanel = new JPanel ();
              buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.Y_AXIS ) );
    //add the Jbutton components to buttonPanel           
              buttonPanel.add(okButton);
              buttonPanel.add(exitButton);
    //     add the mySlider components to mySliderPanel
              mySliderPanel.add(mySlider[0], BorderLayout.NORTH);
              mySliderPanel.add(mySlider[1], BorderLayout.CENTER);
              mySliderPanel.add(mySlider[2], BorderLayout.SOUTH);
    //add the textField components to textFieldPanel     
              for (int i = 0; i < textField.length; i++){
                   textFieldPanel.add(textField[i]);
    // add the panels to the container c          
              c.add( mySliderPanel, BorderLayout.NORTH );
              c.add( buttonPanel, BorderLayout.WEST);
              c.add( textFieldPanel, BorderLayout.SOUTH);
              c.add( myPanel, BorderLayout.CENTER );
              setSize(500, 300);          
              show();               
    //     inner class for mySlider events handling
         private class ChangeHandler implements ChangeListener {          
              public void stateChanged( ChangeEvent e )
    // start by collecting the current color shade
    // for red , forgreen and for blue               
                   setRedColor(mySlider[0].getValue());
                   setGreenColor(mySlider[1].getValue());
                   setBlueColor(mySlider[2].getValue());
    //The textcolor in myPanel (subclass of JPanel for drawing purposes)
                   myPanel.setMyTextColor( ( 255 - getRedColor() ),
                             ( 255 - getGreenColor() ), ( 255 - getBlueColor() ) );
    //call to repaint() occurs here
                   myPanel.setThumbSlider1( getRedColor() );
                   myPanel.setThumbSlider2( getGreenColor() );
                   myPanel.setThumbSlider3( getBlueColor() );
    // display color value in the textFields (%)
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   for (int i = 0; i < textField.length; i++){
                        textField[i].setText("" + twoDigits.format(
                                  100.0* mySlider[i].getValue()/255) + " %") ;
    // seting the textcolor for each textField
    // and the background color for each slider               
                   textField[0].setForeground(
                             new Color ( getRedColor(), 0, 0 ) );
                   mySlider[0].setBackground(
                             new Color ( getRedColor(), 0, 0) );
                   textField[1].setForeground(
                             new Color ( 0, getGreenColor() , 0 ) );
                   mySlider[1].setBackground(
                             new Color ( 0, getGreenColor(), 0) );
                   textField[2].setForeground(
                             new Color ( 0, 0, getBlueColor() ) );
                   mySlider[2].setBackground(
                             new Color ( 0, 0, getBlueColor() ) );
    // color of myPanel background
                   myColor = new Color (getRedColor(),
                             getGreenColor(), getBlueColor());
                   myPanel.setBackground(myColor);               
    // set methods to set the basic color shade
         private void setRedColor (int r){
              red = ( (r >= 0 && r <= 255) ? r : 255 );
         private void setGreenColor (int g){
              green = ( (g >= 0 && g <= 255) ? g : 255 );
         private void setBlueColor (int b){
              blue = ( (b >= 0 && b <= 255) ? b : 255 );
    // get methods (return the basic color shade)
         private int getRedColor (){
              return red ;
         private int getGreenColor (){
              return green;
         private int getBlueColor (){
              return blue;
         public static Color getMyColor (){
              return myColor;
    // main method                
         public static void main (String args []){
              MyChooserColor app = new MyChooserColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {     System.exit( 0 );
    // inner class CustomPanel for drawing purposes
         private class CustomPanel extends JPanel {
              private int thumbSlider1 = 255;
              private int thumbSlider2 = 255;
              private int thumbSlider3 = 255;
              private Color myTextColor;
              public void paintComponent( Graphics g )
                   super.paintComponent( g );
                   g.setColor(myTextColor);
                   g.setFont( new Font( "Serif", Font.TRUETYPE_FONT, 12 ) );
                   DecimalFormat twoDigits = new DecimalFormat ("0.00");
                   g.drawString( "The RGB values of the current color are : "
                             + "( "     + thumbSlider1 + " , " + thumbSlider2 + " , "
                             + thumbSlider3 + " )", 10, 40);
                   g.drawString( "The current background color is composed by " +
                             "the folllowing RGB colors " , 10, 60);
                   g.drawString( "Percentage of RED from slider1 : "
                        + twoDigits.format(thumbSlider1*100.0/255), 10, 80 );
                   g.drawString( "Percentage of GREEN from slider2 : "
                        + twoDigits.format(thumbSlider2*100.0/255), 10, 100 );
                   g.drawString( "Percentage of BLUE from slider3 : "
                        + twoDigits.format(thumbSlider3*100.0/255), 10, 120 );
    // call to repaint occurs here     
              public void setThumbSlider1(int th){
                   thumbSlider1 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider2(int th){
                   thumbSlider2 = (th >= 0 ? th: 255 );
                   repaint();
              public void setThumbSlider3(int th){
                   thumbSlider3 = (th >= 0 ? th: 255 );
                   repaint();
              public void setMyTextColor(int r, int g, int b){
                   myTextColor = new Color(r, g, b);
                   repaint();
    //The following method is used by layout managers
              public Dimension getPreferredSize()
              {     return new Dimension( 150, 100 );
    The following is the code of application that tests the component
    //Application used to demonstrating
    // the homemade GUI MyChooserColor component
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowMyColor extends JFrame {
         private JButton changeColor;
         private Color color = Color.lightGray;
         private Container c;
         MyChooserColor colorComponent;
         public ShowMyColor()
         {     super( "Using MyChooserColor" );
              c = getContentPane();
              c.setLayout( new FlowLayout() );
              changeColor = new JButton( "Change Color" );
              changeColor.addActionListener(
                        new ActionListener() {
                             public void actionPerformed( ActionEvent e )
                             {     colorComponent = new MyChooserColor ();
                                  colorComponent.show();
                                  color = MyChooserColor.getMyColor();
                                  if ( color == null )
                                       color = Color.lightGray;
                                  c.setBackground( color );
                                  c.repaint();
              c.add( changeColor );
              setSize( 400, 130 );
              show();
         public static void main( String args[] )
         {     ShowMyColor app = new ShowMyColor();
              app.addWindowListener(
                        new WindowAdapter() {
                             public void windowClosing( WindowEvent e )
                             {  System.exit( 0 );

    Yes, I want help for the missing code to add in actionPerformed method below. As a result, when you confirm the selected color (clicking the OK button), it will be transferred to a variable color of class ShowMyColor.
    // instanciate okButton with its inanymous class
    // to handle its related events
              okButton = new JButton ("OK");
              okButton.setToolTipText("To confirm the current color");
              okButton.setMnemonic('o');
              okButton.addActionListener(
                   new ActionListener(){
                        public void actionPerformed (ActionEvent e)
                        {     // code permetting to transfer
                             // the current color to the parent
                             // component backgroung color
                             //System.exit( 0 );     
              );

  • Add a JLabel below a JTextArea in a boxlayout

    I have a JTextArea in a JScrollPane in a GUI, and I'm using BoxLayout. Occasionally, I wish to add a JLabel to my JScrollPane, which works fine.
    However, since my BoxLayout is set to the Y_Axis layout, the JLabel always ends up being centered below the JTextArea, and I want it, as well as the JTextArea, to be aligned to the left. I know there is a LEFT_ALIGNMENT operator, but I am unsure of how to use it, although I've read the API for java.awt.Component.
    Also, my JTextArea has a maximum column size, but when the JLabel is displayed, the JTextArea stretches across my entire JScrollPane window. I've tried setting a maximum size, but for some reason that tends to cut off some text on the left side of the JTextArea.
    The JLabel will almost always be wider than the JTextArea. Perhaps that is causing some problems with BoxLayout?
    If there's any more information I should provide, please let me know.
    Thanks for any help you can provide,
    Dan
    Message was edited by:
    Djaunl

    Ok I figured out how the align the JLabel to the left:
    myJLabel.setAlignmentX(Component.LEFT_ALIGNMENT);However, I'm having an odd problem with my JTextArea. If my GUI displays the text normally, everything is fine. But once I add a JLabel to my JScrollPane that is wider than the view (i.e. so I need to scroll horizontally to see the entire JLabel), when I load more text, the text will not position itself within the JScrollPane view, and I will have to scroll over to see all of the text, which I do not want to do.
    Is there a way to keep the JTextArea at the same maximum column number, even though there is a JLabel below it that is much wider than the JTextArea should be?
    I get the feeling this isn't making sense. Here's the code to create my components:
    // Create min/max dimensions
              Dimension minimumSize = new Dimension(200, 500);
              Dimension maximumSize = new Dimension(500, 500);
                    Dimension buttonSize = new Dimension (125, 20);
                    int cols = 30;
              // Create Tree viewing pane
              JScrollPane treeView = new JScrollPane(tree);
              treeView.setMinimumSize(minimumSize);
              treeView.setMaximumSize(maximumSize);
              // Create HTML viewing pane 1
              final JPanel htmlView1 = new JPanel();
                    BoxLayout BL = new BoxLayout(htmlView1, BoxLayout.Y_AXIS);
                    htmlView1.setLayout(BL);
                    final JScrollPane htmlPane = new JScrollPane(htmlView1);
              htmlPane.setMinimumSize(minimumSize);
              htmlPane.setMaximumSize(maximumSize);
                    // Create text area1
                    final JTextArea textArea1 = new JTextArea();
                    textArea1.setLineWrap(true);
                    textArea1.setWrapStyleWord(true);
                    textArea1.setColumns(cols);
                    textArea1.setAlignmentX(Component.LEFT_ALIGNMENT);
                                            JLabel pic = new JLabel (new ImageIcon(new URL(DBQuery.list.get(1))));
                                            pic.setAlignmentX(Component.LEFT_ALIGNMENT);
                                            htmlView1.add(pic);Later in the code, I add textArea1 to htmlView1.
    I'm sorry if this is very confusing. If there is anything I can do to help, please let me know.

  • How to create a jdialog with boxlayout

    Hi,
    I was trying to create a jdialog as simple as plsql login dialog. In attempt to learn how should I proceed I downloaded and modified BoxLayoutDemo.java that is available from java's swing tutorial site:
    * BoxLayoutDemo.java is a 1.4 application that requires no other files.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class BoxLayoutDemo {
        static JDialog jdlg;
        public static void addComponentsToPane(Container pane) {
            pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
            addTextField(pane);
            addAButton("Button 1", pane);
            addAButton("Button 2", pane);
            addAButton("Button 3", pane);
            addAButton("Long-Named Button 4", pane);
            addAButton("5", pane);
        private static void addAButton(String text, Container container) {
            JButton button = new JButton(text);
            button.setAlignmentX(Component.CENTER_ALIGNMENT);
            container.add(button);
        private static void addTextField(Container container) {
            JTextField txt = new JTextField(20);
            //txt.setMaximumSize(new Dimension(100,20));
            txt.setPreferredSize(new Dimension(100,10));
            txt.setAlignmentX(Component.RIGHT_ALIGNMENT);
            //Border padding = BorderFactory.createEmptyBorder(20,20,5,20);
            //txt.setBorder(padding);
            container.add(txt);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("BoxLayoutDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set up the content pane.
            jdlg = new JDialog(frame);
            addComponentsToPane(jdlg.getContentPane());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
            jdlg.setPreferredSize(new Dimension(200,200));
            jdlg.pack();
            jdlg.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }The funniest thing is every thing except the text box is ok. With or without the text box the buttons are shown appropriately i mean they dont stretch. But in case of the text field it seems like that the height of the textfield becomes 60 instead of 20. if I use txt.setMaximumsize(new Dimension(100,20)) then everything seems ok.
    Now it seems like swing has some fetish about textfields. Because even if I dont specify the size of the buttions they dont stretch themsleves but even if I specify the size of the text field and make it the first element so that the last element gets stretched if necessary without affecting it, it will defy the size instruction.Layout managers are really amazing!!!!!!!! and so helpful!!!!!!!!!

    not really sure what effect you want, but try this
        private static void addTextField(Container container) {
            JTextField txt = new JTextField(20);
            //txt.setMaximumSize(new Dimension(100,20));
            txt.setPreferredSize(new Dimension(100,10));
            txt.setAlignmentX(Component.RIGHT_ALIGNMENT);
            //Border padding = BorderFactory.createEmptyBorder(20,20,5,20);
            //txt.setBorder(padding);
            JPanel p = new JPanel();//<-------------
            p.add(txt);//<-------------
            //container.add(txt);//<-------------
            container.add(p);//<-------------
        }

Maybe you are looking for

  • Print html to image and create pdf

    Hi! I'm looking for a way to convert html-pages to fairly good looking pdf-files. As far as I have found there are only one product that can do this and they will not stay in budget. So I wonder if there is a way to "print" the html to an image that

  • From which table do i fetch cost center????

    Hi.. i have material and plant as selection screen parameters.. CSKS table has plant and cost center.. but when i checked the contents of the table...there is no value for plant.. so plz suggest me smeother table wherein i can fetch cost center detai

  • USB Drive is treated as an Alias without original and without owner !!!

    After not being able to use a Formac analog to digital video converter I thought that installing in parallel Leopard only for that converter would finish th problems with Snow Leopard. Wishful thinking !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Nature of relations between Containers and Components in AWT

    I don't know if this entitles me for Duke Dollars but I just wanted to contribute something anyway. Please let me know if it does. Here it's: import java.awt.*; import java.applet.Applet; import java.awt.event.*; Name: Negib Mohamed Purpose: to show

  • Is it possible to submit an abap oo instance?

    Hi experts, I need to execute the process of creating 300.000 materials associated with 15 centres in background. Is this possible? Apparently, I can't specify the instance of the class to the SUBMIT declarative... I would appreciate your responses.