Multiple Components in a JScrollPane

Hi all,
I'm trying to create a JScrollPane with multiple components in it, inside a TabPane. However I keep running into problems getting the display working.
The contents of the ScrollPane will be determined at runtime and will consist of "n" tables and JLabels, in no particular order. The only constraint is that I want to have the components displayed in rows (one column per row). The number of rows and columns in each of the JTables (and therefore their size) will also be determined at runtime.
I've run into problems where the JScrollPane only shows the last JTable added. I've tried adding a JPanel to the JScrollPane and then adding the tables to that, but the display doesn't work - maybe something I've missed on the sizing?
Any clues on where I should focus will be most appreciated.
Thanks

Hi,
Thanks for the suggestion - I've tried using the following test code, but I cannot get it to display anything:
public class AFrame extends JFrame {
  private JScrollPane jScrollPane1 = new JScrollPane();
  public AFrame() {
    try {
      this.getContentPane().setLayout(new BorderLayout());
      this.setTitle("Test Frame");
      this.setSize(500, 500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.getContentPane().add(jScrollPane1, null);
      jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
      jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      //create a table   
      JTable table1 = new JTable();
      table1.setModel(new TestTableModel());
      TableColumnModel colmod = table1.getColumnModel();
      for (int i=0; i < table1.getColumnCount(); i++) {
        TableColumn col = colmod.getColumn(i);
        col.setPreferredWidth(50);
      //create an edit field
      JEditorPane jep1 = new JEditorPane();
      jep1.setPreferredSize(new Dimension(100, 20));
      //create the panel & add two components
      JPanel p = new JPanel();
      p.setPreferredSize(this.getSize());
      double size[][] =
        {{10, TableLayout.PREFERRED, 10},  // Columns
         {10, TableLayout.PREFERRED, 10}}; // Rows
      TableLayout tl = new TableLayout(size);
      p.setLayout(tl);
      p.add(table1, "1, 1");
      p.add(jep1, "1, 2");
      validate();
      setVisible(true);
    catch(Exception e) {
      e.printStackTrace();
  public static void main(String[] args) { new AFrame(); }
//The TestTableModel dummy class for testing
public class TestTableModel extends AbstractTableModel  {
  public TestTableModel() {
  public int getRowCount() {
    return 2;
  public int getColumnCount() {
    return 10;
  public Object getValueAt(int row, int col) {
    return "Test value";
}

Similar Messages

  • How to remove multiple components border inside a single table column cell

    Hi,
    I'm adding multiple components to a table cell. To provide a good layout I'm using the following component hierarchy in a table column - table-->groupPanel--> gridPanel-->staticText Components 1 ..2 ..3. Now when I do preview in browser or run the app, the table shows up fine, but textComponent s(1,2,3) in the column are each surrounded by a border (which is the width of gridPanel border). Is there a way to get rid of this border?
    This only occurs when you add multiple components in table cell, under gridpanel layout component.
    I've tried searching for a way to remove the grid pane layout component border but couldn't find any info. Used style class border setting to not set but that doesn't help either. I checked forums, tutorial, learning sections etc., but no success. Any help or direction is appreciated..
    Thanks
    -Vinod

    Hi ,
    Can you please post the query ..what u have tried ...
    SQL&gt; select sub from coa1;
    SUB
    XY
    XY
    XY
    XY
    XY
    HXY
    HXY
    HXY
    8 rows selected.
    SQL&gt; select obj from coa1;
    OBJ
    AM
    AM
    AM
    AK
    AK
    AK
    ATK
    ATK
    8 rows selected.
    SQL&gt; SELECT OBJ FROM COA1
    2 UNION ALL
    3 SELECT SUB FROM COA1;
    OBJ
    AM
    AM
    AM
    AK
    AK
    AK
    ATK
    ATK
    XY
    XY
    XY
    OBJ
    XY
    XY
    HXY
    HXY
    HXY
    16 rows selected.
    SQL&gt; insert into coa2 (obj)
    2 (
    3 SELECT OBJ FROM COA1
    4 UNION ALL
    5 SELECT SUB FROM COA1
    6 );
    16 rows created.
    SQL&gt; select * from coa2;
    OBJ SUB MCU DOC F
    AM
    AM
    AM
    AK
    AK
    AK
    ATK
    ATK
    XY
    XY
    XY
    OBJ SUB MCU DOC F
    XY
    XY
    HXY
    HXY
    HXY
    16 rows selected.
    SQL&gt;
    i tried the same it worked fine .....
    so u can combine select and insert statements .. you can get the required result.....!
    Thanks
    Ananda
    Edited by: Ananda on Feb 2, 2009 7:38 PM
    Edited by: Ananda on Feb 2, 2009 7:52 PM

  • Use of multiple components in ABAP WEB DYNPRO

    Hi,
    Am  new to  abap web dynpro and I just want to know whether  we  can  use  multiple components for an application in web dynpro.
    Thanks ,
    Dhaya.G
    Edited by: Dhayalinie Ganesh on Feb 22, 2012 12:06 PM

    Hi,
    depending requirement of application we can use multiple components.
    for example if we want to display table data into alv grid for that we can use the existing(standard component) ie: SALV_WD_TABLE  .Like such a way we can use the components as per our requirements.
    For importing components:
    --> Go to properties tab of view of your web dynpro application
    --> There you can find one button create controller usage ,click on it then import the components
    Thanks&Regards
    Sreenivas Pachva
    Edited by: sreenivas.p on Feb 22, 2012 1:11 PM

  • Drag and Drop of multiple components at once

    Hi everybody,
    I need to select and drag multiple components (Eg. JLabels) at once, it is quite simple to manage just one drag at a time but how can be managed a multiple drag?
    I mean something like Windows files selection mechanism : using Ctrl + Left mouse click to select the components and then start dragging them all to the drop target.
    Beneath the code I'm using for testing , clicking and dragging each JLabel to JTextField just cause the copy of JLabel text to the JTextField contents.
    In the sample a left click on each displayed label sets a border just to identify the selected status of the labels to drag but there's no implementation of the drop mechanism that should copy all the selected JLabels text to the drop target (the JTextField).
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.HashMap;
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.TransferHandler;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    public class SelectableJLabel extends JPanel {
      MouseListener listener = new DragMouseAdapter();
      public Border getBorder(boolean getSelectedBorder) {
        Border outsideBorder = BorderFactory.createEmptyBorder(2,2,2,2);
        Border insideBorder = BorderFactory.createEmptyBorder(2,2,2,2);
        if (getSelectedBorder)
          insideBorder = BorderFactory.createEtchedBorder();
        return BorderFactory.createCompoundBorder(outsideBorder, insideBorder);
      private class DragMouseAdapter extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
          System.out.println("Press!");
          JComponent c = (JComponent) e.getSource();
          JLabel lbl = (JLabel)c;     
          if (lbl.getBorder()==null || ((CompoundBorder)lbl.getBorder()).getInsideBorder() instanceof EmptyBorder) {
            lbl.setBorder(getBorder(true));
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);    
          } else
            lbl.setBorder(getBorder(false));        
        /* (non-Javadoc)
         * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
        @Override
        public void mouseClicked(MouseEvent e) {
      public JLabel getSelectableLabel() {
        JLabel selectableJLabel = new JLabel("You can't select me");
        selectableJLabel.setBorder(getBorder(false));
        selectableJLabel.setTransferHandler(new TransferHandler("text"));
        selectableJLabel.addMouseListener(listener);
        return selectableJLabel;
      public SelectableJLabel() {
        // a regular JLabel
        add(getSelectableLabel());
        add(getSelectableLabel());
        add(getSelectableLabel());
        // a look-alike JLabel
        JTextField f = new JTextField("You can select me........................");
        f.setDragEnabled(true);
        //f.setEditable(false);
        f.setBorder(null);
        f.setForeground(UIManager.getColor("Label.foreground"));
        f.setFont(UIManager.getFont("Label.font"));
        add(f);
      public Dimension getPreferredSize() {
        return new Dimension(100, 100);
      public static void main(String s[]) {
        JFrame frame = new JFrame("SelectableJLabel");
        SelectableJLabel panel = new SelectableJLabel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel, "Center");
        frame.setSize(panel.getPreferredSize());
        frame.setVisible(true);
    }Tnx in advance for HELP
    Massimo
    Edited by: JKut on May 2, 2010 10:48 AM

    For multiple selections I recommend to use "JList". The "ListTransferHandler" provided in the "DropDemo" sample code supports multiple selections: [http://java.sun.com/docs/books/tutorial/uiswing/dnd/dropmodedemo.html]. To enable MULTIPLE_INTERVAL_SELECTION, simply remove the following statement in the "DropDemo" class:
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

  • Logging same NC code for multiple components

    Hi,
    When logging NC codes in SAP ME 6.0 it is possible to log the same NC Code (defect) against many ref-des for
    multiple components.
    However when logging a secondary code (Action) for the previous primary NC Code all the choosen ref-des and components
    don't get copied..
    Is this how it is supposed to work or is there a setting somewhere so that all ref-des and components gets copied?
    Best Regards,
    Johan Nordebrink

    Hi Johan,
    The matter of your question is related to Ref Des List re-desinged for 6.0.
    Overall situation looks like a design gap because:
    - no explicit statement in the documentation describing the case of copying multiple Ref Des'es;
    - the case of 1-to-1 relation between Component and Ref Des is mentioned in the context of auto-population of these feilds on tabbing out if one of the field is populated;
    - the case of single Ref Des is widely referenced in the context of VTR that is a new feature in 6.0.
    So, if you need this to be reviewed by Product Mgmt (maybe they agreed to identify this as a bug), as usually you should either ask your SAP ME Consulting representative or submit a support ticket (depending on whom you pefer to talk with ).
    Regards,
    Sergiy

  • Data table header facet with multiple components?

    Hi,
    I have a data table to which I wish to add buttons to change the sort order of the items displayed. However when I add the 'buttons' to the 'header' facet I get strange results - some components are shown, some are not, and the order they appear seems almost random.
    Is the header / footer facet designed only for one component - or can I combine them somehow?
    Code snippet is
    <h:dataTable id="table" rowClasses="oddRow,evenRow" width="80%"
    value="#{ControllerBean.orderedResults}" var="meet">
    <h:column>
    <f:facet name="header">
    <h:commandLink action="#{ControllerBean.setOrder}">
    <h:graphicImage value="/img/up.gif" style="border: 0px" />
    <f:param name="order" value="up-title" />
    </h:commandLink>
    <h:outputText value="#{msgs.title}" />
    <h:commandLink action="#{ControllerBean.setOrder}">
    <h:graphicImage value="/img/down.gif" style="border: 0px" />
    <f:param name="order" value="down-title" />
    </h:commandLink>
    </f:facet>
    <h:outputText id="meetTitle"
    value="#{meet.title}" />
    </h:column>
    etc..
    So to be clear - I want a header that contains two graphic buttons separated by the text. When I run this code as is here, I get just the 'down' button, but by changing the order I can sometimes get the down button and the text......
    Cheers
    Reeling

    Yes, you can place it in a panelGrid or panelGroup component.
    The following is an excerpt from a book:
    TIP: To place multiple components in a table header or footer, you must
    group them in an h:panelGroup tag, or place them in a container component
    with h:panelGrid or h:dataTable. If you place multiple components in a facet, only the
    first component will be displayed.
    Thus you could have something like:
                   <f:facet name="header">
                        <h:panelGrid columns="1">
                             <h:outputText value="#{fields.recordings}" style="font-weight: bolder" />
                             <h:panelGroup>
                                  <h:outputText value="#{fields.type}" style="font-weight: bolder"/>
                                  <h:outputText value="#{fields.date}" style="font-weight: bolder"/>
                                  <h:outputText value="#{fields.time}" style="font-weight: bolder"/>
                             </h:panelGroup>
                        </h:panelGrid>
                   </f:facet>

  • JOptionPane: adding multiple Components

    Hello,
    I am trying to add multiple components to a JOption Pane. When the JOptionPane is displayed, the JOptionPane is not resized in order to display all of the components. In my case, the buttons of the JOptioPane are pushed down. Only the upper half of buttons are visible.
    How do you set the JOptionPane to fully display all of the objects that were passed into it?

    What do you mean by saying that the components should be added to the JPanel using the setBounds() method?
    I currently have this:
    JPanel p = new JPanel(null);
    p.add(new JLabel("Label"));
    p.add(new JEditorTextPane("text/plain", "Text"));
    p.add(new JTextField("Text field"));
    p.setBounds(new Rectangle(200, 200));
    JOptionPane.showOptionDialog(null, p, "Title", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
    With this code, I do not even see the "OK" button. The dialog is not resizing correctly. Also, the components are getting laid out incorrectly in the JPanel. Everything is laid out from left to right.

  • Dynamic SORT with multiple components

    Hi all,
    I want to sort an internal table in this way:
    SORT itab BY (component).
    This is not difficult if "component" contains the name of ONE column of itab. But - and here is my problem - how can I sort with multiple components?
    Like this:
    SORT itab BY (comp_1) (comp_2) ... (comp_N).
    The number of components (N) shall be flexible. It is not possible to concatenate the components into one string-variable. This causes an error ITAB_ILLEGAL_COMPONENT.
    Brillant would be a solution which also contains the sort-direction (ASCENDING or DESCENDING for each component like this:
    SORT itab BY (comp_1) (dir_1)
                 (comp_2) (dir_2)
                 (comp_N) (dir_N).
    Is there a way to do so?
    Thanks for all hints!
    Mathias

    Hi Matahias ...
    From ABAP help...
    SORT itab.
    Extras:
    1. ... BY f1 f2 ... fn
    2. ... ASCENDING
    3. ... DESCENDING
    4. ... AS TEXT
    5. ... STABLE
    The syntax check performed in an ABAP Objects context is stricter than in other ABAP areas. See Field symbols not allowed as sort criterion.
    Effect
    The entries in the internal table are sorted in ascending order using the key from the table definition (DATA, TYPES).
    Addition 1
    ... BY f1 f2 ... fn
    Effect
    Uses the sort key defined by the sub-fields f1, f2, ..., fn of the table itab instead of the table key. The fields can be of any type; even number fields and tables are allowed.
    You can also specify the sort fields dynamically in the form (name). If name is blank at run time, the sort field is ignored. If itab is a table with a header line, you can also use a field symbol pointing to the header line of itab as a dynamic sort criterion. A field symbol that is not assigned is ignored. If a field symbol is assigned, but does not point to the header line of the internal table, a runtime error occurs.
    If the line type of the internal table contains object reference variables as components, or the entire line type is a reference variable, you can use the attributes of the object to which a reference is pointing in a line as sort criteria (see Attributes of Objects as the Key of an Internal Table
    You can address the entire line of an internal table as the key using the pseudocomponent TABLE_LINE. This is particularly relevant for tables with a non-structured line type when you want to address the whole line as the key of the table (see also Pseudocomponent TABLE_LINE With Internal Tables).
    If you use one of the additions 2 to 5 before BY, it applies to all fields of the sort key by default. You can also specify these additions after each individual sort field f1, f2, ..., fn. For each key field, this defines an individual sort rule which overrides the default.
    Cheers
    Preetham

  • Printing a multipage document containing multiple Components

    Hi everybody,
    I am trying to print a multipage document which consists of multiple JPanels used for grouping, each of which hold JLabels and JScrollPanes and JTextAreas.
    I know how to do multipage printing with text but I am lost with the multi component situation.
    Thanks in advance for any help.
    vh

    If you know how many pages are in use, get the size of the page (the pageformats imageable height * page number) and with that number translate the page up that number of pixels. ( the translate method of graphics ). Then you can draw all the components on the page. Make sure you translate before you draw, this mistake took me a day to figure out. Hope this helps.

  • How do i add multiple components to a scrollpane?

    i have found info and examples on using a jpanel within the scroll pane, but i am still having difficulties. i put multiple componets (textarea's and so forth) into the panel and when i run the application the scrollable area does not work - show all of the panel? any ideas? thanks for any help!

    Since there is no code attached, I assume that your mistake is that you simply did something like:myScroll.add(myPanel)This doesn't work, since you have to add the panel to the viewport and not the scroll pane itself. Do this instead:myScroll.getViewport().add(myPanel);Or, there is a better version - just put it in creation:
    myScroll = new JScrollPane(myPanel);This is better since you need to bear in mind that there should be only one component in the scroll pane's viewport.
    If you want to replace it during run time, you need to remove the component from the viewport and add the new one: myScroll.getViewport().remove(oldPanel);
    myScroll.getViewport().add(newPanel);Good luck!
    - Moti

  • How to move multiple components into a Tab Component and still keep layout?

    I have created a Combination Chart with multiple combo boxes and a slider on my Xcelsius Canvas.  Now, I realize that I want to put all of this into a Tab Set Component.  How can I move everything into this new Tab Component without messing up all the layout and alignment I have done on all my components already?  I tried shift-selecting everything and doing a drag --> drop into the Tab Canvas but they just all stack on top of each other.
    Can this be done?  Would it be wiser to start a new Xcelsius document, place a Tab Set Component on the canvas and then copy --> paste from the original document into the new one? I'm reluctant to do this though (even within the same document) because it forces all components to be renamed back to their defaults such as Chart 1, Combo Box 1, etc etc.
    Edit:
    Bolded my biggest concern on this topic, can components be copy/pasted or cut/pasted and still retain their original name?

    i think this scenario would work fine for you
    choose all the components you want to move from the "Object Browser"
    you can show the Object Browser from the View Menu
    after you select them all, you can drag them to your Tab component
    or you can make them as a group, so it will be easy to move them as the same layout they have.
    to make them as one group
    select them all, go to format menu, and select Group
    now you have all of them as one item, move them to the tab and then you can ungroup them the same way
    good luck
    Amr

  • Mouse Coordinate issues caused by Scaling Components in a JScrollPane

    Hi All,
    I've been attempting to write a program that includes a simple modeler. However, I've been having some trouble with being able to select components when attempting to implement zoom functionality - when I "zoom" (which is done via scroll wheel) using the scale Graphics2D method, while it zooms correctly, the mouse location of components do not seem scale.
    I've tried one of the solutions found on the forums here (create a custom event queue that adjusts the mouse coordinates) and while it seemed to work initially, if I zoom in and adjust the current view position using the scrollbars, certain components contained in the JPane will become un-selectable and I haven't been able to work out why.
    I've attached a SSCCE that reproduces the problem below - it implements a JScrollPane with a JPane with a few selectable shapes set as the Viewport. The zoom is done using the mouse scroll wheel (with wheel up being zoom in and wheel down being zoom out)
    Any help in order to fix the selection/de-selection issues on zoom would be greatly appreciated! I've spent some time reading through the forums here but have unfortunately not been able to find a workable solution around it.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Tester extends JScrollPane
        public Tester() {
            this.setViewportView(new Model());
        public static void main (String[] args) {
            JFrame main = new JFrame();
            main.add(new Tester());
            main.setSize(500,300);
            main.setResizable(false);
            main.setVisible(true);
    class Model extends JPanel implements MouseListener, MouseWheelListener
        private GfxClass selection = null;
        private static double zoomLevel = 1;
        // zoom methods
        public void setZoom(double zoom) {
            if( zoom < 0 && zoomLevel > 1.0)
                zoomLevel += zoom;
            if( zoom > 0 && zoomLevel < 5.0)
                zoomLevel += zoom;
        public static double getZoom() { return zoomLevel; }
        public void resetZoom() { zoomLevel = 1; }
        public Model() {
            super(null);
            addMouseListener(this);
            addMouseWheelListener(this);
            MyEventQueue meq = new MyEventQueue();
            Toolkit.getDefaultToolkit().getSystemEventQueue().push(meq);
            for(int i = 0; i <7; i++) {
                double angle = Math.toRadians(i * 360 / 7);
                GfxClass oc_tmp = new GfxClass((int)(200 + 150 * Math.cos(angle)), (int)(125 + 100 * Math.sin(angle)), "Element"+i);
                add(oc_tmp);
            repaint();
        public void paint (Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            AffineTransform oldTr=g2.getTransform();
            g2.scale(getZoom(),getZoom());
            super.paint(g2);
            g2.setTransform(oldTr);
            setBackground (Color.white);
            super.paintBorder(g2);
        private static class MyEventQueue extends EventQueue  {
            protected void dispatchEvent(AWTEvent event) {
                AWTEvent event2=event;
                if ( !(event instanceof MouseWheelEvent) && (event instanceof MouseEvent) ) {
                    if ( event.getSource() instanceof Component && event instanceof MouseEvent) {
                        MouseEvent me=(MouseEvent)event2;
                        Component c=(Component)event.getSource();
                        Component cursorComponent=SwingUtilities.getDeepestComponentAt(c, me.getX(), me.getY());
                        JPanel zContainer= getZoomedPanel(cursorComponent);
                        if (zContainer!=null) {
                            int x=me.getX();
                            Point p=SwingUtilities.convertPoint(zContainer,0,0,(Component)event.getSource());
                            int cX=me.getX()-p.x;
                            x=x-cX+(int)(cX/getZoom());
                            int y=me.getY();
                            int cY=me.getY()-p.y;
                            y=y-cY+(int)(cY/getZoom());
                            MouseEvent ze = new MouseEvent(me.getComponent(), me.getID(), me.getWhen(), me.getModifiers(), x, y, me.getClickCount(), me.isPopupTrigger());
                            event2=ze;
                super.dispatchEvent(event2);
        public static JPanel getZoomedPanel(Component c) {
            if (c == null)
                return null;
            else if (c instanceof Model)
                return (Model)c;
            else
                return getZoomedPanel(c.getParent());
        private void deselectAll() {
            if(selection != null)
                selection.setSelected(false);
            selection = null;
        public void mouseClicked(MouseEvent arg0)  {    }
        public void mouseEntered(MouseEvent arg0)  {    }
        public void mouseExited(MouseEvent arg0)   {    }
        public void mouseReleased(MouseEvent arg0) {    }   
        public void mousePressed(MouseEvent me) {
            Component c1 = findComponentAt(me.getX(),me.getY());
            if(c1 instanceof GfxClass)
                if(selection != null)
                    selection.setSelected(false);
                selection = (GfxClass)c1;
                selection.setSelected(true);
            else
                deselectAll();
            repaint();
            return;
        public void mouseWheelMoved(MouseWheelEvent e) { // controls zoom
                int notches = e.getWheelRotation();
                if (notches < 0)
                    setZoom(0.1);
                else
                    setZoom(-0.1);
                this.setSize(new Dimension((int)(500*getZoom()),(int)(300*getZoom())));           
                this.setPreferredSize(new Dimension((int)(500*getZoom()),(int)(300*getZoom())));     
                repaint();
    class GfxClass extends Component { // simple graphical component
        private boolean isSelected = false;
        private String name;
        public GfxClass(int xPos, int yPos, String name) {
            this.name = name;
            this.setLocation(xPos,yPos);
            this.setSize(100,35);
        public void setSelected(boolean b) {
            if( b == isSelected )
                return;
            isSelected = b;
            repaint();
        public boolean isSelected() {
            return isSelected;
        public void paint(Graphics g2) {
            Graphics2D g = (Graphics2D)g2;
            if( isSelected )
                g.setColor(Color.RED);
            else
                g.setColor(Color.BLUE);
            g.fill(new Ellipse2D.Double(0,0,100,35));
            g.setColor(Color.BLACK);
            g.drawString(name, getSize().width/2 - 25, getSize().height/2);
    }Edited by: Kys99 on Feb 22, 2010 9:09 AM
    Edited by: Kys99 on Feb 22, 2010 9:10 AM

    Delete your EventQueue class. Change one line of code in your mouse pressed method.
    public void mousePressed(MouseEvent me) {
        Component c1 = findComponentAt((int) (me.getX()/getZoom()),
                                       (int) (me.getY()/getZoom()));
    }

  • Question about adding multiple components....

    .....HI, i really hope someone can help out......
    When I try to add mutilple components to the panel, it won't show the components that I have added before again.....
    For example, I have a Icon Label and I want it to show two of the same Label again in the panel.... but it won't... it will just show one of them....
    for example:
    Label[] dice = new Label[6]
    Icon bug[] = new Icon[6];
    String dicePics[] = {"1.jpg", "2.jpg","3.jpg",
    "4.jpg","5.jpg","6.jpg",};
    for(int i=0; i<6; i++){
    bug[i] = new ImageIcon(dicePics);
    dice[i] = new JLabel();
    dice[i].setIcon( bug[i] );
    userPanel.add(dice[0]);
    userPanel.add(dice[0]);
    This will only show dice[0] once in panel........ how can I show the same things over again in a panel more then once.........?? I also try it on other things... when adding a component with same name, it will just show one of them.......... wondering if someone can help me out.......

    .....HI, i really hope someone can help out......
    When I try to add mutilple components to the panel,
    it won't show the components that I have added before
    again.....
    For example, I have a Icon Label and I want it to
    show two of the same Label again in the panel.... but
    it won't... it will just show one of them....
    for example:
    Label[] dice = new Label[6]
    Icon bug[] = new Icon[6];
    String dicePics[] = {"1.jpg", "2.jpg","3.jpg",
    "4.jpg","5.jpg","6.jpg",};
    for(int i=0; i<6; i++){
    bug[i] = new ImageIcon(dicePics);
    dice[i] = new JLabel();
    dice[i].setIcon( bug[i] );
    l.add(dice[0]);
    userPanel.add(dice[0]);
    This will only show dice[0] once in panel........ how
    can I show the same things over again in a panel more
    then once.........?? I also try it on other
    things... when adding a component with same name, it
    will just show one of them.......... wondering if
    someone can help me out.......
    You can't add the same GUI object to a Container multiple times. The problem is with your design. Consider something like this:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class DieLabelTest {
        private Random rand = new Random();
        private final JLabel[] dies = new JLabel[6];
        DieLabelTest() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel diePanel = new JPanel(new GridLayout(3,0,5,5));
            for (int i = 0; i < 6; i++) {
                dies[i] = new JLabel();
                dies.setIcon(DieIconProvider.getIcon(rand.nextInt(6) + 1));
    diePanel.add(dies[i]);
    f.add(diePanel, BorderLayout.CENTER);
    JButton rollButton = new JButton("Roll");
    rollButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    for (int i = 0; i < 6; i++) {
    dies[i].setIcon(DieIconProvider.getIcon(rand.nextInt(6) + 1));
    f.add(rollButton, BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
    public static void main(String[] args) {
    new DieLabelTest();
    class DieIconProvider {
    private static Icon[] icons = new Icon[6];
    public static synchronized Icon getIcon(int num) {
    if (icons[num - 1] == null) {
    icons[num - 1] = new ImageIcon(num + ".jpg");
    return icons[num -1];

  • Movable components interacting with JScrollPane

    I am creating movable components. The class is designed as an extension to JPanel and contains a label and a textfield. The Panel responds to the mouse and moves itself around a JPanel which is inside the JScrollPane according to the user. This will eventially be a layout process so users of this program can make things look the way they want.
    I can't seem to get the JScrollPane to recognize when a component is moved outside it's immediate area and scroll. I'm looking through the archives but I am not running into answers because I don't know what to look for.
    Do I need to look at the scrollable interface? Do I need to throw an event which will notify the Scrollpane. Any hints or answer would be greatly appreciated!
    Here is my main class definition which may provide some clues:
    public static void main (String[] args) {
    JFrame view = new JFrame( "Testing" );
    JPanel mainPanel = new JPanel();
    JScrollPane scrollPane = new JScrollPane( mainPanel );
    mainPanel.add( new movablePanel( "Label", "Testing" ) );
    mainPanel.add( new MovablePanel( "Label", "Text" ) );
    view.getContentPane().add( scrollPane );
    view.validate();
    view.repaint();
    view.show();

    Here's what you should do.
    In your panel's mouseDragged or mouseMoved event handler, add:
    x = this.getLocation().x;
    y = this.getLocation().y;
    maxX = this.getLocation().x+this.getSize().width;
    maxY = this.getLocation().y+this.getSize().height;
    scrollminX = ScrollPane.getViewPort().getViewPosition().x
    scrollminY = ... getViewPosition().y
    scrollmaxX = scrollminX + ScrollPane.getViewPort().getExtentSize().width;
    scrollmaxY = scrollminY + ... getExtentSize().height
    now test to see if everything is in range

  • Multiple JPanels, non-working JScrollPane

    So, I'm trying to make a scrollbar with multiple text areas, but I can't seem to get the scroll bar to appear when there's overflow. When I try, [this is an example of what I get|http://www.fileden.com/files/2010/3/9/2788777//scrollpane.png].
    Here is my code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.KeyboardFocusManager;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.ScrollPaneConstants;
    public class SSCCE
         public SSCCE()
              JFrame f = new JFrame();
              JPanel p[] = {new JPanel(),new JPanel()};
              JScrollPane pane = new JScrollPane(p[0],ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              p[0].setLayout(new GridBagLayout());
              for(int i = 0 ; i < 16; i++)
                   addItem(p[0],createTextArea(""+i),0,i,GridBagConstraints.WEST);
              p[1].add(new JButton("Click"));
              pane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
              f.add(pane,BorderLayout.NORTH);
              f.add(p[1],BorderLayout.SOUTH);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(500,300);
              f.setLocationRelativeTo(null);
              f.setVisible(true);
         private JTextArea createTextArea(String text)
              JTextArea t = new JTextArea(text,1,10);
              t.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
              t.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
              return t;
         private static void addItem(JPanel p, JComponent c, int column, int row, int align)
              GridBagConstraints gc = new GridBagConstraints();
              gc.fill = GridBagConstraints.NONE;
              c.setFont(new Font("Courier New",Font.PLAIN,12));
              gc.gridx = column;
              gc.gridy = row;
              gc.gridwidth = 1;
              gc.gridheight = 1;
              gc.anchor = align;
              gc.weightx = 100;
              gc.weighty = 100;
              p.add(c, gc);
              p.validate();
         public static void main(String[] args)
              new SSCCE();
    }What do I do to get the scroll bar to appear?

    preferredSize worked. Thanks guys. :)
    Edit: BorderLayout.CENTER also worked. Thanks.
    Edited by: ElectrifiedBrain on Aug 14, 2010 12:57 AM

Maybe you are looking for