Repaint() for JPanels

HI ALL,
I am doing a line plot of image data, and displaying it on a JPanel.
In my App, I added some buttons for I can transition between the plots.
I can grab all the data at once and display all in separate tabs, but
when I changed it to this buttons format, the plot never updates.
Here is my button function to update the panel.
     myPrevButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
                    try{
                         p = (Plotable)myPlotables.elementAt(currentPlot-2);
                    myMeanPlotPanel = new XYPlotJPanel(p);
               p = (Plotable)list.nextElement();
                         currentPlot = myPlotables.indexOf(p);
          mySDPlotPanel = new XYPlotJPanel(p);
                         myMainPanel.repaint();
          } catch (NotEnoughDataException nede){
               MsgPopup msg = new MsgPopup(LocalizedError.constructFormattedErrorString(nede));
               msg.show();
When I read the images, I use a vector to order the images, and "list" is an enumertion variable in this function.
The mainPanel holds both subpanels. Now the app will show only the first plot, but will not update any other plots. I have tried repaint() all panels before, it did not work.
Does anyone know how to get this to update or replot,refresh, ...or etc....?
I have not ideas now.
Thanks!

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SelectingGraphs {
  static int plotIndex = 0;
  public static void main(String[] args) {
    float[] data1 = {
      1.2f, 2.0f, 3.7f, 4f, 2.9f, 4.9f, 3.1f, 4.02f
    float[] data2 = {
      29f, 18.2f, 75f, 34f, 92f, 15f, 50.9f, 42.3f
    float[] data3 = {
      90f, 44f, 53.7f, 67.2f, 49.2f, 79f, 80.3f, 55.2f
    final float[][] allData = {
      data1, data2, data3
    Plot
      plot1 = new Plot(),
      plot2 = new Plot(),
      plot3 = new Plot();
    final Plot[] plots = {
      plot1, plot2, plot3
    for(int i = 0; i < plots.length; i++)
      for(int j = 0; j < allData.length; j++)
plots[i].plot(allData[i][j]);
final JPanel panel = new JPanel();
panel.add(plot1);
// south panel
final JButton
lastButton = new JButton("last"),
nextButton = new JButton("next");
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
panel.remove(plots[plotIndex % 3]);
if(button == lastButton) {
--plotIndex;
if(plotIndex < 0)
plotIndex = 2;
if(button == nextButton)
++plotIndex;
panel.add(plots[plotIndex % 3]);
panel.revalidate();
panel.repaint();
lastButton.addActionListener(l);
nextButton.addActionListener(l);
JPanel southPanel = new JPanel();
southPanel.add(lastButton);
southPanel.add(nextButton);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.getContentPane().add(southPanel, "South");
f.setSize(400,300);
f.setLocation(400,300);
f.setVisible(true);
class Plot extends JPanel {
float PAD = 25;
List dataList;
public Plot() {
dataList = new ArrayList();
setBackground(Color.white);
setPreferredSize(new Dimension(200,200));
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
float width = getWidth();
float height = getHeight();
float xStep = (width - 2*PAD)/(dataList.size() - 1);
float x = PAD;
float y;
// scale data
float max = ((Float)Collections.max(dataList)).floatValue();
float min = ((Float)Collections.min(dataList)).floatValue();
float vertSpace = height - 2*PAD;
float yOffset = height - PAD;
float yDataOffset = (min >= 0 ? min : max > 0 ? 0 : max);
float scale = vertSpace/(max - min);
float yOrigin = yOffset + (min > 0 ? 0 : max > 0 ? scale*min : - vertSpace);
// draw ordinate
g2.draw(new Line2D.Float(PAD, PAD, PAD, yOffset));
// draw abcissa
g2.draw(new Line2D.Float(PAD, yOrigin, width - PAD, yOrigin));
// label ordinate limits
g2.drawString(String.valueOf(max), 10, PAD - 10);
g2.drawString(String.valueOf(min), 10, yOffset + PAD/2);
g2.setStroke(new BasicStroke(4f));
g2.setPaint(Color.red);
for(int j = 0; j < dataList.size(); j++) {
y = yOrigin - scale * (((Float)dataList.get(j)).floatValue() - yDataOffset);
g2.draw(new Line2D.Float(x, y, x, y));
x += xStep;
protected void plot(float input) {
dataList.add(new Float(input));
repaint();

Similar Messages

  • Urgent: Repaint, JTable, JPanel...

    I know there've been a few posts about using repaint() for JTable...but my layout's a bit different than the ones already mentioned and trying to update my table is driving me crazy...
    i have a table class which extends a JPanel...
    an instance of this is created in a separate class within a JPanel...THIS Panel is inside a scrollpane (the table itself isn't)...this class has a button, on the click of which the table needs to be updated.
    Now, should i be repainting the table, the table's panel, the parent panel, or the scrollpane? Or should i be doing something compeltely different?
    PLEASE HELP!

    [http://forum.java.sun.com/thread.jspa?threadID=5306228&tstart=0]

  • Background image  for JPanel using UI Properties

    Is there any way to add background image for JPanel using UI Properties,
    code is
    if (property.equals("img")) {
    System.out.println("call image file in css"+comp);
    //set the background color for Jpanel
    comp.setBackground(Color.decode("#db7093"));
    here the comp is JPanel and we are setting the background color,
    Is there any way to put the Background image for the JPanel ????

    KrishnaveniB wrote:
    Is there any way to put the Background image for the JPanel ????Override the paintComponent(...) method of JPanel.
    e.g.
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    public class ImagePanel {
        public void createAndShowUI() {
            try {
                JFrame frame = new JFrame("Background Image Demo");
                final Image image = ImageIO.read(new File("/home/oje/Desktop/icons/yannix.gif"));
                JPanel panel = new JPanel() {
                    protected void paintComponent(Graphics g) {
                        g.drawImage(image, 0, 0, null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(new Dimension(400, 400));
                frame.setContentPane(panel);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException ex) {
                ex.printStackTrace();
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new ImagePanel().createAndShowUI();
    }

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Problem with repaint() in JPanel

    Hi,
    This is the problem: I cyclically call the repaint()-method but there is no effect of it.
    When does it appear: The problem occurs by calling the repaint()-method of a JPanel -class.
    This is what i am doing: The repaint() is called from a different class which is my GUI. I do this call in an endless loop which is done within a Thread.
    I tried to add a KeyListener to the JPanel-class and there I called the repaint()-method when i press a Key. Then the Panel is repainted.
    so I implemented a "callRepaint"-method in the JPanel-class that does nothing else than call repaint() (just like the keyPressed()-method does). But when i cyclically call this "callRepaint"-method from my GUI nothing happens.
    Now a few codedetails:
    // JPanel-class contains:
    int i = 0;
    public void callRepaint(){
                    repaint();
    public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawLine(i++,0,200,200);
    public void keyPressed(KeyEvent e) {
            repaint();                       // This is working
    //GUI-class contains:
    // This method is called cyclically
    public void draw() {
                  lnkJPanelclass.repaint();             // This calling didn't work
                  // lnkJPanelclass.callRepaint();  // This calling didn't work     
    Thanks for your advices in advance!
    Cheers spike

    @ARafique:
    This works fine:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Date;
    import javax.swing.*;
    public class Test extends JFrame implements ActionListener{
        private JTextField label;
        private Timer timer;
        private Container cont;
        public Test() {
            label = new JTextField("",0);
            timer = new Timer(1000,this);
            cont = getContentPane();
            cont.add(label);
            setSize(250,70);
            setDefaultCloseOperation(3);
            setVisible(true);
            timer.start();
        public void actionPerformed(ActionEvent e){
            label.setText(new Date(System.currentTimeMillis()).toString());
        public static void main(String[] args){
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Test();
    }no repaint()/revalidate() needed

  • Repaint() in JPanel doesn't align correctly

    Hey all,
    I'm running into this problem with a program I'm writing for work. It's basically a dispatch board which connects to our SQL server via ODBC. When the user presses a "Next" or "Prev" button, the dates will change and show the dispatching for the next or previous week respectively. However, the refreshed components go where they are supposed to, but the old screen is underneath, and shifted slightly so that nothing aligns. In turn, you can make heads or tails as to what's happening. However, if you select File -> Refresh from my menubar (calls repaint() the same way) everything is repainted correctly. Any ideas?
    package dispatchBoard.DispatchBoard;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.sql.*;
    import javax.swing.JPanel;
    import sun.misc.Queue;
    public class DB_MainWindow extends JPanel implements MouseListener{
         private static final long serialVersionUID = 1L;
         private int _xRes, _yRes;
         private int _techs;
         private String _dayOption, _monday, _tuesday, _wednesday, _thursday, _friday, _odbcName, _databaseName, _currYear;
         private String[] _months;
         private Tech _myTechList;
         private Font _defaultFont;
         DB_Frame _mainFrame;
         private Calendar cal = new GregorianCalendar();
         public DB_MainWindow(String _resolution, String optionString, String ofTechs, DB_Frame frame, String _odbc, String _database, String _year)
              _xRes = Integer.valueOf(_resolution.substring(0, findCharPosition(_resolution, 'x'))).intValue() - 5;
              _yRes = Integer.valueOf(_resolution.substring(findCharPosition(_resolution, 'x')+1)).intValue() - 30;
              _techs = Integer.valueOf(ofTechs).intValue();
              _dayOption = optionString;
              _mainFrame = frame;
              _odbcName = _odbc;
              _databaseName = _database;
              _currYear = _year;
              setDaysFiveStraight();
              System.out.println(_xRes + " " + _yRes);
              this.setBackground(Color.GRAY);
              this.setPreferredSize(new Dimension(_xRes,_yRes));
              this.addMouseListener(this);
         public void paint(Graphics g)
              _myTechList = null;
              int _spacing = 0;
              int _spacing2 = 0;
              g.setColor(Color.BLACK);
              g.drawLine(60,0,60,_yRes);
              _defaultFont =g.getFont();
              //draw tech barriers
              for (int i = 1; i < _techs+1; i ++)
                   _spacing = _yRes / (_techs+1);
                   g.drawLine(0, _spacing*i, 1366, _spacing*i);
              //draw day barriers
              for (int j = 1; j < 5; j++)
                   _spacing2 = (_xRes-60) / 5;
                   g.drawLine(_spacing2*j + 60, 0, _spacing2*j + 60, 768);
              int _curPos = 60, _timePos = 0;
              int _time[] = {8,9,10,11,12,1,2,3,4,5};
              for (int k = 0; k < 5; k++)
                   _curPos = 60+(k*_spacing2);
                   for (int l = 0; l < 9; l++)
                        g.drawLine( _curPos + (l*(_spacing2/9)), 0+_spacing, _curPos + (l*(_spacing2/9)), _yRes);
                        String _tempString = ""+_time[_timePos];
                        g.drawString(_tempString, _curPos + (l*(_spacing2/9)), _spacing);
                        _timePos++;
                   _timePos = 0;
              //draw graph labels
              System.out.println(_dayOption);
              g.drawString("TECHS", 10, _spacing);
              g.drawString("Monday "+_monday, 60+(_spacing2/2) - 23, _spacing/2);
              g.drawString("Tuesday "+_tuesday, 60+_spacing2+(_spacing2/2) - 26, _spacing/2);
              g.drawString("Wednesday "+_wednesday, 60+2*_spacing2+(_spacing2/2) - 33, _spacing/2);
              g.drawString("Thursday "+_thursday, 60+3*_spacing2+(_spacing2/2) - 28, _spacing/2);
              g.drawString("Friday "+_friday, 60+4*_spacing2+(_spacing2/2) - 25, _spacing/2);
               * At this point the default grid, including all labels, have been drawn on
               * the dispatch board.  Now, we have to fetch the data from the SQL server,
               * place it into some sort of form (possibly 2d array?!) and then print it out
               * on the board....
               * Here goes!
    //          this.addMouseMotionListener(this);
    //          g.drawRect(_mousePosition.x, _mousePosition.y, 10, 10);
              fillInTimes(g, _spacing, _spacing2);
         public void setDaysFiveStraight()
              if (_dayOption.equals(new String("work_week")))
                   _monday = new String("");
                   _tuesday = new String("");
                   _wednesday = new String("");
                   _thursday = new String("");
                   _friday = new String("");
                   String[] _months2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
                   _months = _months2;
                    * Sunday = 1
                    * Monday = 2
                   System.out.println("DAY OF THE WEEK = "+cal.get(Calendar.DAY_OF_WEEK));
                   if (cal.get(Calendar.DAY_OF_WEEK) == 2)
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 3)
                   {     //tuesday
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        System.out.println("TUESDAY = "+_tuesday);
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 4)
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        //System.out.println("TUESDAY = "+_tuesday);
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 5)
                   {     //thursday
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 6)
                   {     //friday
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
         private void fillInTimes(Graphics g, int _spacing, int _spacing2) {
              // need to get the data first, building pre-defined array for test data...
              //****START REAL DATA LOAD****\\
    //          Calendar cal = new GregorianCalendar();
             try {
                 // Load the JDBC-ODBC bridge
                 Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                 // specify the ODBC data source's URL
                 String url = "jdbc:odbc:"+_odbcName;
                 // connect
                 Connection con = DriverManager.getConnection(url,"sa",_currYear);
                 // create and execute a SELECT
                 Statement stmt = con.createStatement();
                 Statement stmt2 = con.createStatement();
                 ResultSet techList = stmt2.executeQuery("USE "+_databaseName+" SELECT Distinct(SV00301.Technician) from SV00301 join SV00115 on SV00301.Technician = SV00115.Technician where SV00115.SV_Inactive<>1");
                 // traverse through results
                 Tech temp;
                 int counter = 0;
                 while(techList.next())
                      if (_myTechList == null)
                           _myTechList = new Tech(techList.getString(1).trim());
                           System.out.println(_myTechList.getName());
                           counter++;
                      else if (!_myTechList.hasNext())
                           _myTechList.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(_myTechList.getNext().getName());
                           counter++;
                      else
                           temp = _myTechList.getNext();
                           while(temp.hasNext())
                                temp = temp.getNext();
                           temp.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(temp.getNext().getName());
                           counter++;
    //             printTechList();
                 String nextMonth, prevMonth;
                 if(cal.get(Calendar.MONTH)==11)
                      nextMonth=_months[0];
                 else
                      nextMonth = _months[cal.get(Calendar.MONTH)+1];
                 if(cal.get(Calendar.MONTH) == 0)
                      prevMonth = _months[11];
                 else
                      prevMonth = _months[cal.get(Calendar.MONTH)-1];
                 ResultSet rs = stmt.executeQuery
                 ("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00301.Task_Date)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00301.Task_Date)="+prevMonth+" or Month(SV00301.Task_Date)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                 System.out.println("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00300.Date_of_Service_Call)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00300.Date_of_Service_Call)="+prevMonth+" or Month(SV00300.Date_of_Service_Call)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                  while (rs.next()) {
                      // get current row values
                       String servicecallid = rs.getString(1).trim(),
                               tech = rs.getString(4).trim(),
                               rawDate = rs.getString(6).trim(),
                               startTime = rs.getString(7).trim(),
                               _length = rs.getString(9).trim(),
                               description = rs.getString(33).trim(),
                               customernumber = rs.getString(35).trim(),
                               custname = rs.getString(45).trim(),
                               location = rs.getString(46).trim(),
                               calltype = rs.getString(54).trim(),
                               notes = rs.getString(268).trim();   
    //                  String formattedDate = month+"/"+day+"/"+year;
    //                  System.out.println(formattedDate);
    //                  String tech = rs.getString(142).trim();
    //                  String rawDate = rs.getString(144);
                      System.out.println(rawDate);
                      String day = rawDate.substring(8,10);
                      String month = rawDate.substring(5,7);
                      String year = rawDate.substring(0,4);
                      formatNumber(day);
                      formatNumber(month);
    //                  startTime = rs.getString(145);
    //                  String _length = rs.getString(147);
                      int hour = Integer.valueOf(startTime.substring(11,13)).intValue();
                      String minute = startTime.substring(14,16);
                      int minutes = Integer.valueOf(minute).intValue();
                      minutes = minutes / 60;
                      double length = (Integer.valueOf(_length).intValue())/100;
                      // print values
                      //System.out.println ("Service_Call_ID = " + Surname);
                      if (hour!=0)
                           sortJob(new Job(servicecallid, custname, new MyDate(month,day,year), hour+minutes,length, description, customernumber, location, calltype, notes), _myTechList, tech);
                  // close statement and connection
                  stmt.close();
                  con.close();
                  catch (java.lang.Exception ex) {
                      ex.printStackTrace();
              //draw techs and blocks of jobs!!!!!
              //***TECHS***\\
             Tech _tempTech = new Tech("DOOKIE");
              int multiplier = 2;
              if (_myTechList.hasNext())
                   g.setColor(Color.BLACK);
                   _tempTech = _myTechList.getNext();
                   g.drawString(_myTechList.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_myTechList.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_myTechList,multiplier, _spacing,_spacing2);
                   multiplier++;
              while(_tempTech.hasNext())
                   g.setColor(Color.BLACK);
                   g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
                   multiplier++;
                   _tempTech = _tempTech.getNext();
              g.setColor(Color.BLACK);
              g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
              System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
              printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
              //***TIME BLOCKS***\\\
         private void printTechList() {
              // TODO Auto-generated method stub
              boolean temp = !_myTechList.hasNext();
              Tech tempTech = _myTechList;
              System.out.println("BEGINNING TECH LIST PRINTOUT!!!!");
              while (tempTech.hasNext() || temp)
                   System.out.println(tempTech.getName());
                   if (temp)
                        temp = !temp;
                   else
                        tempTech = tempTech.getNext();
              System.out.println(tempTech.getName());
              System.out.println("END TECH LIST PRINTOUT!!!");
         private void formatNumber(String month) {
              // TODO Auto-generated method stub
              if (month.equals(new String("01")))
                   month = new String("1");
              else if (month.equals(new String("02")))
                   month = new String("2");
              else if (month.equals(new String("03")))
                   month = new String("3");
              else if (month.equals(new String("04")))
                   month = new String("4");
              else if (month.equals(new String("05")))
                   month = new String("5");
              else if (month.equals(new String("06")))
                   month = new String("6");
              else if (month.equals(new String("07")))
                   month = new String("7");
              else if (month.equals(new String("08")))
                   month = new String("8");
              else if (month.equals(new String("09")))
                   month = new String("9");
         private void printJobs(Graphics g, Tech techList, int multiplier, int _spacing, int _spacing2) {
              Job tempJob = techList.getJobs();
              boolean temp = false;
              if (tempJob != null)
              {     temp = !tempJob.hasNext();
              while (tempJob.hasNext() || temp)
                   g.setColor(Color.RED);
                   String _tempDate = new String(tempJob.getDate().toString());
    //               System.out.println("This job has date of: "+_tempDate);
                   int horizontalMultiplier = 0;
                   if (_tempDate.equals(_monday))
                        horizontalMultiplier = 0;
                   else if (_tempDate.equals(_tuesday))
                        horizontalMultiplier = 1;
                   else if (_tempDate.equals(_wednesday))
                        horizontalMultiplier = 2;
                   else if (_tempDate.equals(_thursday))
                        horizontalMultiplier = 3;
                   else if (_tempDate.equals(_friday))
                        horizontalMultiplier = 4;
                   else
                        horizontalMultiplier = 5;
    //               System.out.println("HorizontalMultiplier = "+horizontalMultiplier);
                   if (horizontalMultiplier !=5)
                        if (tempJob.getJobCallType().equals(new String("TM"))) g.setColor(new Color(0,255,0));
                        else if (tempJob.getJobCallType().equals(new String("SU"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("SPD"))) g.setColor(new Color(44,148,67));
                        else if (tempJob.getJobCallType().equals(new String("QUO"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("MCC"))) g.setColor(new Color(255,0,255));
                        else if (tempJob.getJobCallType().equals(new String("MC"))) g.setColor(new Color(128,0,255));
                        else if (tempJob.getJobCallType().equals(new String("CBS"))) g.setColor(new Color(0,0,255));
                        else if (tempJob.getJobCallType().equals(new String("AS"))) g.setColor(new Color(255,255,255));
                        else g.setColor(Color.red);
                        g.fillRect(/*START X*/(int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1),/*START Y*/_spacing*(multiplier-1)+1,/*LENGTH*/(int)(tempJob.getJobLength()*(_spacing2/9)-1),/*WIDTH*/_spacing-1);
                        System.out.println("g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        g.setColor(Color.BLACK);
                        g.setFont(new Font("Monofonto", Font.PLAIN, 22));
                        if ((int)(tempJob.getJobLength()*(_spacing2/9)-1) >0)
                             g.drawString(formatStringLength(tempJob.getJobName().toUpperCase(), tempJob.getJobLength()), (int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1), (_spacing*(multiplier)+1)-_spacing/2+5);
                        g.setFont(_defaultFont);
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
                   else
                        System.out.println("*g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
         //     g.fillRect((int)(60+(tempJob.getStarTime()-8)*(_spacing2/9)+1),_spacing*(multiplier-1)+1,(int)(tempJob.getJobLength()*(_spacing2/9)-1),_spacing-1);
         private String formatStringLength(String string, double jobLength) {
              // TODO Auto-generated method stub
              if (jobLength*3>string.length())
                   return string;
              return string.substring(0, new Double(jobLength*3).intValue());
         private void sortJob(Job job, Tech techList, String techName) {
              Tech _tempTech2;
              if (techName.equals(techList.getName()))
                   techList.insertJob(job);
                   System.out.println("ADDED " + job.getJobName() +" TO " + techName);
              else
                   _tempTech2 = techList.getNext();
                   while (!_tempTech2.getName().equals(techName) && _tempTech2.hasNext())
                        _tempTech2 = _tempTech2.getNext();
    //                    System.out.println(_tempTech2.getName()+" vs. " + techName);
                   if (_tempTech2.getName().equals(techName))
                        _tempTech2.insertJob(job);
                        System.out.println("ADDED " + job.getJobName() +" TO " + techName);
                   else
                        System.out.println("TECH NAME: "+_tempTech2.getName()+" NOT FOUND :: COULD NOT INSERT JOB");
         private int findCharPosition(String _resolution2, char c) {
              // TODO Auto-generated method stub
              for (int i = 0; i < _resolution2.length(); i++)
                   if (_resolution2.charAt(i) == c)
                        return i;
              return 0;
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
              System.out.println("Mouse clicked at coordinates: "+arg0.getX()+", "+arg0.getY()+"\nAttempting to intelligently find the job number");
               * Find the tech
              int techNum = arg0.getY()/(_yRes / (_techs+1));
              String techName= new String("");
              int counter = 0;
              Tech temp = _myTechList;
              boolean found = true;
              while(temp.hasNext() && found)
                   counter++;
                   if (counter == techNum)
                        techName = temp.getName();
                        found = false;
                   else
                        temp = temp.getNext();
              System.out.println("The "+techNum+"th tech was selected... which means you clicked "+techName);
               * Find the day
              int day = (arg0.getX()-60)/(0 + ((_xRes-60)/5));
              String days[] = {_monday, _tuesday, _wednesday, _thursday, _friday};
              System.out.println("The day you chose was "+days[day]);
               * Find the time
              int blocksIn = ((arg0.getX()-60)/(((_xRes-60)/5)/9))%9;
              System.out.println(blocksIn+" blocks inward!!!!");
               * Find the job
               *           - temp is already initialized to the current tech!!
              System.out.println(temp.getName()+" has "+temp.getNumberOfJobs()+" jobs");
              Job current = temp.getJobs();
              Queue jobQueue = new Queue();
              boolean first = true;
              while(current.hasNext() || first)
                   if(current.getDate().toString().equals(days[day]))
                        jobQueue.enqueue(current);
                        System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
                   else
                        System.out.println("Did not queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
              if(current.getDate().toString().equals(days[day]))
                   jobQueue.enqueue(current);
                   System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              else
                   System.out.println("Did not queue the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              blocksIn+=8;
              while(!jobQueue.isEmpty())
                   try {
                         * Get a job off the queue... now check the times
                        Job dqJob = (Job)jobQueue.dequeue();
                        System.out.println(dqJob.getStarTime()+"<="+blocksIn +" && "+(dqJob.getStarTime()+dqJob.getJobLength()-1)+">="+blocksIn+" :: "+dqJob.getJobName());
                        if (dqJob.getStarTime()<=blocksIn && dqJob.getStarTime()+dqJob.getJobLength()-1>=blocksIn)
                             System.out.println("MONEY!!!! Found job: "+dqJob.getJobName());
                             new JobDisplayer(dqJob, _xRes, _yRes);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void nextDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+7);
                   setDaysFiveStraight();
              this.repaint();
         public void prevDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-7);
                   setDaysFiveStraight();
                   this.repaint();
              this.repaint();
    }Sorry for the huge chunk of code.
    Thanks in advance,
    Jeff

    Sorry for the huge chunk of code.
    Mm, yes, I'm far too lazy to read all that.
    But you should be overriding paintComponent(), not paint().
    http://www.google.co.uk/search?hl=en&q=java+swing+painting&btnG=Google+Search&meta=
    I've not bothered to work out from that pile of magic numbers exactly what you're tring to draw but is it not something that JTable would happily do?

  • Advice for JPanel transparency idea

    Hi!
    I've spent all day reading about the CardLayout and JLayeredPane and am confused as to which route to take.
    Here's what I'm planning to build:
    - One frame containing three panels.
    - Each panel holds an invididual image and and stretches to the extents of the frame, thus the panels sit on top of each other.
    - I would like to be able to change the order of the panels
    - Here's the killer: I'd like to change the transparancy of the top panel (either partially or completely) so that I can peer through to the panel below.
    Any advice would be appreciated. Many thanks...

    To summarise (thanks J_Rooze for advice):
    - Setting the AlphaComposite value before calling super.paintComponent(g2) will change the transparency of the whole panel.
    - Performance will drop in the order of ~40%, but using J_Rooze's suggestion to force the OpenGL rendering pipeline (above) completely remedies this (is there a similar hack for java3D?? :-).
    - Using these panels with JLayeredPane worked completely for my spec (top post).
    - I also tried them in CardLayout, however, whilst I could get the top panel to go transparent the underneath panel would not show through. This might not necessarily be a problem for other specs.
    - Panels should be .setOpaque(false) to eliminate crazy phasing effects.
    Here's my working code for reference:
    import java.awt.*;
    import javax.swing.JPanel;
    public class DisplayPanel extends JPanel{
         private boolean antiAlias;
         private float alpha = 1.0f;
         public DisplayPanel(boolean setAntiAlias) {
              antiAlias = setAntiAlias;
              this.setOpaque(false);
         public void setAlpha(float a) {
              alpha = a;
              if (alpha > 1) alpha = 1.0f;
              if (alpha < 0) alpha = 0.0f;
              repaint();
         public float getAlpha() {
              return alpha;
         protected void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha());
              g2.setComposite(ac);
              super.paintComponent(g2);
              // for speed
              g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
              g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
              if (antiAlias) g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              //draw commands go here
    }Edited by: .eD on May 7, 2008 4:46 AM

  • My glassPane mimic for JPanel is affecting layout. Suggestions?

    I am trying to implement a Glass pane of sorts-- something that can I can lay on top of an arbitrary JPanel momentarily and then remove it again (ideally, it would work regardless of the JPanel's layout, etc.). I'd been kinda modeling it after the code for the frame's glass pane, and I've realized that I'm probably not going about this the right way... which is why I've come to the forums for help. Here's example code that illustrates the problem.
    Instead of my actual glass pane component, I've substituted it for a JLabel that I've called m_onTop. The problem is illustrated just as well using a JLabel.
    import javax.swing.*;
    import java.awt.*;
    public class LayoutIssueExample extends JFrame
        private JLabel m_onTop;
        private JPanel m_coloredPanel;
        private JTextArea m_textArea;
        private JScrollPane m_scrollPane;
        private JButton m_button;
        public LayoutIssueExample()
            m_coloredPanel = new JPanel();
            m_coloredPanel.setBackground( Color.MAGENTA );
            m_coloredPanel.setSize(100,300);
            m_button = new JButton("Dummy button");
            m_onTop = new JLabel("THIS TEXT WILL BE DISPLAYED FOR A MOMENT.");
            m_textArea = new JTextArea();
            m_textArea.setBackground( Color.GRAY );
            m_scrollPane = new JScrollPane(m_textArea);
            m_textArea.setSize(10,80);
            m_scrollPane.setSize( 300,300 );
            setLayout(new BorderLayout());
            add(m_coloredPanel,BorderLayout.WEST);
            add(m_scrollPane,BorderLayout.CENTER);
            add(m_button,BorderLayout.SOUTH);
            setSize(new Dimension(500,500));
            add(m_onTop,0);   // !!!Comment this line to get rid of the label!!!
            setVisible(true);
            try { Thread.sleep(5000); } catch (InterruptedException e) {} //mimic the adding and removing of my special "glass pane" component after a span of time
            remove(m_onTop); // !!!Comment this line to get rid of the label!!
            repaint();
            validate();
        public static void main(String[] args)
            new LayoutIssueExample();
    }        If you run that, you'll see that the magenta bar along the left and the JButton at the bottom will automatically resize, while the gray text area/scrollpane does not.
    If you comment the two lines I've marked (the ones that add and remove the JLabel), recompile, and run, you'll see that all of the components resize swimmingly.
    My first question is: why? I assume it has to do with my having arbitrarily added the JLabel to component position 0... I guess I don't fully understand what all that does. My next question would be: Do you have any ideas or tips for how I could get the JLabel displayed on top of all components, but not affect the layout?
    I would just use the Frame's glassPane functionality and call it good, but I'm implementing this in a Frame that basically just contains a JTabbedPane, and not all items in the tabbed pane should have the special component pane on top.
    Please let me know if you need anything clarified!
    Thanks!

    Maybe something like this:
    import javax.swing.*;
    import java.awt.*;
    public class LayoutIssueExample extends JFrame
        private JLabel m_onTop;
        private JPanel m_coloredPanel;
        private JTextArea m_textArea;
        private JScrollPane m_scrollPane;
        private JButton m_button;
        public LayoutIssueExample()
            m_coloredPanel = new JPanel();
            m_coloredPanel.setBackground( Color.MAGENTA );
            m_button = new JButton("Dummy button");
            m_onTop = new JLabel("THIS TEXT WILL BE DISPLAYED FOR A MOMENT.");
            m_textArea = new JTextArea();
            m_scrollPane = new JScrollPane(m_textArea);
            m_scrollPane.setSize( 300,300 );
              JPanel center = new JPanel();
              center.setLayout( new OverlayLayout( center ) );
              center.add( m_onTop );
              center.add( m_scrollPane );
            add(m_coloredPanel, BorderLayout.WEST);
            add(center, BorderLayout.CENTER);
            add(m_button, BorderLayout.SOUTH);
            setSize(new Dimension(500,500));
            setVisible(true);
        public static void main(String[] args)
            new LayoutIssueExample();
    }

  • How to repaint a JPanel.

    Hi
    I am building a GUI in which i have a fixed panel.........in this panel there is a jpanel....i want to change its contents at run time............like at first there are buttons when someone presses these buttons.....the panel changes to a textbox for instance...........any ideas

    Maybe CardLayout and public void remove(Component comp) will help ...

  • How to retrieve default background color for JPanels or other containers?

    Hi everybody, I've written a small class extending the default JTextArea, intended to provide the functionality of a small, descriptive item in JPanels.
    import java.awt.*;
    import javax.swing.*;
    public class JInfoTextArea extends JTextArea{
         public JInfoTextArea(String text){
              super(text);
              setEditable(false);
              setFont(Font.decode("SansSerif"));
              setFocusable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
    //          setBackground(contentPane.getBackground());
              setAlignmentX(Component.LEFT_ALIGNMENT);
              setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    }As you can see, there formerly used to be a third parameter, namely contentPane, which contained a reference to the parent Container in order to set the TextArea's background color appropriately for transparency.
    Now, is there ANY way to retrieve the background color without either passing a dedicated parameter or doing something like
    setBackground((new JPanel()).getBackground());Any help is greatly appreciated!
    Yours, Stefanie

    To answer your original question the UIManager contains properties of the various components. In case your interested the following program has a fancy GUI display of all the components:
    http://www.discoverteenergy.com/files/ShowUIDefaults.java

  • Maximum size for JPanel in BorderLayout

    I'am using a BorderLayout in my JFrame. I want to place a JPanel in BorderLayout.CENTER. The problem: It should use the maximum possible space.
    For example, if I place a JButton in CENTER, the JButton will grow very big. I want the same behaviour for a JPanel.
    Using setPreferredSize doesn't seem to be a solution because I want the JPanel to resize dynamically, like a JButton does.
    Any ideas? :-)
    Thanks

    The borderlayout is the layout which resizes the components as and when the frame is resized. So i think you should not have a problem like resizing.
    One more thing when u are adding a panel with a borderlayout, do specify where the components are to be added on the panel. i.e. on north, center or south,etc...
    May be this simple example help u out, just copy paste the code and run it.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class BorderMain extends JFrame {
    Container c;
    JPanel pnl;
    BorderLayout bl;
    public BorderMain()
         setPreferredSize(new Dimension(200,200));
         c = getContentPane();
         bl = new BorderLayout();
         pnl = new JPanel();
         pnl.setLayout(bl);
         pnl.setBackground(Color.GRAY);
         c.add(pnl);
         c.validate();
         setVisible(true);
         pack();
         public static void main(String[] args) {
              new BorderMain();
    now when u add anythin to the panel just say
    pnl.add(new JButton("OK"), BorderLayout.NORTH);
    pnl.add(new JButton("OK"), BorderLayout.CENTER);
    pnl.add(new JButton("OK"), BorderLayout.SOUTH);
    this is just an example.
    if u add anything only to north, then to the panel will occupy all the space given.
    Regards
    Poonam.
    and if ur adding another panel on a panel with the borderlayout then u need to set the same layoutfor the inner panel also.

  • Background image for JPanel

    I was to come here and "search" for examples on this but i havnt found any so im jsut going to post it:
    How do i set an image to be the background of a JPanel? setBackground(image); doesnt work... i was toal something about paintComponent() but i tried it with that too and it didnt work... anyhelp would be greatly appreciated

    Ive tried many of the things that search suggested but none of them pertained enough to what i am doing for it to work. Here is my code:package gameFunctions;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class loginScreen extends JFrame implements ActionListener
         JTextField USERNAME, Username, PASSWORD, Password; // yeah i know, bad practice but there is some logic to the names relative to capitalization
         String username, password;
         JButton LOGIN;
         Dimension res = Toolkit.getDefaultToolkit().getScreenSize();
         ImageIcon background = new ImageIcon("C:\\FileTesting\\testImage.jpg");;
         JPanel pane;
    public static void main(String[] args)
              loginScreen frame = new loginScreen();
              frame.setVisible(true);
    public loginScreen()
              Container c = getContentPane();
              setSize(400, 300);
              setLocation((int)res.getWidth()/2-getWidth()/2, (int)res.getHeight()/2-getHeight()/2);
              setResizable(false);
              setLayout(null);
              pane = new JPanel();
              pane.setSize(getWidth(), getHeight());
              pane.setLayout(null);
              c.add(pane);
              USERNAME = new JTextField("Username:");
              USERNAME.setSize(68,25);
              USERNAME.setLocation(getWidth()/2-USERNAME.getWidth()/2-80, getHeight()/2-USERNAME.getHeight()/2-50);
              USERNAME.setEditable(false);
              pane.add(USERNAME);
              PASSWORD = new JTextField("Password:");
              PASSWORD.setSize(68,25);
              PASSWORD.setLocation(USERNAME.getX(), USERNAME.getY()+30);
              PASSWORD.setEditable(false);
              pane.add(PASSWORD);
              Username = new JTextField();
              Username.setSize(150,25);
              Username.setLocation(USERNAME.getX()+USERNAME.getWidth()+5, USERNAME.getY());
              Username.setEditable(true);
              pane.add(Username);
              Password = new JTextField();
              Password.setSize(150,25);
              Password.setLocation(Username.getX(), Username.getY()+30);
              Password.setEditable(false); // because im not working with PW's yet
              pane.add(Password);
              LOGIN = new JButton("LOGIN");
              LOGIN.setSize(80,30);
              LOGIN.setLocation(getWidth()/2-LOGIN.getWidth()/2, PASSWORD.getY()+30);
              pane.add(LOGIN);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent event)
    }i want "pane" to be the image of "background" imageIcon is the only thing that works like this because i dont know how to use straight up "Image". everything works if i set the ImageIcon "background" to be the background of JButton "LOGIN"
    any help would be greatly appreciated

  • Setting size for JPanel to fit JTable

    hi!
    Iam stuck with some grey area in JPanel or JScroolPanel with holds JTable, starting to get gray hair by trying to get rid of that
    public class MiniCalTopPane extends JPanel {
         private static final long serialVersionUID = 8490663735555155912L;
         private TableValues tv;
         private JTable table;
         private JLabel lable;
         public MiniCalTopPane() {
              //create pane with border layout
              super(new BorderLayout());
              //create components
              tv = new TableValues();
              table = new TableW(tv);
              lable = new JLabel("2006");
              lable.setSize(table.getWidth(), 25);
              System.out.println(table.getWidth());
              JScrollPane jsp = new JScrollPane(table);
              jsp.setPreferredSize(new Dimension(200,
                        (table.getHeight())));
              this.add(lable, BorderLayout.BEFORE_FIRST_LINE);
              this.add(jsp, BorderLayout.CENTER);
              setPreferredSize(jsp.getPreferredSize());
              setBackground(Color.GREEN);
              this.setOpaque(true);
    }JTable
    public class TableW extends JTable{
         private static final long serialVersionUID = 2480280947312015884L;
         private static final int ROW_HEIGHT             = 20;
        private static final int COL_WIDTH              = 20;
         public TableW(TableModel dm) {
              super(dm);
            this.changeSelection(0,0,false,false);
            this.setAutoCreateColumnsFromModel(true);
    //      initiate row height
            this.setRowHeight(ROW_HEIGHT);
            this.setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
            this.setRowSelectionAllowed(true);
            this.setColumnSelectionAllowed(true);
            //no dragible colums please!
            this.getTableHeader().setReorderingAllowed(false);
            //dont show grid in table
            this.setShowGrid(false);
            tableHeader.setBackground(Color.WHITE);
              TableColumnModel tcm = this.getColumnModel();       
            //add cutom render to
              for (int i = 0; i < this.getColumnCount(); i++) {
                   TableColumn tc = tcm.getColumn(i);
                   tc.setCellRenderer(new SmallCallRender());
         }I don't se whats is the proble, hope you can point me out :P
    and thanx in advance

    Well, the code you posted isn't executable, so we can't tell whats going on based on the code you posted.
    Here is a simple example that sizes the frame based on the tables size:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=627108
    If you want the frame to be bigger than the table then you can always add the table to the NORTH of the BorderLayout and set the color of the panel to whatever you want. Or, if you keep the table in the center then you need to set the background of the JViewport of the JScrollPane.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Cannot set border for JPanel

    I am not able to select any border for a JPanel, except <default>, in the property window of the visual designer. I can insert a statement by hand to get the border (e.g.: jPanel1.setBorder(new javax.swing.border.EtchedBorder());
    ), but I would like to do it with the visual designer. Is this a missing feature or do I do something wrong?
    Thank you
    Heinz

    You first have to make a Border object in your source code, then it will allow you to select the border.
    example:
    import javax.swing.border.*;
    public class MyFrame1
    // Create a border object in your class
    // Add this next line, and change it to
    // create the type of border you want.
    Border borderPanel1 = BorderFactory.createEtchedBorder();
    after this, you can use the inspector to set the border property (you should see borderPanel1 in the combobox of choices)
    Take Care,
    Rob
    null

  • Adding drop support for JPanel in 1.4

    Hi there.
    I'm sorry for this naive question, but I just had to...
    For implementing drop support in a JPanel can we use the new dnd features of 1.4 or do we have to do it using the "old style"?
    I mean, do we have to implement the DropTargetListener interface and define it as a DropTarget or is there a simpler way?
    Cheers,
    /rp

    Hi there.
    I'm sorry for this naive question, but I just had to...
    For implementing drop support in a JPanel can we use the new dnd features of 1.4 or do we have to do it using the "old style"?
    I mean, do we have to implement the DropTargetListener interface and define it as a DropTarget or is there a simpler way?
    Cheers,
    /rp

Maybe you are looking for

  • Installation of module failed in IPC

    Hi When i m trying upload ipc routine jar files in CRM i am getting th following error Installation of module 'XXXXX' has failed Please help me why i am getting this error... Regards Sowmya

  • Problem generating an IDOC

    Hi I have setup a partner profile with  outbound parameters having message type WMINVE for inventory counts. But when I am creating a inventory document I dont get the idoc created for the inventory document. I hope the question is clear. If not plea

  • Security token testing with soapUI

    Have anyone managed to test the tutorial: [url http://dev2dev.bea.com/pub/a/2006/04/securing-service-bus.html?page=1]Securing Services Using the ALSB with SoapUI ? We had a hard time calling the WS without BEA specific libraries, and ended up making

  • Samples for creating a calibration grid with supplied points. Not a Grid graphic

    Hi again. I have a desire to create a calibration grid for my images captured with IMAQ methods from Measurement Studio. I already take measurements and such based on a calibrated Grid from a .jpg. But now I am interested in allowing my user to creat

  • Working with raw Microphone data...

    so I'm creating an audio recorder and I'm writing the floats from the SampleDataEvent to a byteArray.  Everything works fine locally, but we need to store these files on our server.  I have tried to use Sound.load with the url of the byteArray howeve