Adding a progressbar to a JLayeredPane

Hi,
I am having problems with adding a progressbar to a JlayeredPane.
Below is the code I have.
I can see the JLayeredPane, but cannot see the ProgressBar inside it.
Do u know what the prblem might be ?
ovpg1 is the object for the progressbar and jlp is the object for the JLayeredPane.
Am I missing something ?
Thanks
Amit
JLayeredPane jlp=new JLayeredPane();
JProgressBar ovpg1 = new JProgressBar();
jlp.setPreferredSize(new Dimension(2000,2050));
lp.setBorder(BorderFactory.createTitledBorder("JLayeredPane"));
ovpg1.setStringPainted(true);
ovpg1.setAlignmentX(2.7f);
ovpg1.setBorder(BorderFactory.createTitledBorder(
"The first progressbar's layer and position "));
ovpg1.setValue(90);
ovpg1.setBorderPainted(true);
ovpg1.setBackground(Color.green);
ovpg1.setForeground(Color.red);
jlp.add(ovpg1,new Integer(10)); // Default is the bottom layer.
toolbar.add(jlp);

You also need to realize that a JLayeredPane does not use a LayoutManager to layout your components... You have to manually set the Bounds your self...
try this...
Dimension pref = ovpg1.getPreferredSize();
ovpg1.setBounds(0, 0, pref.width, pref.height);Hope this helps,
Josh Castagno
http://www.jdc-software.com

Similar Messages

  • Why can't I change the color of my ProgressBar? Always green.

    I added a ProgressBar object to my form. Works fine. But the bar is always green despite setting the Forecolor to Blue in the Design and to red in code:
    ' intTotalNumberOfFiles = 80
    pgbCloset.Value = 0
    pgbCloset.Step = 1
    pgbCloset.Maximum = 99
    pgbCloset.ForeColor = Color.Red ' for testing.
    For intCnt = 1 To intTotalNumberOfFiles
    'If intTotalNumberOfFiles > 0 Then pgbCloset.ForeColor = Color.Green
    'If intTotalNumberOfFiles > 30 Then pgbCloset.ForeColor = Color.Yellow
    'If intTotalNumberOfFiles > 60 Then pgbCloset.ForeColor = Color.Red
    pgbCloset.PerformStep()
    Next
    Any idea why? How do I fix this? Thx.

    ... ups, VB,so here's something to start with... (or uncheck the "enable XP visual styles" checkBox in your project's settings)
    Partial Public Class Form1
    Inherits Form
    Private WithEvents progressBar1 As New NewProgressBar()
    Private WithEvents button1 As New System.Windows.Forms.Button()
    Private WithEvents timer1 As New System.Windows.Forms.Timer()
    Private WithEvents button2 As New System.Windows.Forms.Button()
    Private WithEvents trackBar1 As New TrackBar()
    Private WithEvents trackBar2 As New TrackBar()
    Public Sub New()
    InitializeComponent()
    Me.button1.Location = New System.Drawing.Point(20, 105)
    Me.button1.Name = "button1"
    Me.button1.Size = New System.Drawing.Size(75, 23)
    Me.button1.TabIndex = 1
    Me.button1.Text = "button1"
    Me.button1.UseVisualStyleBackColor = True
    Me.timer1.Interval = 50
    Me.progressBar1.Location = New System.Drawing.Point(41, 1)
    Me.progressBar1.Name = "progressBar1"
    Me.progressBar1.Size = New System.Drawing.Size(187, 23)
    Me.progressBar1.TabIndex = 0
    Me.progressBar1.ShowText = True
    Me.progressBar1.ForeColor = Color.White
    'Colors and Positions
    Me.progressBar1.Color1 = Color.Red
    Me.progressBar1.Color2 = Color.Yellow
    Me.progressBar1.Color3 = Color.Green
    'PositionColor2 must be in a range from 0 to 1.0F
    Me.progressBar1.PositionColor2 = 0.71F
    Me.progressBar1.GammaCorrected = True
    'change OverlaySpeed and Delay and Width
    Me.progressBar1.OverlayAddAmount = 0.8F
    Me.progressBar1.OverlayReshowDelay = 35.0F
    Me.progressBar1.OverlayWidth = 50.0F
    Me.button2.Location = New System.Drawing.Point(120, 105)
    Me.button2.Name = "button2"
    Me.button2.Size = New System.Drawing.Size(75, 23)
    Me.button2.TabIndex = 2
    Me.button2.Text = "button2"
    Me.button2.UseVisualStyleBackColor = True
    Me.trackBar1.Location = New Point(20, 145)
    Me.trackBar1.Width = Me.progressBar1.Width
    Me.trackBar1.Minimum = 0
    Me.trackBar1.Maximum = 100
    Me.trackBar1.Value = 10
    Me.trackBar2.Location = New Point(20, 195)
    Me.trackBar2.Width = Me.progressBar1.Width
    Me.trackBar2.Minimum = 0
    Me.trackBar2.Maximum = 100
    Me.trackBar2.Value = 30
    Me.Controls.Add(Me.button2)
    Me.Controls.Add(Me.button1)
    Me.Controls.Add(Me.progressBar1)
    Me.Controls.Add(Me.trackBar1)
    Me.Controls.Add(Me.trackBar2)
    Me.progressBar1.Left = 0
    Me.progressBar1.Width = Me.ClientSize.Width
    End Sub
    Private Sub trackBar2_ValueChanged(sender As Object, e As EventArgs) Handles trackBar2.ValueChanged
    Me.progressBar1.OverlayReshowDelay = CSng(Me.trackBar2.Value)
    End Sub
    Private Sub trackBar1_ValueChanged(sender As Object, e As EventArgs) Handles trackBar1.ValueChanged
    Me.progressBar1.OverlayAddAmount = CSng(Me.trackBar1.Value) / 10.0F
    End Sub
    Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
    Me.timer1.Enabled = True
    End Sub
    Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick
    Me.timer1.Stop()
    Me.progressBar1.Value += 0.5F
    If Me.progressBar1.Value = Me.progressBar1.Maximum Then
    Me.progressBar1.Value = 0
    End If
    Me.timer1.Start()
    End Sub
    Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
    Me.timer1.Enabled = False
    End Sub
    End Class
    Public Class NewProgressBar
    Inherits ProgressBar
    Public Property Percentage() As Single
    Get
    Return m_Percentage
    End Get
    Set(value As Single)
    m_Percentage = Value
    End Set
    End Property
    Private m_Percentage As Single
    Public Property ShowText() As Boolean
    Get
    Return m_ShowText
    End Get
    Set(value As Boolean)
    m_ShowText = Value
    End Set
    End Property
    Private m_ShowText As Boolean
    Private _doMarqueeOverlay As Boolean = False
    Private WithEvents timer1 As New Timer()
    Private _pos As Single = 0
    Private _rWidth As Single = 71
    Public Property OverlayWidth() As Single
    Get
    Return _rWidth
    End Get
    Set(value As Single)
    _rWidth = value
    End Set
    End Property
    Private _c As Integer = 0
    Private _posAdd As Single = 1.5F
    Public Property OverlayAddAmount() As Single
    Get
    Return _posAdd
    End Get
    Set(value As Single)
    _posAdd = value
    End Set
    End Property
    Private _posDelay As Single = 50
    Public Property OverlayReshowDelay() As Single
    Get
    Return _posDelay
    End Get
    Set(value As Single)
    _posDelay = value
    End Set
    End Property
    Public Property Color1() As Color
    Get
    Return m_Color1
    End Get
    Set(value As Color)
    m_Color1 = Value
    End Set
    End Property
    Private m_Color1 As Color
    Public Property Color2() As Color
    Get
    Return m_Color2
    End Get
    Set(value As Color)
    m_Color2 = Value
    End Set
    End Property
    Private m_Color2 As Color
    Public Property Color3() As Color
    Get
    Return m_Color3
    End Get
    Set(value As Color)
    m_Color3 = Value
    End Set
    End Property
    Private m_Color3 As Color
    Public Property PositionColor2() As Single
    Get
    Return m_PositionColor2
    End Get
    Set(value As Single)
    m_PositionColor2 = Value
    End Set
    End Property
    Private m_PositionColor2 As Single
    Public Shadows Property Value() As Single
    Get
    Return Me.Percentage
    End Get
    Set(value As Single)
    Me.Percentage = value
    'maybe dont invalidata always...
    If Not _doMarqueeOverlay Then
    Me.Invalidate()
    End If
    End Set
    End Property
    Private m_useImg As Boolean
    Public Property UseImg() As Boolean
    Get
    Return m_useImg
    End Get
    Set(value As Boolean)
    m_useImg = value
    End Set
    End Property
    Private m_image As Bitmap
    Public Property Image() As Bitmap
    Get
    Return m_image
    End Get
    Set(value As Bitmap)
    m_image = value
    End Set
    End Property
    Public Sub New()
    Me.SetStyle(ControlStyles.UserPaint, True)
    Me.DoubleBuffered = True
    Color1 = Color.Lime
    Color2 = Color.Green
    Color3 = Color.Red
    PositionColor2 = 0.55F
    End Sub
    Public Property GammaCorrected As Boolean
    Protected Overrides Sub OnPaint(e As PaintEventArgs)
    Dim rec As Rectangle = e.ClipRectangle
    rec.Width = CInt(rec.Width * (CDbl(Value) / Maximum)) - 4
    If ProgressBarRenderer.IsSupported Then
    ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle)
    Else
    e.Graphics.DrawRectangle(Pens.Gray, 0, 0, Me.Width, Me.Height)
    End If
    rec.Height = rec.Height - 4
    If m_useImg AndAlso Not Image Is Nothing Then
    Using t As New TextureBrush(Image)
    e.Graphics.FillRectangle(t, 2, 2, rec.Width, rec.Height)
    End Using
    Else
    Using l As New System.Drawing.Drawing2D.LinearGradientBrush(e.ClipRectangle, Color.Green, Color.Red, 0.0F)
    Dim lb As New System.Drawing.Drawing2D.ColorBlend()
    lb.Colors = New Color() {Color1, Color2, Color3}
    lb.Positions = New Single() {0, PositionColor2, 1.0F}
    l.InterpolationColors = lb
    l.GammaCorrection = Me.GammaCorrected
    e.Graphics.FillRectangle(l, 2, 2, rec.Width, rec.Height)
    End Using
    End If
    Using l2 As New System.Drawing.Drawing2D.LinearGradientBrush(e.ClipRectangle, Color.FromArgb(147, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), System.Drawing.Drawing2D.LinearGradientMode.Vertical)
    Dim lb As New System.Drawing.Drawing2D.ColorBlend()
    lb.Colors = New Color() {Color.FromArgb(40, 255, 255, 255), Color.FromArgb(147, 255, 255, 255), Color.FromArgb(40, 255, 255, 255), Color.FromArgb(0, 255, 255, 255)}
    lb.Positions = New Single() {0, 0.12F, 0.39F, 1.0F}
    l2.InterpolationColors = lb
    l2.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile
    e.Graphics.FillRectangle(l2, 2, 2, rec.Width, rec.Height)
    End Using
    If Me.ShowText Then
    Using sb As New SolidBrush(Me.ForeColor)
    Dim sz As SizeF = e.Graphics.MeasureString(Percentage.ToString("N0") + " %", Me.Font)
    e.Graphics.DrawString(Percentage.ToString("N0") + " %", Me.Font, sb, New PointF((Me.Width - sz.Width) / 2.0F, (Me.Height - sz.Height) / 2.0F))
    End Using
    End If
    If Value > 0 AndAlso _doMarqueeOverlay = False Then
    StartMarquee()
    End If
    If Value = Maximum - 1 Then
    StopMarquee()
    End If
    If _doMarqueeOverlay Then
    Dim rWidth As Single = _rWidth
    If rec.Width < rWidth Then
    rWidth = rec.Width
    End If
    If rWidth + _pos > rec.Width Then
    rWidth = rec.Width - _pos
    End If
    Using l As New System.Drawing.Drawing2D.LinearGradientBrush(New RectangleF(_pos + 2, 2, _rWidth, rec.Height), Color.FromArgb(127, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
    Dim lb As New System.Drawing.Drawing2D.Blend()
    lb.Factors = New Single() {1, 0, 1}
    lb.Positions = New Single() {0, 0.5F, 1.0F}
    l.Blend = lb
    'l.TranslateTransform(_pos - rWidth, 0);
    l.WrapMode = System.Drawing.Drawing2D.WrapMode.TileFlipXY
    e.Graphics.FillRectangle(l, _pos + 2, 2, rWidth, rec.Height)
    _pos += _posAdd
    If _pos >= rec.Width Then
    If _c < _posDelay Then
    _pos -= _posAdd
    _c += 1
    Else
    _pos = -_rWidth - _posDelay
    _c = 0
    End If
    End If
    End Using
    End If
    End Sub
    Private Sub StopMarquee()
    timer1.Stop()
    _doMarqueeOverlay = False
    End Sub
    Private Sub StartMarquee()
    _doMarqueeOverlay = True
    timer1.Interval = 10
    timer1.Start()
    End Sub
    Private Sub timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick
    timer1.Stop()
    Invalidate()
    timer1.Start()
    End Sub
    Protected Overrides Sub Dispose(disposing As Boolean)
    If timer1.Enabled Then
    timer1.Stop()
    End If
    timer1.Dispose()
    If Not Image Is Nothing Then
    Image.Dispose()
    End If
    MyBase.Dispose(disposing)
    End Sub
    End Class
    Regards,
      Thorsten

  • Progressbar in JTable

    Hi
    I have added a progressbar to a jtable. but when i add a new record, the earlier record's progressbars are edited. the rows/records are added at random, as the download progresses.
    how do i tackle this problem?
    Pls help me out. i have only 3 days left to complete my project.

    I am not able to understand what u r asking ?
    But I think you problem is you are not able to edit all table cell.
    I think for JTable u have implemented Renderer and Editor than in Editor's
    isCellEditable(java.util.EventObject eventObject)
    u need to return true than only you will be able to edit all cells.

  • How to get multiline text on progress bar

    Hi there,
    I have to use Progress Bar and need to show text in multiline.
    can anyone please suggest me how to achieve that.
    Thanks,
    Prashant

    can u guys figure out what really i am missing here?A spoon-fed solution, I suppose. So enjoy:
    // A JProgressBar with two lines of text.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.beans.*;
    public class PB2Lines extends JPanel implements
                             ActionListener, PropertyChangeListener {
        private TwoLinesProgressBar progressBar;
        private JButton startButton;
        private Task task;
        class Task extends SwingWorker<Void, Void> {
            public Void doInBackground() {
                int progress = 0;
                //Initialize progress property.
                setProgress(0);
                while (progress < 100) {
                    progress += 25;
                    setProgress(progress);
              if (progress==25)
                progressBar.setString("Eggs|added");
              else if (progress==50)
                progressBar.setString("Sugar|added");
              else if (progress==75)
                progressBar.setString("Milk|added");
              else
                progressBar.setString("Everything|done");
                    try {
                      Thread.sleep(500);
                    } catch (InterruptedException ignore) {}
                return null;
            public void done() {
                Toolkit.getDefaultToolkit().beep();
                startButton.setEnabled(true);
                setCursor(null); //turn off the wait cursor
        public PB2Lines() {
            super(new BorderLayout());
            //Create the demo's UI.
            startButton = new JButton("Start");
    //        startButton.setActionCommand("start");
            startButton.addActionListener(this);
            progressBar = new TwoLinesProgressBar(0, 100);
            progressBar.setPreferredSize(new Dimension(200,40));
            progressBar.setValue(0);
    //        progressBar.setStringPainted(true);
            progressBar.setString("Progress|Bar");
            JPanel panel = new JPanel();
            panel.add(startButton);
            panel.add(progressBar);
            add(panel, BorderLayout.PAGE_START);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
         * Invoked when the user presses the start button.
        public void actionPerformed(ActionEvent evt) {
            startButton.setEnabled(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            task = new Task();
            task.addPropertyChangeListener(this);
            task.execute();
         * Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                   JFrame frame = new JFrame("ProgressBar with 2 lines");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   JComponent newContentPane = new PB2Lines();
                   newContentPane.setOpaque(true); //content panes must be opaque
                   frame.setContentPane(newContentPane);
                   frame.pack();
                   frame.setVisible(true);
      class TwoLinesProgressBar extends JProgressBar {
        public TwoLinesProgressBar(int min, int max) {
          super(min, max);
        private int getXofCenteredString(String s) {
          int ix= getFontMetrics(getFont()).stringWidth(s);
          return (getWidth()-ix)/2;
        protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          int i= getString().indexOf('|');
          String s= getString().substring(0,i);
          int ix= getXofCenteredString(s);
          g.setColor(Color.BLACK);
          g.drawString(s, ix,15);
          s= getString().substring(i+1);
          ix= getXofCenteredString(s);
          g.drawString(s, ix,35);
    }

  • Interface update in heavy processing

    In heavy processing, interface contents (textbox , progress bar) can not update (being neglected??)
    is there any method to force it to get update??
    thx for your time in advance.

    Interesting enough I just finished adding a progressbar to a script I'm in the works on right now and I got it to work without using update() at all.
    I'm using CS5.5, not sure if that's why or not, but what I did for this one was...
    var mainRes ="group {orientation:'row', alignment:['fill','fill'], alignChildren:['fill','fill'],\
                                                                columnOne: Group{orientation:'column', alignment:['left','top'],\
         keyTransPB: Progressbar{minvalue:0, maxvalue:100, alignment:['fill','top']},\
    pal.grp = pal.add(mainRes);
    In a function way later in the script I have a simple for() loop that also contains...
    pal.grp.columnOne.keyTransPB.value++;
    and it seems to automatically update the gui without a problem. Maybe try calling your progress bar with it's full path instead of the variable name and see if that works. It might have something to do with functions and variables that declared outside of the function. Not sure if any of that made sense.

  • Preload Problems

    I downloaded some Preloader code from a previous poster. (see
    below):
    <<<Here is the pre-loader i promised you.
    Dont get scared tho, its actually really short. I just added
    alot of comments in there to help you understand what is going on
    in the code. Plus added a progressBar and Stroke to give some
    visuals on loading length.
    place this code on Frame 1 of your _root timeline. and make
    your movie start from Frame 3. on all layers, make sure there is
    Nothing on frames 1 and 2. except the preloading code.
    Attach Code
    stop();
    //******* Create progressBar and ProgressStroke ********\\
    this.createEmptyMovieClip("progressBar",
    this.getNextHighestDepth());
    progressBar.createEmptyMovieClip("progressStroke",
    this.getNextHighestDepth());
    //******* align progressBar on stage *****\\
    progressBar._x = Stage.width/2 - progressBar._xscale/2;
    progressBar._y = Stage.height/2;
    //******* draw progressBar stroke ******\\
    progressBar.progressStroke.lineStyle(1,0,100);
    progressBar.progressStroke.moveTo(-2,2);
    progressBar.progressStroke.lineTo(-2,5);
    progressBar.progressStroke.lineTo(102,5);
    progressBar.progressStroke.lineTo(102,2);
    //******* pre-loader code ***********\\
    this.onEnterFrame = function(){
    //******* create progressText **************\\
    this.createTextField("progressText", 100, progressBar._x,
    progressBar._y+10, 300, 20);
    // this is the formula to get the persentage that is loaded
    // Math.round just rounds up the number to a whole. So there
    is no decimals in the number
    // bytesLoaded divided by bytesTotal times 100. this gives
    you the percentage.
    var loaded:Number =
    Math.round(this.getBytesLoaded()/this.getBytesTotal() * 100 );
    // here we draw a red line to represent the ammount that is
    loaded
    //lineStyle is how you want it to look like..
    //first number is the Thickness of the line
    //second is the hexadecimal value for the color
    //third is the alpha value of the line
    //moveTo simply moves the "pen", basically its where you
    want to start drawing from.
    // first the _x value, then the _y value
    //lineTo simply draws a line to the destination you specify.
    // we are using the variable loaded for the _x position,
    because we want it to represent how much it has loaded.
    progressBar.lineStyle(2,0xFF0000,100);
    progressBar.moveTo(0, 3);
    progressBar.lineTo(loaded, 3);
    //here we tell the text filed to display the variable loaded
    progressText.text = "Loading... "+loaded+"%";
    // here we check to see if it has fully loaded. If it has,
    then we move to frame 3.
    if(loaded == 100){
    this.gotoAndPlay(3);
    delete this.onEnterFrame;
    I am fairly new to Flash and I am ussing Flash MX. I have
    been trying use it in the first 2 frames of my Flash movie,
    however, when I go to test it, I get the following:
    l_______________l
    Progress.....%
    and then nothing happens. It just sits there with no progress
    happening. Am I doing something wrong?

    Sorry about the confusion. I entered the code as it was. See
    the attached link to see how I viewed it in my Flash program. If
    you notice, at the top of the window the code:
    var loaded:Number =
    Math.round(this.getBytesLoaded()/this.getBytesTotal() * 100 );
    reads as:
    variables: loaded:Number =
    Math.round(this.getBytesLoaded()/this.getBytesTotal()*100):
    http://www.markselewacz.com/excess/flash_window.html

  • JLayeredPane and added Components

    Hi everybody,
    I have a panel for drawing, what is actually a JLayeredPane. With the add(someComponent, int layer) I am adding severals JPanel, on which I draw Rectangles for example.
    Now I need to change the layer of a certain JPanel in the layeredPane. This is no Problem (with setLayer(...)). But I have one JPanel, its bound by a Rectangle and I added with the add-Method a own Object (it's a line). The line has to be an object, because I added a MouseListener to that line.
    It appears like that:
    |    (1)    |
    |           |
    |           |
    |-----------|
    |           |
    |____________It's the line in the middle I'm talking about. So when I change the Layer of the JPanel (the Rectangle), the line has the correct bounds, but is displayed in the upper middle position in the Panel (no. (1) in the graphic).
    I tried to remove and re-add it, but nothing helps. Does anybody know the problem?
    Thanx for helping!!
    Robert4

    By default JLayeredPane uses null layout manager. So you have to set the bound of the component being added into JLayeredPane.

  • JLayeredPane problem:  How to remove object added at specific depth in

    JLayeredPane?
    For instance, I have a class called BlobEvolution. In that class, I have an array of JLayeredPanes squrares[row][col][depth]. I add an object Blob, to a new LayeredPane cell, using the statement LayeredPane cell=new LayeredPaine();
    cell.add(Blob, new Integer(2));, then I add the cell to a contentPane using contentPane.add(cell). I set squares[row][col][0] to point to cell, and squares[row][col][2] refers to the blob object in the cell.
    but now I want to remove a certain layer from the cell and repaint that cell to display only the deeper contents of the cell. Or I want to remove the blob in the cell, which is always at depth 2 in the cell. How would I do that? And how do I repaint only that cell?

    By the way, both objects that I add to the layeredpanes extend JLayeredPanes.
    I actually tried to do this remove call: squares[row][col][0].remove(2);
    I was trying to point to the cell layeredpane that contains the two objects, blob, and plankton. blob was placed at depth 2, so I tried to remove the depth 2 component. but I get an ArrayIndexOutofBounds Exception and it says no such child:2. java.awt.Container.getComponent(Container.java:237)
    javax.swing.JLayeredPane.remove(JLayeredPane.java:216)
    BlobEvolution.removeblob(BlobEvolutioin.java:133)
    That's essentially the error message I get in the console. Obviously, it's the remove statement above that's giving me the problem, but I don't know what's wrong with it and how to fix it.
    Please, if anyone can help I'd really appreciate it.

  • JLabel Image Icon lost after added to JLayeredPane

    This is probably that is relatively trivial:
    I have a created a simple class that extends a JPanel
    Within the JPanel I add a JLayeredPane
    Within the JLayeredPane I add two JLabels
    The two JLabels are image placeholders (set using the *.setIcon method)
    Images are set in the JLabels using a public method setImage (for each label respectively)
    In the super class that invokes this, the object (myPanel) with the JPanel shows the panel fine along with the JLayeredPane, anyways this is the problem say "myPanel" calls the method setImage (myPanel.setImage...), the image is set in the JLabel componenent in the JLayeredPane but it seems to get erased when a windows goes over!
    What am I doing wrong?
    Thank you for your time.

    import java.awt.*;
    import javax.swing.*;
    public class Layer_Test extends JFrame {
        public Layer_Test() {
            setTitle("Layer Test");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setSize(400,300);
            setLocationRelativeTo(null);
            getContentPane().add(new MyPanel(), BorderLayout.CENTER);
        public static void main(String args[]) {
            new Layer_Test().setVisible(true);
    class MyPanel extends JPanel{
        MyPanel(){
            layeredPane = new JLayeredPane();
            label_1 = new JLabel();
            label_2 = new JLabel();
            layeredPane.setPreferredSize(new Dimension(300, 200));
            label_1.setIcon(new ImageIcon(MYPATH+"toolbarButtonGraphics\\general\\About16.gif"));
            label_1.setBounds(0, 0, 16, 16);
            layeredPane.add(label_1, new Integer(1));
            label_2.setIcon(new ImageIcon(MYPATH+"toolbarButtonGraphics\\general\\Copy16.gif"));
            label_2.setBounds(0, 100, 16, 16);
            layeredPane.add(label_2, new Integer(2));
            add(layeredPane);
        private JLabel label_1, label_2;
        private JLayeredPane layeredPane;
        private final String MYPATH = "C:\\Documents and Settings\\Uhres Andr�\\Mes documents\\";
    }

  • Help adding to JLayeredPane

    basically I need to create a panel with a background, then use JLayeredPane to put 2 other panel on top of each other over the background. The problem is that each panel will display properly by with the background but not all 3 together.
    /* main gui class for the four score game.*/
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GuiMain extends JFrame
         //declare variables
         private JButton quit = new JButton("Quit");
         private JButton restart = new JButton("Restart");
         //panels
         private BoardPanel myBoard = new BoardPanel();
         private JPanel South = new JPanel();
         //embedded main class used for testing
         public static void main(String[] args)
              new GuiMain();
         /*no arg constructor which zeroes the bead array, creates a new window using the boxlayout manager,
          * creates the board, and adds the quit/restart buttons
         public GuiMain()
              super("Four Score");
              this.addComponentListener(new ResizeListener());
              setSize(640,480);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
              myBoard.setBorder(BorderFactory.createLineBorder(Color.black));
              restart.addActionListener(new ResetListener());
              quit.addActionListener(new QuitListener());
              South.add(quit);
              South.add(restart);
              South.setBorder(BorderFactory.createLineBorder(Color.green));
              add(myBoard, BorderLayout.CENTER);
              add(South, BorderLayout.SOUTH);
              repaint();
              setVisible(true);
         //sends a new complete set of beads to the board
         public void updateBoard(int[][][] newBeads)
              myBoard.updateBoard(newBeads);
         //updates a specific bead then calls the updateboard method
         public void updateBead(int x, int y,int z, int color)
              myBoard.updateBead(x, y, z, color);
         //checks if a peg at a set of coordinates is full
         public boolean isFull(int x, int y)
              return myBoard.isFull(x,y);
         /* customer action listener for the reset button
          * resets the beads array to all zeroes (empty) and
          * sends the command "reset;" to the player
         private class ResetListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   int[][][] beads = new int[4][4][4];
                   for(int i = 0; i < 4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4;k++)
                                  beads[i][j][k] = 0;
                   updateBoard(beads);
                   sendCommand("reset;");
         /* customer action listener for the quit button
          * sends a "quit;" command to the player.
         public class QuitListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   sendCommand("Quit;");
                   System.exit(0);      //REMOVE AFTER TESTING
         public void sendCommand(String command)
              //so far unused as I still need to work out sending the commands to the appropriate place
         public class ResizeListener implements ComponentListener
              public void componentResized(ComponentEvent e)
                   if(getWidth() != 640 || getHeight() != 480)
                        setSize(640,480);
              public void componentMoved(ComponentEvent e){}
              public void componentShown(ComponentEvent e) {}
              public void componentHidden(ComponentEvent e) {}
    /* class which creates the actual game board
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BoardPanel extends JPanel
         enum BeadStatus {EMPTY, WHITE, BLACK};
         //variables, basic x and y starting points for drawing the board.
         final int x = 100;
         final int y = 100;
         final int[] boardxPoints = {x,x+320,x+420,x+100};
         final int[] boardyPoints = {y,y,y+200,y+200};
         //array for the beads
         private int[][][] beads = new int[4][4][4];
         private PegButton[] pegs = new PegButton[16];
         public JPanel pegsPanel = new JPanel();
         public BeadLayer beadsPanel = new BeadLayer();
         JLayeredPane layers = new JLayeredPane();
          * no arg constructor which simply zeroes the bead array
         public BoardPanel()
              pegsPanel.setLocation(0,0);
              pegsPanel.setPreferredSize(new Dimension(630,480));
              pegsPanel.setOpaque(false);
              setOpaque(false);
              drawPegs();
              layers.setBorder(BorderFactory.createTitledBorder(
            "Test"));
              layers.add(pegsPanel, 1);
              beadsPanel.setLocation(0,0);
              beadsPanel.setPreferredSize(new Dimension(630,480));
              //layers.add(beadsPanel, new Integer(1));
              add(layers);
          * overriden paint component method which draws out the board, pegs, and beads
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.setColor(Color.blue); //board background color
              g.fillPolygon(boardxPoints,boardyPoints, 4); //create the basic board shape
              drawGrid(g);
          * method to draw out the grid shape
         public void drawGrid(Graphics g)
              int p;
              int q;
              g.setColor(Color.cyan);
              //draw the vertical lines
              for(int i=0; i<5;i++)
                   p=x+(i*80);
                   g.drawLine(p,y,p+100,y+200);
              //draw the horizontal lines
              for (int j=0; j<4; j++)
                   p=x+(j*25);
                   q=y+(50*j);
                   g.drawLine(p,q,p+320,q);
              g.drawLine(x+100,y+200,x+420,y+200);
          * draw out the 16 pegs in proper position
         public void drawPegs()
              int p = x;
              int q = y;
              int n;
              for(int i=0; i<4;i++)
                   for(int j=0; j < 4; j++)
                        p = x+(j*80+40)+(i*25+12)-5;
                        q = y+(i*50+25)-80;
                        //g.fillRect(p,q,10,75);
                        //g.fillArc(p, q-5, 10, 10, 0, 180);
                        n =j+(i*4);
                        pegs[n] = new PegButton(i,j);
                        pegs[n].setLocation(p,q);
                        pegsPanel.add(pegs[n]);
         //updates the board by reading in a new bead array then repainting
         public void updateBoard(int[][][] beads)
              for(int i = 0; i < 4; i++)
                   for(int j = 0; j<4; j++)
                        for(int k=0; k<4; k++)
                             this.beads[i][j][k] = beads[i][j][k];
              repaint(); //inheirited method which causes paintcomponent to be called again
         public void updateBead(int x, int y, int z, int color)
              beads[x][y][z] = color;
              repaint();
         //returns true if a peg is full
         public boolean isFull(int x, int y)
              if (beads[x][y][3] != 0)
                   return false;
              return true;
    import java.awt.*;
    import javax.swing.*;
         public class BeadLayer extends JPanel
              enum BeadStatus {EMPTY, WHITE, BLACK};
              final int x = 100;
              final int y = 100;
              private int[][][] beads = new int[4][4][4];
              public BeadLayer()
                   for(int i = 0; i < 4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4; k++)
                                  beads[i][j][k] = 1;
                   repaint();
              //method which takes in a set of coordinates and a color then draws the bead at the correct position
              public void paintComponent(Graphics g)
                   //reads through the bead array and calls the drawbead method where required
                   for(int i = 0; i<4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4;k++)
                                  if(beads[i][j][k] == 1)
                                       drawBead(i,j,k,BeadStatus.BLACK,g);
                                  else if(beads[i][j][k] == 2)
                                       drawBead(i,j,k,BeadStatus.WHITE,g);
              public void drawBead(int x, int y, int z, BeadStatus color, Graphics g)
                   x = this.x+(x*80+40)+(y*25+12)-10;
                   y = this.y+(y*50+25)-18-(18*z);
                   if(color == BeadStatus.WHITE)
                        g.setColor(Color.WHITE);
                   else
                        g.setColor(Color.BLACK);
                   g.fillOval(x, y, 20, 18);
                   g.setColor(Color.GREEN);
                   g.drawOval(x, y, 20, 18);
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PegButton extends JButton implements ActionListener
         private String coord;
         public PegButton(int x, int y)
              getCoord(x,y);
              this.setPreferredSize(new Dimension(10,75));
              this.setBorderPainted(false);
              addActionListener(this);
         public void getCoord(int x, int y)
              y+=1;
              switch(x)
                   case 0: coord = "A"+Integer.toString(y)+".";
                             break;
                   case 1: coord = "B"+Integer.toString(y)+".";
                             break;
                   case 2: coord = "C"+Integer.toString(y)+".";
                             break;
                   case 3: coord = "D"+Integer.toString(y)+".";
                             break;
         public void setLocation(int x,int y)
              if (y != 5)
                   super.setLocation(x,y);
         public void paintComponent(Graphics g)
              g.setColor(Color.RED);
              g.fillRect(0, 7, 10, 75);
              g.fillArc(0, 0, 10, 15, 0, 180);
         public void actionPerformed(ActionEvent e)
              System.out.println(coord);
    }

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5274611

  • How can i use Progressbar for loading data to DataGridView using DataTable

    I have a datatable which have 3 columns and set this datatable to be datasouce of datagridview.
    I want to add 100000 rows into this  table while
     table is adding , I want Progressbar to calculate and show the remaining
    percentage.
    How can i do this ?

    I've seen this done 2 different ways.
    You could either set the ProgressBar.Maximum to: 100, or  to QuantityToLoad. 
    example:
    Option Strict On
    Option Explicit On
    Option Infer Off
    Public Class Form1
    Dim QuantityToLoad As Integer = 100000
    Dim increment As Double = 100 / QuantityToLoad
    Private Sub btnExample1_Click(sender As Object, e As EventArgs) Handles btnExample1.Click
    ProgressBar1.Value = 0
    ProgressBar1.Maximum = 100
    ProgressBar2.Value = 0
    ProgressBar2.Maximum = QuantityToLoad
    For i As Integer = 1 To QuantityToLoad
    'Some code
    'Some code
    'Some code
    'Done loading item
    ProgressBar1.Value = CInt(i * increment)
    ProgressBar2.Increment(1)
    Label1.Text = ProgressBar1.Value.ToString & "% complete."
    Label2.Text = CStr(Math.Round((ProgressBar2.Value / ProgressBar2.Maximum) * 100, 2)) & "% complete."
    Application.DoEvents()
    Next
    MsgBox("done")
    End Sub
    End Class
    “If you want something you've never had, you need to do something you've never done.”
    Don't forget to mark
    helpful posts and answers
    ! Answer an interesting question? Write a
    new article
    about it! My Articles
    *This post does not reflect the opinion of Microsoft, or its employees.

  • How to use JLayeredPane with LayoutManager

    Hi!
    I'm having problems with JLayeredPane. I simply cannot understand how to use it. I would like to have a button on top of my JDialog (The Dialog should have two components, a custom drawing panel and a JButton to close it with (want to keep the window undecorated, thus the need for the close-button)).
    AboutDialog
    |******Animation here***<- ------- CustomPanel
    |**************************|
    | *********and here*******|
    | ******** ______*********|
    | &here | Close | &here |<-----JDialog
    | ******** ----------*********|
    +------------------^---------- --+
    ...........................|
    ..........................JButton
    This is what i tried, after finding out that JLayeredPane has a null layout:
    class FilledLayeredPane extends JLayeredPane {   
    public FilledLayeredPane() {
         super();
         addComponentListener(new ComponentAdapter() {
              public void componentResized(ComponentEvent e) {
              compRes();
    //Resize all components to fit
    protected void compRes() {
         Component[] comps = getComponents();
         Rectangle bounds = getBounds();
         for (int i=0; i<comps.length;i++)
         ((JComponent) comps).setBounds(bounds);
    Then i added two panels with different z-order. One panel with the button, and also the CustomPanel.
    However, the resize algorithm is ugly, and it doesn't work as it should at all. I'm getting really random behaviour from this...
    How am i supposed to do?? I want the LayeredPane to layout the components i add to it! At least make sure that all added component fill up the size of the LayeredPane...
    Plz help!

    Forgive me, that was bs. I get correct componentResized notificatiuons every single time.
    The problem is: My manual updates of the JPanel inside the JLayeredPanel DO work, and the JPanel is resized correctly (otherwise I would see elements from behind shinig through).
    BUT the JPanel doesn't always take the fact that it is manually resized as a reason to layout its components!!!
    In my case, it works, as far as I've seen, EXACTLY EVERY SECOND TIME!!!
    The solution is indeed VERY simple: After manually resizing an element with a layout that is non-null, call layout() on that element!!!
    In my case,
    jpanelXXX.setSize(size); jpanelXXX.layout();works wonders!!!

  • JTable in JLayeredPane - resize table header cursor

    Hey everybody, I have searched all over this forum and the net for an answer to this problem. I have a class that adds a JComponent to a JLayeredPane in the default layer. In another layer above the default layer is a JComponent that exists only to provide a 'pretty' image border with round corners that overlap the component below it. It works and looks very good. The only problem I have found is that if the JComponent that is added (in the default layer) is a JTable the cursor no longer changes to the resize cursor (<->) when mousing over the table header column edges. I can still resize the columns but I need to have the cursor change to indicate that the colums can be resized for user friendliness. I assume that the mouse events are getting trapped by the upper layer in the JLayeredPane and aren't reaching the JTable in the lower layer as they need to.
    I have tried swapping the two layers but when I do that the corners of the component that I want to add the border to overlap over the nice round corners of the border which defeats the purpose.
    If anyone has any suggestions, or even better a solution, that would be great!
    Thanks,
    Erik

    table.getTableHeader().setVisible(false); will
    help.This is necessary, but probably not quite sufficient for picky users. You may also want to set the min, max, and preferred dimensions of the table header to 0,0, otherwise you get what looks like a top-only border.
    Michael Bushe

  • JLayeredPane - keeping all contained components filling the layeredPane

    I'm having some troubles keeping contained components inside a JLayeredPane so they're all filling the pane.
    The desired effect I want is to have a region of the window that contains two panels -- one for standard view/editing, and an overlayed transparent panel above it, which, at times, will show icons overlayed over the base panel -- basically an OSD layer over a panel that will be showing video.
    I've gone the approach of using a JLayeredPane and adding the base panel, but I'm having troubles getting it to make sure it fills the entirety of the JLayeredPane.
    I thought of several approaches:
    1.) Set up the JLayeredPane with a BorderLayout, and set the components all to CENTER, but then I realized that with BorderLayout, each position can only have one component assigned to it.
    So, this approach is a no-go. :(
    2.) Set up a ComponentListener on the JLayeredPane, listening for componentResized, and resizing the contained panels to event.getComponent().getSize(). This approach did result in a resize happening on the component I was testing, but alas, it resizes it to the original, pre-resized size! Reading the docs, and what others have said on the msg board, this seems to be going against what I'm reading and hearing about.
    Does anyone have any ideas for me? I'm all ears.
    Is there a radically different approach I could take?
    What I'm going after is kinda like the glassPane feature on a Frame, but I'm not working with a frame, just one panel inside the frame of my main application window.. And I'd like it so I could encapsulate the OSD panel in it's own derived class -- that's what I'm doing right now -- so I can have custom methods for manipulating the OSD.

    bsampieri wrote:
    For this type of situation, I usually subclass JLayeredPane and override the doLayout() method. In there, assuming you want to have everything on it's layer fill the layer it's on, just set it's bounds to (0, 0, w, h) with the width/height of the layered pane itself. Aha! That worked like a charm! Just what I was after. I need to get more comfortable altering the inner-workings of swing components through subclassing.
    If you need something more advanced, you'd have to have a way to determine which components should go where/what size.Nope -- I didn't need to subclass in this case -- I want each and every item in the JLayeredPane to fill the entirety of the container. I sorta figured that there should be a relatively easy solution to it, but I hadn't been able to figure out how, and googling it up didn't seem to result in any useful information on the subject.
    Thank you very much bsamieri!
    Here's exactly what I ended up doing:
    package com.tripleplayint.newvideopreviewermockup;
    import java.awt.Component;
    import javax.swing.JLayeredPane;
    * A panel widget that allows components to be layered on top of one another,
    * where each component fills the entirety of this container.
    * This is only useful when all but the lowest layer is set transparent, as
    * the highest opaque layer will obscure any layers below it.
    * @NOTE If one wants to move the layers to choose which one is visible, your
    * better option is to use a JPanel with the CardLayout.
    * @author kkyzivat
    public class FilledLayeredPane extends JLayeredPane {
         * Layout each of the components in this JLayeredPane so that they all fill
         * the entire extents of the layered pane -- from (0,0) to (getWidth(), getHeight())
        @Override
        public void doLayout() {
            // Synchronizing on getTreeLock, because I see other layouts doing that.
            // see BorderLayout::layoutContainer(Container)
            synchronized(getTreeLock()) {
                int w = getWidth();
                int h = getHeight();
                for(Component c : getComponents()) {
                    c.setBounds(0, 0, w, h);
    }

  • Resizing Components in a JLayeredPane

    Hello,
    I'm brand new to Java (formerly a VB man). I'm creating an application where icons are displayed on a background image and can be dragged around the window. The background image and the icons need to resize with the window.
    I've managed to get the back ground image to resize but can't work out how to get the icon images to resize as well. I also need to keep their relative positions as well.
    I have three classes which extend JFrame, JLayeredPane and JPanel to construct the display. I have attached them below.
    If anyone can help or at least point me in the right direction I would be very grateful indeed.
    Best regards
    Simon
    package imagelayers;
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SecondFrame extends JFrame
    private JLayeredPane m_layeredPane;
    private MovingImage m_movImage1, m_movImage2, m_movImage3;
    private BackgroundImage m_background;
    public SecondFrame() {
    super("Moving Images");
    setLocation(10,10);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Load the background image in a JPanel
    ImageIcon kcIcon = new ImageIcon("images/kclogo.gif");
    m_background = new BackgroundImage(kcIcon);
    setSize(kcIcon.getIconWidth(), kcIcon.getIconHeight());
    m_movImage1 = new MovingImage("images/dukewavered.gif", 0);
    m_movImage2 = new MovingImage("images/dukewavegreen.gif", 1);
    m_movImage3 = new MovingImage("images/dukewaveblue.gif", 2);
    m_background.add(m_movImage1 , JLayeredPane.DRAG_LAYER);
    m_background.add(m_movImage2 , JLayeredPane.DRAG_LAYER);
    m_background.add(m_movImage3 , JLayeredPane.DRAG_LAYER);
    m_movImage2.topLayer = 2;
    Container contentPane = getContentPane();
    contentPane.add(m_background);
    setVisible(true);
    public static void main(String[] arguments)
    JFrame frameTwo = new SecondFrame();
    package imagelayers;
    import java.awt.*;
    import javax.swing.*;
    public class BackgroundImage extends JLayeredPane
    private Image m_backgroundImage;
    public BackgroundImage(ImageIcon bg)
    m_backgroundImage = bg.getImage();
    setBorder(BorderFactory.createTitledBorder(""));
    public void paintComponent(Graphics g)
    g.drawImage(m_backgroundImage,0,0,getWidth(),getHeight(),this);
    package imagelayers;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import java.awt.*;
    import java.awt.event.*;
    public class MovingImage extends JLabel implements MouseListener, MouseMotionListener
    private Image m_theImage;
    private ImageIcon m_theImageIcon;
    private int nStartX, nStartY;
    static int topLayer;
    public MovingImage(String imgLocation, int layerNum)
    addMouseListener(this);
    addMouseMotionListener(this);
    m_theImageIcon = new ImageIcon(imgLocation);
    m_theImage = m_theImageIcon.getImage();
    setBounds(0, 0, m_theImageIcon.getIconWidth(), m_theImageIcon.getIconHeight());
    public void paintComponent(Graphics g)
    g.drawImage(m_theImage,0,0,getWidth(),getHeight(),this);
    public void mousePressed(MouseEvent e)
    JLayeredPane imagesPane = (JLayeredPane)getParent();
    imagesPane.setLayer(this,topLayer,0);
    nStartX = e.getX();
    nStartY = e.getY();
    public void mouseMoved(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseDragged(MouseEvent e)
    setLocation(getX() + e.getX() - nStartX, getY() + e.getY() - nStartY);
    }

    Try useing the JFrames show() method or setVisible(true) method after you have added all the other components.
    If that doesnt work use the JFrames validate() method, inherited from Container, after one of the previous methods.
    Hope this helps

Maybe you are looking for

  • XMLP Desktop 5.6.2 vs BI Publisher template builder for word?

    Hi, Is anybody know what's the difference betweent these two product? When i installed XMLP desktop 5.6.2 i could see option for SQL and Report wizard under Data tab. But in BI publisher template builder i can see only XML data and XML schema under D

  • Oracle 8i Post Installation Prob..

    Respected members I succesfully installed Oracle8i on linux (redhat linux 6.1) . Everything is ok and got a succesfull installation message. After it i set Path and everything but but getting listner not available or sometime oracle not available mes

  • Problem migrating from 5.0 to 7.0 - ISBEGINNING

    I am having an issue adding the ISBEGINNING property to the time membersheet. I selected 'Modify Dimension Property' in the Time dimension and see the ISBEGINNING property was added automatically. When I go to 'Maintain Dimension Members', add the ne

  • MDM Syndication - IDOC mapping ?

    Hi Gurus, I was going thru the following blog. MDM Syndication /people/harrison.holland5/blog/2006/11/27/mdm-syndication What is the purpose of remote system(ECC) in MDM ? Is it required to get IDOC structure from ECC into MDM repository ? If so, wha

  • Help Requred on WebServices

    Hi All,   I require some information about Web services.. 1.  Is web services can be developed by XI or EP ? 2.  What is the Use of webservices in the Context of XI? 3.   How much secure these webservcies than FTP? 4.   Is there any SAP webservices?