Class Panel3D
- All Implemented Interfaces:
com.jogamp.opengl.GLEventListener,ImageObserver,MenuContainer,Serializable,EventListener,Accessible
GLJPanel and manages a simple
interactive 3D scene.
Panel3D is the central drawing panel used by the MDI-3D extension.
It owns the OpenGL panel, the list of Item3D objects to render, the
current camera translation, the current scale, and the current orientation.
Rotation is stored as a quaternion so mouse-drag arcball rotations compose
smoothly without accumulating Euler-angle artifacts.
Subclasses normally customize a panel by overriding
createInitialItems(), beforeDraw(GLAutoDrawable), or
afterDraw(GLAutoDrawable). Optional Swing components can be placed
around the OpenGL canvas by overriding the directional hook methods
addNorth(), addSouth(), addEast(), and
addWest().
Rendering uses two passes. Opaque items are drawn first with depth writes enabled. Transparent items are then sorted approximately back-to-front and drawn with blending enabled and depth writes disabled. This is not a full order-independent transparency solution, but it is appropriate for the simple educational and diagnostic scenes used by the MDI-3D demos.
The panel supports both unit-scale and large-world scenes. Keyboard panning
and mouse-wheel navigation use a configurable navigation step; the default
preserves the original small-scene behavior, while larger scenes can call
setNavigationStep(float) or setNavigationStepFromExtent(float).
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanelNested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponentNested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected MouseAdapter3Dprotected Stringprotected Stringstatic final floatDefault background component used for red, green, and blue.protected com.jogamp.opengl.GLCapabilitiesprotected final com.jogamp.opengl.awt.GLJPanelThe hosted OpenGL panel, ornullif OpenGL could not be initialized on this system (seeisGLAvailable()).protected com.jogamp.opengl.GLProfileprotected com.jogamp.opengl.glu.GLUFields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
ConstructorsConstructorDescriptionPanel3D(float angleX, float angleY, float angleZ, float xDist, float yDist, float zDist) Construct a 3D panel with the default light-gray background.Panel3D(float angleX, float angleY, float angleZ, float xDist, float yDist, float zDist, float bgRed, float bgGreen, float bgBlue, boolean skipLastStage) Construct a 3D panel with an explicit background color. -
Method Summary
Modifier and TypeMethodDescriptionprotected JComponentaddEast()Optional hook for a Swing component on the east side of the panel.voidAdd an item at the specified list index.voidAdd an item to the panel.protected JComponentaddNorth()Optional hook for a Swing component on the north side of the panel.protected JComponentaddSouth()Optional hook for a Swing component on the south side of the panel.protected JComponentaddWest()Optional hook for a Swing component on the west side of the panel.voidafterDraw(com.jogamp.opengl.GLAutoDrawable drawable) Hook called after all items have been drawn and before the model-view matrix is restored.voidbeforeDraw(com.jogamp.opengl.GLAutoDrawable drawable) Hook called after the model-view transform has been applied and before any items are drawn.voidRemove all items from the panel and refresh the display.voidCreate the initial 3D items for this panel.voiddeltaX(float dx) Increment the current x translation.voiddeltaY(float dy) Increment the current y translation.voiddeltaZ(float dz) Increment the current z translation.voiddisplay(com.jogamp.opengl.GLAutoDrawable drawable) Render the current OpenGL frame.voiddispose(com.jogamp.opengl.GLAutoDrawable drawable) Dispose of OpenGL resources associated with this listener.The reason OpenGL initialization failed, if it did.com.jogamp.opengl.awt.GLJPanelReturn the JOGL panel hosted by this Swing panel.floatReturns the current X scale factor.floatReturns the current Y scale factor.floatReturns the current Z scale factor.floatgetZStep()Return the navigation step used by keyboard panning and mouse-wheel zoom.voidinit(com.jogamp.opengl.GLAutoDrawable drawable) Initialize the OpenGL state for this panel.booleanWhether OpenGL was successfully initialized for this panel.voidReset the current orientation to the identity rotation.voidproject(com.jogamp.opengl.GL2 gl, float objX, float objY, float objZ, float[] winPos) Project object coordinates to window coordinates using the current OpenGL matrices.voidrefresh()Hard refresh: forces an immediate JOGL render.voidPlaceholder for queued refresh support.voidForce JOGL to tear down and rebuild the GL context on next paint.voidremoveItem(Item3D item) Remove an item from the panel and refresh the display.voidreshape(com.jogamp.opengl.GLAutoDrawable drawable, int x, int y, int width, int height) Update the OpenGL viewport and projection matrix after a resize.voidApply an axis-angle rotation to the current orientation.voidrotateX(float angleDeg) Rotate the scene about the x axis.voidrotateY(float angleDeg) Rotate the scene about the y axis.voidrotateZ(float angleDeg) Rotate the scene about the z axis.voidsetNavigationStep(float navigationStep) Set the navigation step used by keyboard panning and mouse-wheel zoom.voidsetNavigationStepFromExtent(float extent) Set the navigation step from a characteristic scene extent.voidsetScale(float xscale, float yscale, float zscale) Set the scale factors applied to the scene before rotation.voidSoft refresh: schedules a repaint through AWT's normal paint mechanism.Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUIMethods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeMethods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
BG_DEFAULT
public static final float BG_DEFAULTDefault background component used for red, green, and blue.- See Also:
-
glprofile
protected com.jogamp.opengl.GLProfile glprofile -
glcapabilities
protected com.jogamp.opengl.GLCapabilities glcapabilities -
gljpanel
protected final com.jogamp.opengl.awt.GLJPanel gljpanelThe hosted OpenGL panel, ornullif OpenGL could not be initialized on this system (seeisGLAvailable()). Every method in this class that touchesgljpanelalready null-checks it, so anullvalue here degrades gracefully to a no-op rather than an NPE. -
glu
protected com.jogamp.opengl.glu.GLU glu -
_itemList
-
_mouseAdapter
-
_rendererStr
-
_versionStr
-
-
Constructor Details
-
Panel3D
public Panel3D(float angleX, float angleY, float angleZ, float xDist, float yDist, float zDist) Construct a 3D panel with the default light-gray background.The initial orientation is established by resetting the quaternion orientation and then applying rotations about x, y, and z, in that order. The distance parameters are OpenGL model-view translations applied before scaling and rotation.
- Parameters:
angleX- initial rotation angle about the x axis, in degreesangleY- initial rotation angle about the y axis, in degreesangleZ- initial rotation angle about the z axis, in degreesxDist- initial x translationyDist- initial y translationzDist- initial z translation
-
Panel3D
public Panel3D(float angleX, float angleY, float angleZ, float xDist, float yDist, float zDist, float bgRed, float bgGreen, float bgBlue, boolean skipLastStage) Construct a 3D panel with an explicit background color.The constructor creates the
GLJPanel, registers this object as theGLEventListener, installs the MDI-3D keyboard and mouse adapters, and creates any optional border components returned by the directional hook methods. Initial scene contents are created later, when the first OpenGL context is initialized, by callingcreateInitialItems(). Deferring scene creation avoids invoking an overridable method from this constructor.- Parameters:
angleX- initial rotation angle about the x axis, in degreesangleY- initial rotation angle about the y axis, in degreesangleZ- initial rotation angle about the z axis, in degreesxDist- initial x translationyDist- initial y translationzDist- initial z translationbgRed- red component of the background color, in[0, 1]bgGreen- green component of the background color, in[0, 1]bgBlue- blue component of the background color, in[0, 1]skipLastStage- iftrue, skip the finalglLoadIdentity()indisplay(GLAutoDrawable)
-
-
Method Details
-
isGLAvailable
public boolean isGLAvailable()Whether OpenGL was successfully initialized for this panel.- Returns:
trueif this panel has a workingGLJPanel;falseif GL initialization failed andgetGLJPanel()returnsnull
-
getGLInitError
The reason OpenGL initialization failed, if it did.- Returns:
- the throwable caught during GL setup, or
nullifisGLAvailable()istrue
-
createInitialItems
public void createInitialItems()Create the initial 3D items for this panel.The default implementation is empty. Subclasses normally override this method to populate the panel with axes, lines, surfaces, point clouds, or other
Item3Dobjects.The method is invoked once, when the panel's first OpenGL context has been initialized. It is deliberately not called from the
Panel3Dconstructor because subclasses may depend on fields that are not initialized until after the superclass constructor has returned.A later OpenGL-context recreation does not rebuild the logical item list. Individual items that own OpenGL resources are responsible for recreating those resources as necessary.
-
addNorth
Optional hook for a Swing component on the north side of the panel.The default implementation returns
null. Subclasses can override this method to add controls, legends, sliders, or other Swing components outside the OpenGL drawing area.- Returns:
- component to place on the north side, or
null
-
addSouth
Optional hook for a Swing component on the south side of the panel.The default implementation returns
null. Subclasses can override this method to add controls, legends, sliders, or other Swing components outside the OpenGL drawing area.- Returns:
- component to place on the south side, or
null
-
addEast
Optional hook for a Swing component on the east side of the panel.The default implementation returns
null. Subclasses can override this method to add controls, legends, sliders, or other Swing components outside the OpenGL drawing area.- Returns:
- component to place on the east side, or
null
-
addWest
Optional hook for a Swing component on the west side of the panel.The default implementation returns
null. Subclasses can override this method to add controls, legends, sliders, or other Swing components outside the OpenGL drawing area.- Returns:
- component to place on the west side, or
null
-
getGLJPanel
public com.jogamp.opengl.awt.GLJPanel getGLJPanel()Return the JOGL panel hosted by this Swing panel.Most callers should interact with
Panel3Drather than the rawGLJPanel. This accessor is provided for cases that need direct integration with JOGL or Swing.- Returns:
- the hosted OpenGL panel
-
setScale
public void setScale(float xscale, float yscale, float zscale) Set the scale factors applied to the scene before rotation.- Parameters:
xscale- scale factor in xyscale- scale factor in yzscale- scale factor in z
-
rotate
Apply an axis-angle rotation to the current orientation.This method composes the new rotation with the existing quaternion orientation. The rotation angle is in radians, which matches the values produced by
MouseAdapter3D. Invalid or nearly zero-length axes are ignored.- Parameters:
axis- rotation axisangleRadians- rotation angle, in radians
-
rotateX
public void rotateX(float angleDeg) Rotate the scene about the x axis.- Parameters:
angleDeg- rotation angle, in degrees
-
rotateY
public void rotateY(float angleDeg) Rotate the scene about the y axis.- Parameters:
angleDeg- rotation angle, in degrees
-
rotateZ
public void rotateZ(float angleDeg) Rotate the scene about the z axis.- Parameters:
angleDeg- rotation angle, in degrees
-
loadIdentityMatrix
public void loadIdentityMatrix()Reset the current orientation to the identity rotation.Earlier versions of MDI-3D stored the orientation as a matrix. The current implementation stores the orientation as a quaternion; this method preserves the old name while resetting the quaternion to identity.
-
display
public void display(com.jogamp.opengl.GLAutoDrawable drawable) Render the current OpenGL frame.JOGL calls this method whenever the
GLJPanelneeds to draw. The method clears the buffers, applies translation, scale, and quaternion orientation, snapshots the current item list, draws opaque items first, and then draws transparent items in approximate back-to-front order.- Specified by:
displayin interfacecom.jogamp.opengl.GLEventListener- Parameters:
drawable- JOGL drawable being rendered
-
beforeDraw
public void beforeDraw(com.jogamp.opengl.GLAutoDrawable drawable) Hook called after the model-view transform has been applied and before any items are drawn.The default implementation is empty. Subclasses can override this method to draw custom OpenGL content behind the item list.
- Parameters:
drawable- JOGL drawable being rendered
-
afterDraw
public void afterDraw(com.jogamp.opengl.GLAutoDrawable drawable) Hook called after all items have been drawn and before the model-view matrix is restored.The default implementation is empty. Subclasses can override this method to draw custom OpenGL content on top of the item list.
- Parameters:
drawable- JOGL drawable being rendered
-
init
public void init(com.jogamp.opengl.GLAutoDrawable drawable) Initialize the OpenGL state for this panel.JOGL calls this method when the GL context is created. The method records renderer/version strings and configures depth testing, perspective correction, blending, point sizing, and the clear color.
- Specified by:
initin interfacecom.jogamp.opengl.GLEventListener- Parameters:
drawable- JOGL drawable whose context is being initialized
-
reshape
public void reshape(com.jogamp.opengl.GLAutoDrawable drawable, int x, int y, int width, int height) Update the OpenGL viewport and projection matrix after a resize.The projection uses a 45-degree perspective field of view with a broad near/far range appropriate for the simple demo scenes used by MDI-3D.
- Specified by:
reshapein interfacecom.jogamp.opengl.GLEventListener- Parameters:
drawable- JOGL drawable being reshapedx- viewport x originy- viewport y originwidth- new viewport widthheight- new viewport height
-
deltaX
public void deltaX(float dx) Increment the current x translation.Unlike
rotateX(float), this does not callrefresh()itself — callers (e.g.MouseAdapter3D,KeyAdapter3D) must request a refresh explicitly after the last delta in a batch.- Parameters:
dx- change in x translation
-
deltaY
public void deltaY(float dy) Increment the current y translation.Unlike
rotateY(float), this does not callrefresh()itself — callers (e.g.MouseAdapter3D,KeyAdapter3D) must request a refresh explicitly after the last delta in a batch.- Parameters:
dy- change in y translation
-
deltaZ
public void deltaZ(float dz) Increment the current z translation.Unlike
rotateZ(float), this does not callrefresh()itself — callers (e.g.MouseAdapter3D,KeyAdapter3D) must request a refresh explicitly after the last delta in a batch.- Parameters:
dz- change in z translation
-
refreshQueued
public void refreshQueued()Placeholder for queued refresh support.The current implementation is intentionally empty. It is retained for API compatibility with code that may distinguish queued refreshes from immediate or soft refreshes.
-
softRefresh
public void softRefresh()Soft refresh: schedules a repaint through AWT's normal paint mechanism. Use this for layout-driven redraws (resize, move, show). This is safe to call from the EDT and does not race with Swing painting. -
refresh
public void refresh()Hard refresh: forces an immediate JOGL render. Only call this when you need synchronous GL output, e.g. after a mouse-drag rotation. Do NOT call from component/layout events. -
reinitGLContext
public void reinitGLContext()Force JOGL to tear down and rebuild the GL context on next paint. Call this once after a lazy view has been made visible with a real native peer, to ensure the FBO is created against the correct surface. -
addItem
Add an item to the panel.If the item is already present, it is moved to the end of the list. Later items are normally drawn later within their opaque/transparent pass.
The remove-then-add is performed under
synchronized(_itemList)so it is atomic with respect todisplay()'s own synchronized snapshot of_itemList: without this, a concurrent snapshot taken between the remove and the add could observe the item as transiently missing.- Parameters:
item- item to add; ignored whennull
-
addItem
Add an item at the specified list index.If the item is already present, the existing occurrence is removed first.
- Parameters:
index- insertion indexitem- item to add; ignored whennull
-
removeItem
Remove an item from the panel and refresh the display.- Parameters:
item- item to remove; ignored whennull
-
clearItems
public void clearItems()Remove all items from the panel and refresh the display. -
getXScale
public float getXScale()Returns the current X scale factor.- Returns:
- the current X scale factor
-
getYScale
public float getYScale()Returns the current Y scale factor.- Returns:
- the current Y scale factor
-
getZScale
public float getZScale()Returns the current Z scale factor.- Returns:
- the current Z scale factor
-
project
public void project(com.jogamp.opengl.GL2 gl, float objX, float objY, float objZ, float[] winPos) Project object coordinates to window coordinates using the current OpenGL matrices.The result is written into
winPos:winPos[0]is window x,winPos[1]is window y, andwinPos[2]is window z/depth. The caller must provide an array with length at least three.- Parameters:
gl- active GL2 contextobjX- object x coordinateobjY- object y coordinateobjZ- object z coordinatewinPos- output array for window coordinates
-
getZStep
public float getZStep()Return the navigation step used by keyboard panning and mouse-wheel zoom.- Returns:
- navigation step in world units
-
dispose
public void dispose(com.jogamp.opengl.GLAutoDrawable drawable) Dispose of OpenGL resources associated with this listener.Panel3Ditself holds no explicit GL resources, but items on the panel may — for example a text-drawing item's lazily-created JOGLTextRenderer, which owns a GPU texture atlas. This gives every item (and its children) a chance to release those viaItem3D.disposeItem(GLAutoDrawable)before the GL context goes away, so repeatedly opening and closing 3D views doesn't leak texture memory.- Specified by:
disposein interfacecom.jogamp.opengl.GLEventListener- Parameters:
drawable- JOGL drawable being disposed
-