JFrame setBackground(Color c)

i'm just curious about Swing so i started reading sun tut Using Swing Components /Using Top-Level Containers and at the same time reviewing a tut i built some time ago called DiveLog (also from sun).
package divelog;
import javax.swing.*;
import java.awt.*;   // Contains all of the classes for creating user
                     // interfaces and for painting graphics and images.
import java.awt.event.*; // Provides interfaces and classes for
                         // dealing with different types of events fired by AWT components
public class DiveLog {
    private JFrame dlframe;
    //private JTabbedPane tabbedPane;
    public DiveLog() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        dlframe = new JFrame ("T?tulo do frame");
        dlframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        dlframe.setSize(400, 200);
        //dlframe.setBackground(Color(49, 106, 197));
        Color c = new Color(49, 106, 197);
        dlframe.setBackground(c);
        //dlframe.setForeground(c);
        //dlframe.pack();
        // Causes this Window to be sized to fit the
        // preferred size and layouts of its subcomponents.
        // If the window and/or its owner are not yet displayable,
        // both are made displayable before calculating the preferred size.
        // The Window will be validated after the preferredSize is calculated.
        dlframe.setVisible(true);
        System.out.print(dlframe.getBackground());
    public static void main(String args[]) {
        DiveLog dl = new DiveLog();
}My Q:
what's the use of
.setBackground(c); if we cant see it?

The content pane is always painted over the JFrame. So you would set the background color of the content pane, not the frame. So, I agree with you, there is no need for that line of code.
The only possible reason I could think of is that when using a slow computer the painting may not be done fast enough and you could get a flicker as the frame is painted and then the content pane.
JFrame frame = new JFrame();
frame.setBackground( Color.RED );
frame.getContentPane().setBackground( Color.GREEN );
frame.setSize(300, 300);
frame.setVisible(true);
Run the above code and you will notice a flicker as the frame is first painted red and then green. So to reduce flicker you could set the frame background to green as well. In most cases when using the default background color of gray you don't notice the flicker so you don't usually worry about it.

Similar Messages

  • JFrame background color

    I have a JFrame and I'm setting the background color in the constructor:
    frame.setBackground(Color.green);
    The frame opens up, and the background color flashes green for an instant, then it goes back to grey. What am I missing? Do I have to set the background color in the paint() method?
    TIA,
    Rich

    I found a post from back in April about setting the background color of the contentPane instead, and that works.
    Thanks anyway!
    Rich

  • SetBackground(Color.WHITE) not working

    I am trying to set background color to white, but it's not working. Can anyone find out the problem?
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.font.FontRenderContext;
    import java.awt.font.LineMetrics;
    import java.awt.font.TextLayout;
    import java.awt.geom.*;
    public class Lab3ex2 {
         * @param args ignored
         public static void main(String[] args) throws IOException {
              // Station[] stations = new Station[100];
              // int n = 0;
              ArrayList<Station> stations = new ArrayList<Station>();
              ArrayList xPos = new ArrayList();
              ArrayList yPos = new ArrayList();
              final String fname = "C://Positions-v2.csv";
              BufferedReader br = new BufferedReader(new FileReader(fname));
              String stationName, item, line;
              line = br.readLine(); // first line skipped
              line = br.readLine(); // 2nd
              while (line != null) {
                   StringTokenizer stoke = new StringTokenizer(line, ",");
                   stationName = stoke.nextToken().trim();
                   item = stoke.nextToken();
                   float x = Float.parseFloat(item);
                   item = stoke.nextToken();
                   float y = Float.parseFloat(item);
                   item = stoke.nextToken();
                   String justification = item;
                   // stations[n] = new Station(stationName, x, y);
                   // n++;
                   stations.add(new Station(stationName, x, y, justification));
                   xPos.add(x);
                   yPos.add(y);
                   line = br.readLine(); // line 3,4,...
              for (Station station : stations) {
                   System.out.println(station);
                   //System.out.printf("%20s %6.1f,%6.1f)%n",station.name, station.x, station.y);
              System.out.print("Press enter...");
              System.in.read();
              JFrame f = new JFrame("Lab3ex2");
              f.add(new MyPanel(stations, xPos, yPos));
              f.setSize(500,400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to avoid needing ^C
    class Station {
         public String name;
         public float x;
         public float y;
         public String justification;
         public Station(String name, float x, float y, String justification) {
              this.name = name;
              this.x = x;
              this.y = y;
              this.justification = justification;
         public String toString() {
              // todo: format x and y
              return name + " (" + x + "," + y + ")";
    class MyPanel extends JPanel {
         private ArrayList<Station> stations;
         private float xMax, yMax;
         private ArrayList xPos;
         private ArrayList yPos;
         public void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              Dimension dim = getSize();
              float xScale, yScale, scale, x, y, radius = 1.0f, diam;
              String justification = null;
              diam = 2.0f*radius;
              Shape s;
              xScale = dim.width/xMax;
              yScale = dim.height/yMax;
              scale = Math.min(xScale, yScale);
              g2.scale(scale, scale);
              g2.setStroke(new BasicStroke(1.0f/scale)); // thin lines
              g2.setFont(new Font("SanSerif", Font.PLAIN, (int)(11.2f/scale))); // always 12 approx
              int total = 0;
              for (Station st : stations) {
                   if(st.name.length()>total)
                        total = st.name.length();
              for (Station st : stations) {
                   x = st.x - radius;
                   y = st.y - radius;
                   justification = st.justification;
                   s = new Ellipse2D.Float(x, y, 2.0f*radius, 2.0f*radius);
                   g2.draw(s);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   if(justification.equals("R"))
                        g2.drawString(st.name, (x-st.name.length())-2, (y+diam));
                   else
                        g2.drawString(st.name, (x+diam+radius), (y+diam));
    GeneralPath theShape = new GeneralPath();
         theShape.moveTo((float)(Float)xPos.get(0), (float)(Float)yPos.get(0));
    for(int i=0; i<15; i++)
         theShape.lineTo((float)(Float)xPos.get(i), (float)(Float)yPos.get(i));
    g2.draw(theShape);
    this.setBackground(Color.WHITE);
         public MyPanel(ArrayList<Station> stations, ArrayList xPos, ArrayList yPos) {
              this.stations = stations;
              this.xPos = xPos;
              this.yPos = yPos;
              xMax = -99999.0f;
              yMax = -99999.0f;
              for (Station st : stations) {
                   if (st.x > xMax) xMax = st.x;
                   if (st.y > yMax) yMax = st.y;
    }

    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.font.FontRenderContext;
    import java.awt.font.LineMetrics;
    import java.awt.font.TextLayout;
    import java.awt.geom.*;
    * Advanced Java Lab 3 ex 2: reading and drawing Met station data
    * @author rallen
    public class Lab3ex2 {
          * @param args
          *            ignored
         public static void main(String[] args) throws IOException {
              // Station[] stations = new Station[100];
              // int n = 0;
              ArrayList<Station> stations = new ArrayList<Station>();
              ArrayList xPos = new ArrayList();
              ArrayList yPos = new ArrayList();
              final String fname = "C://Positions-v2.csv";
              BufferedReader br = new BufferedReader(new FileReader(fname));
              String stationName, item, line;
              line = br.readLine(); // first line skipped
              line = br.readLine(); // 2nd
              while (line != null) {
                   StringTokenizer stoke = new StringTokenizer(line, ",");
                   stationName = stoke.nextToken().trim();
                   item = stoke.nextToken();
                   float x = Float.parseFloat(item);
                   item = stoke.nextToken();
                   float y = Float.parseFloat(item);
                   item = stoke.nextToken();
                   String justification = item;
                   // stations[n] = new Station(stationName, x, y);
                   // n++;
                   stations.add(new Station(stationName, x, y, justification));
                   xPos.add(x);
                   yPos.add(y);
                   line = br.readLine(); // line 3,4,...
              for (Station station : stations) {
                   System.out.println(station);
                   // System.out.printf("%20s %6.1f,%6.1f)%n",station.name, station.x,
                   // station.y);
              System.out.print("Press enter...");
              System.in.read();
              JFrame f = new JFrame("Lab3ex2");
              f.add(new MyPanel(stations, xPos, yPos));
              f.setSize(500, 400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to avoid needing ^C
    class Station {
         public String name;
         public float x;
         public float y;
         public String justification;
         public Station(String name, float x, float y, String justification) {
              this.name = name;
              this.x = x;
              this.y = y;
              this.justification = justification;
         public String toString() {
              // todo: format x and y
              return name + " (" + x + "," + y + ")";
    class MyPanel extends JPanel {
         private ArrayList<Station> stations;
         private float xMax, yMax;
         private ArrayList xPos;
         private ArrayList yPos;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              this.setLayout(new FlowLayout());
              Graphics2D g2 = (Graphics2D) g;
              Dimension dim = getSize();
              float xScale, yScale, scale, x, y, radius = 1.0f, diam;
              String justification = null;
              diam = 2.0f * radius;
              Shape s;
              xScale = dim.width / xMax;
              yScale = dim.height / yMax;
              scale = Math.min(xScale, yScale);
              g2.scale(scale, scale);
              g2.setStroke(new BasicStroke(1.0f / scale)); // thin lines
              g2.setFont(new Font("SanSerif", Font.PLAIN, (int) (11.2f / scale))); // always
                                                                                                        // 12
                                                                                                        // approx
              int total = 0;
              for (Station st : stations) {
                   if (st.name.length() > total)
                        total = st.name.length();
              for (Station st : stations) {
                   x = st.x - radius;
                   y = st.y - radius;
                   justification = st.justification;
                   s = new Ellipse2D.Float(x, y, 2.0f * radius, 2.0f * radius);
                   g2.draw(s);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   if (justification.equals("R")) {
                        g2.drawString(st.name, (x - st.name.length()) - 2, (y + diam));
                   } else {
                        g2.drawString(st.name, (x + diam + radius), (y + diam));
              GeneralPath theShape = new GeneralPath();
              theShape.moveTo((float) (Float) xPos.get(0), (float) (Float) yPos
                        .get(0));
              for (int i = 0; i < 15; i++) {
                   theShape.lineTo((float) (Float) xPos.get(i), (float) (Float) yPos
                             .get(i));
              g2.draw(theShape);
              setOpaque(true);
         public MyPanel(ArrayList<Station> stations, ArrayList xPos, ArrayList yPos) {
              this.stations = stations;
              this.xPos = xPos;
              this.yPos = yPos;
              xMax = -99999.0f;
              yMax = -99999.0f;
              for (Station st : stations) {
                   if (st.x > xMax)
                        xMax = st.x;
                   if (st.y > yMax)
                        yMax = st.y;
              this.setBackground(Color.WHITE);
              this.setVisible(true);
    }Edited by: swapnil_raverkar on Sep 21, 2008 5:10 AM

  • JComponent.setbackground(Color.BLACK) is NOT working

    I am creating Space Invaders game and have GamePanel as my JComponent, named panel. The background is not changing for sum reason though???
    import java.awt.*;
    import javax.swing.*;
    public class SpaceInvaders{
         //variables
         public static final int WIDTH = 800;
         public static final int HEIGHT = 800;
         GamePanel panel;
         public SpaceInvaders()
              //create frame
              JFrame demoFrame = new JFrame("Space Invaders");
              demoFrame.setBounds(0,0,WIDTH,HEIGHT);
              demoFrame.setVisible(true);
              demoFrame.setResizable(false);
              demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              demoFrame.setBackground(Color.BLACK);
              //create panel
              GamePanel panel = new GamePanel(this);
              panel.setBackground(Color.BLACK);
              demoFrame.add(panel);
              //add buttons
              JButton startButton = new JButton("Start");
              startButton.setEnabled(true);
              JButton stopButton = new JButton("Stop");
              stopButton.setEnabled(true);
    ..... import java.awt.*;
    import javax.swing.*;
    import java.awt.Image;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferStrategy;
    import javax.swing.*;
    import java.awt.event.*;
    public class GamePanel extends JComponent implements KeyListener, ActionListener
         SpaceInvaders game;
         static Player player1;
         Bullets bullet;
         private BufferStrategy strategy;
         static int alienNum = 36;
         static int alienRow = 6;
         static int alienCol = 6;
         static Aliens[][] aliens;
         static Bullets[] bullets;
         private Timer timer;
         int bulletNum=0;
         public GamePanel(SpaceInvaders game)
              this.game = game;
              player1 = new Player(this);
              player1.start();
              aliens = new Aliens[alienRow][alienCol];
              for(int i=0; i<alienRow; i++)
                   for(int j=0; j<alienCol; j++){
                        aliens[i][j] = new Aliens(this);
                        aliens[i][j].setX(i*50);
                        aliens[i][j].setY(j*50);
              bullets = new Bullets[5];
                   bullets[0]=new Bullets(this);
              timer=new Timer(500, this);
              //timer.setDelay(500);
              timer.start();
              this.setFocusable(true);
            this.addKeyListener(this);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Image pic1 = player1.getImage();
    ...........

    I changed the GamePanel class to extend JPanel instead of extend JComponent and it works now. Didnt realise JComponent had no paint functions.. Thanks for your help.
    import java.awt.image.BufferStrategy;
    import javax.swing.*;
    import java.awt.event.*;
    public class GamePanel extends JPanel implements KeyListener, ActionListener
         SpaceInvaders game;
         static Player player1;
         Bullets bullet;
         private BufferStrategy strategy;

  • Please help - JFrame, menu, another JFrame, setBackground

    I am trying to make a simple program that draws a JFrame with a menu. The menu has one item, which when selected draws another JFrame. That JFrame has a button, which when pressed changes the background color. Many hours have gone into this, despite the fact that I made a similar program a few weeks ago.
    The compiler complains about the method getContentPane, when I remove that, it runs and draws the first window, but the menu item does not make the second window. Also, the setDefaultCloseOperation confuses the compiler as well.
    Please help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MenuAction2
    public static void main(String[] args) 
         MainWindow window = new MainWindow("Menu action example");
      //window.setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
         window.setVisible(true);      
    class MainWindow extends JFrame
         MainWindow(String title)
         super(title);
         getContentPane.setLayout(new BorderLayout());
         Toolkit theKit = getToolkit();          
         Dimension wndSize = theKit.getScreenSize();  
         setBounds(0, 0,wndSize.width, wndSize.height);
         setJMenuBar(menuBar);
         fileMenu = new JMenu("File");
         connectItem = new JMenuItem();
         connectItem = fileMenu.add("Connect...");
         connectItem.addActionListener(menuHandler = new Handler());
         menuBar.add(fileMenu);
         getContentPane.add(toolBar, BorderLayout.NORTH);  
    class Handler implements ActionListener
         public void actionPerformed(ActionEvent e)
          win = new ConnectWindow("Connect to Database");
          getContentPane().add(win, BorderLayout.NORTH);
          setVisible(true);
      private JMenu fileMenu;
      private JMenuItem connectItem;
      private JMenuBar menuBar = new JMenuBar(); 
      private JToolBar toolBar = new JToolBar();
      private Handler menuHandler;
      private ConnectWindow win;
    class ConnectWindow extends JFrame
         ConnectWindow(String title)
              super(title);
              setSize(200,200);
              setLayout(new BorderLayout());
              JButton connectB = new JButton("Connect");
              connectB.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        setBackground(Color.red);
              add(connectB,BorderLayout.SOUTH);
              setVisible(true);
    }

    getContentPane is a method so you should use it that way:
    getContentPane().setLayout(new BorderLayout());
    getContentPane.add(new Button("Ok"));

  • JLabel.setBackground(Color.red) not working

    Hi, I am using the (JLabel) lblPrmf.setBackground(Color.RED), but the label is not colored. Here is my program:
    import java.util.*;
    import javax.swing.*; //JFrame and JPanel etc...
    import java.awt.*; //BorderLayout and Container etc....
    import java.awt.Color;
    import java.awt.event.*; //ActionListener og WindowAdapter
    public class AllVac extends JFrame
    //Define JLabel
    private JLabel lblDays;
    private JLabel lblAbs;
    private JLabel lblPrmf;
    //Define JButton
    private JButton month;
    private JButton back;
    private JButton forward;
    //Define JPanel
    private JPanel south;
    private JPanel north;
    public AllVac()
    // JFrame jf = new JFrame("Vacation for the Stavanger Team ");
    Container c = getContentPane();
    // c.setTitle("Vacation for the Stavanger Team ");
    c.setLayout(new BorderLayout());
    c.add(new ShowNorth(), BorderLayout.NORTH);
    c.add(new ShowSouth(), BorderLayout.SOUTH);
    pack();
    setVisible(true);
    addWindowListener(new Close());
    public static void main(String args[])
    AllVac a = new AllVac();
    public class ShowNorth extends JPanel
    public ShowNorth()
         north = new JPanel(new GridLayout(1, 3));
         month = new JButton("August 2006");
         back = new JButton("<<");
         forward = new JButton(">>");
         north.add(back);
         north.add(month);
         north.add(forward);
         add(north);
    public class ShowSouth extends JPanel
    public ShowSouth()
         int days = 31;
         south = new JPanel(new GridLayout(16, days+1));
    //Arrange the days
    for ( int i = 1; i<(days+1); i++)
    lblDays = new JLabel(" " + Integer.toString(i));
    lblDays.setBorder(BorderFactory.createLineBorder(Color.red));
    south.add(lblDays);
    add(south, BorderLayout.LINE_START);
    //Fill in the names and vacation days
    for ( int i = 1; i<(days+1); i++)
    lblAbs = new JLabel(" ");
    south.add(lblAbs);
    add(south, BorderLayout.LINE_START);
    for (int j = 0; j<14; j++)
    for ( int i = 1; i<days+1; i++)
    String v = "v";
    lblPrmf = new JLabel(" " + v + " ");
    lblPrmf.setBackground(Color.RED);
    lblPrmf.setBorder(BorderFactory.createLineBorder(Color.blue));
    lblPrmf.setBackground(Color.RED);
    lblPrmf.repaint();
    south.add(lblPrmf);
    add(south);
    public class Close extends WindowAdapter
    public void windowClosing(WindowEvent c)
    System.exit(0);
    }

    You are building a GUI with Swing components. Why would you ask the question in the general programming forum???? People there may never have built a GUI or heard of Swing.
    Concepts of creating GUI components adding then to a GUI, dealing with models, listening to events and responding to the events are all techniques related to GUI programming. Even Swing programming is different from AWT programming in some cases.
    So when you topic title says. "I have a problem, with a Swing (JLabel) component", or "How do I change a JTable in a JScrollPane" where do you think the question should be asked. Maybe its just me but I would think the Swing forum is where you would find the experts, or at least people who think they know something about Swing.
    Your previous posting on "display a button on a background image" was not very clear. You use an Applet and Panel which are an AWT components. But then you are also using JFrame and JButton which are Swing components. Since you posted the question in the general programming forum, I had no idea whether you where attempting to write an AWT or a Swing application so I ignored the posting.

  • How we can change JFrame Border Color Not Background.

    How we change jframe border color not background
    if any body know about that then plz tell me
    at this [email protected]
    i m thanksfull to ..... .

    hi Shafr
    beleive it or not, i got it using trial and error. i keep
    trying words in the function setStyle until the color changed. i
    dont know why it is not documented.
    var periodBarColor:SolidColor = new
    SolidColor(taskSchedColorChooser.selectedColor, 1);
    periodBar.setStyle("fill",periodBarColor);
    //where taskSchedColorChooser is colorPicker component. you
    can replace it by any color you want

  • SetBackground(Color c)

    Hello All,
    What do you know about setBackground(Color c) execution ?
    I mean does this function work as PostMessage() or as SendMessage ? Can I be sure that after the funcion has returned this "paint message" has already been processed by the system ?

    Wrong. I suggest you take a look at the code in JComponent:
    public void setBackground(Color bg) {
       Color oldBg = getBackground();
       super.setBackground(bg);
       if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
          // background already bound in AWT1.2
          repaint();
    }But in general if you program in such a way that it matters when exactly
    your component gets repainted, better re-think your approach:
    You should call setBackground() only from AWTs event thread and you
    better don't make long-running calculations in this thread.
    However at the latest your component will get repainted when this
    thread is idle.
    Also, take a look at the JavaDoc of repaint():
    "Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched."
    So even repaint() does not paint your component immediatly.
    The gist of it: JavaDoc and the JDK sources are your friend.

  • SetBackground color not working

    Hello,
    While viewing my applet from within a HTML file, my background color is still grey, except the buttons.
    The color is fine while viewing with appletviewer so I'm a bit confussed.
    Any ideas as to why would be appreciated.
    Thanks in advance.
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.awt.event.*;
    public class MyCalendar extends javax.swing.JApplet  {
           public void init()
             Container content = getContentPane();
             JPanel calendars = new JPanel(new GridLayout(0,1));
             JScrollPane jsp = new JScrollPane(calendars);
             content.add(jsp, BorderLayout.CENTER);
             GregorianCalendar gc = new GregorianCalendar();
              //gc.set(GregorianCalendar.DAY_OF_YEAR,1);c
              gc.set(GregorianCalendar.DAY_OF_MONTH,1);     
                for (int i=0; i<12; i++)
               calendars.add(new CalendarPanel(gc));
               gc.add(GregorianCalendar.MONTH, 1);
              //setSize(300, 300);
                  //setVisible(true);
    class CalendarPanel extends JPanel implements ActionListener
           private JLabel jl;
           private int testYear;
           private final static String[] DOW = {"S","M","T","W","T","F","S"};
           SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
           GridBagConstraints gbc = new GridBagConstraints(0,0,7,1,1.0,1.0,GridBagConstraints.CENTER,
              GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0);
           public CalendarPanel(GregorianCalendar cal)
              setLayout(new GridBagLayout());
              setBorder(BorderFactory.createEtchedBorder());
              setBackground(Color.white);
              //get the month name
              String testMonth=sdf.format(cal.getTime());
               testYear = cal.get(GregorianCalendar.YEAR);
              int nextYear = cal.get(GregorianCalendar.YEAR)+1;
              JLabel lblYear = new JLabel(""+testYear);
              JLabel jl = new JLabel(testMonth, JLabel.CENTER);
              add(jl,gbc);
              gbc.gridwidth=1;
                 gbc.gridy=1;
              for (int i=0; i<7; i++)
                    gbc.gridx=i;
                    add(new JLabel(DOW, JLabel.CENTER),gbc);
              gbc.gridx = cal.get(GregorianCalendar.DAY_OF_WEEK)-1;
         gbc.gridy++;
              int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
              for (int i=1; i<=daysInMonth; i++)
              JButton jb = new JButton(""+i);
              jb.setBackground(Color.white);
              jb.setForeground(Color.blue);
              jb.addActionListener(this);
              //jb.setBorder(BorderFactory.createRaisedBevelBorder());
              add(jb,gbc);
              if (++gbc.gridx==7)
                   gbc.gridx=0;
                   gbc.gridy++;
         public void actionPerformed(ActionEvent event)
              String command = event.getActionCommand();
              if(event.getSource() instanceof JButton)
                   System.out.println("Button:"+command);
                   String text = jl.getText();     
                   System.out.println("Month:"+text);
                   System.out.println("Year:"+testYear);

    Ok, the last one worked but now one of my labels won't change color even after jl.setOpaque(true).
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.awt.event.*;
    public class MyCalendar extends javax.swing.JApplet  {
           public void init()
             Container content = getContentPane();
             JPanel calendars = new JPanel(new GridLayout(0,1));
             JScrollPane jsp = new JScrollPane(calendars);
             content.add(jsp, BorderLayout.CENTER);
             GregorianCalendar gc = new GregorianCalendar();
              //gc.set(GregorianCalendar.DAY_OF_YEAR,1);c
              gc.set(GregorianCalendar.DAY_OF_MONTH,1);     
                for (int i=0; i<12; i++)
               calendars.setOpaque(true); //this worked
               calendars.add(new CalendarPanel(gc));
               gc.add(GregorianCalendar.MONTH, 1);
    class CalendarPanel extends JPanel implements ActionListener
           private JLabel jl;
           private int testYear;
           private final static String[] DOW = {"S","M","T","W","T","F","S"};
           SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
           GridBagConstraints gbc = new GridBagConstraints(0,0,7,1,1.0,1.0,GridBagConstraints.CENTER,
              GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0);
           public CalendarPanel(GregorianCalendar cal)
              setLayout(new GridBagLayout());
              setBorder(BorderFactory.createEtchedBorder());
              setBackground(Color.white);
              //get the month name
              String testMonth=sdf.format(cal.getTime());
               testYear = cal.get(GregorianCalendar.YEAR);
              int nextYear = cal.get(GregorianCalendar.YEAR)+1;
              JLabel lblYear = new JLabel(""+testYear);
              JLabel jl = new JLabel(testMonth, JLabel.CENTER);
              jl.setOpaque(true); //only works in appletviewer NOT html
              jl.setBackground(Color.red);
              add(jl,gbc);
              gbc.gridwidth=1;
                 gbc.gridy=1;
              for (int i=0; i<7; i++)
                    gbc.gridx=i;
                    add(new JLabel(DOW, JLabel.CENTER),gbc);
              gbc.gridx = cal.get(GregorianCalendar.DAY_OF_WEEK)-1;
         gbc.gridy++;
              int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
              for (int i=1; i<=daysInMonth; i++)
              JButton jb = new JButton(""+i);
              jb.setBackground(Color.white);
              jb.setForeground(Color.blue);
              jb.addActionListener(this);
              jb.setBorder(BorderFactory.createRaisedBevelBorder());
              add(jb,gbc);
              if (++gbc.gridx==7)
                   gbc.gridx=0;
                   gbc.gridy++;
         public void actionPerformed(ActionEvent event)
              String command = event.getActionCommand();
              if(event.getSource() instanceof JButton)
                   System.out.println("Button:"+command);
                   String text = jl.getText();     
                   System.out.println("Month:"+text);
                   System.out.println("Year:"+testYear);
    [\code]

  • JScrollPane.setBackground(Color.white);

    Hi @all,
    I want to make the BackgroundColor of my JScrollPane white. Does anybody know, why this little piece of code doesn?t do anything?
    I can compile it, but then the background is still grey.
    JLabel pic = new JLabel(new ImageIcon("dile_logo.jpg"));
    JScrollPane sp = new JScrollPane(pic, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    sp.setBackground(Color.white);          
    add(sp);
    thank you
    Juergen

    I tried:
    sp.setOpaque(true);
    and also:
    pic.setBackground(Color.white);
    but both does not change anything.
    @vaskol
    I have a picture that is smaller than the window and also as the scrollpane. So I do not have ScrollBars.
    The background of the picture is white and the rest of the window is grey and I want to change that to white.
    I do not understand what you mean with "that square in the corner" and also this part of your explication.
    Sorry
    Juergen

  • JButton.setBackground(Color color) not working

    With JDK 1.4.2, my JButtons below have a blue background. When I compile with 1.5, they are gray. I tried using setOpaque(true) on one of them below. It didn't work. Any ideas?
    class MainMenu extends JFrame
        public MainMenu() throws Exception
            super("");// no title on main menu
            JPanel pane = new JPanel(null, true);
            pane.setBackground(new Color(4194496));
            Icon icon = new ImageIcon(BizThriveMenu.getResourceDir()+"\\BizThriveSmall.gif");
            JLabel lImage = new JLabel(icon);
            JButton bEditCustomers = new JButton("<html><FONT COLOR=WHITE>Customers</FONT></html>");
            bEditCustomers.setOpaque(true);
            bEditCustomers.setBackground(new Color(4194496));
            JButton bAccounting = new JButton("<html><FONT COLOR=WHITE>Accounting</FONT></html>");
            bAccounting.setBackground(new Color(4194496));
            JButton bEditReminders = new JButton("<html><FONT COLOR=WHITE>Reminders</FONT></html>");
            bEditReminders.setBackground(new Color(4194496));
            JButton bPublish = new JButton("<html><FONT COLOR=WHITE>Publish</FONT></html>");
            bPublish.setBackground(new Color(4194496));
            JButton bExit = new JButton("<html><FONT COLOR=WHITE>Exit</FONT></html>");
            bExit.setBackground(new Color(4194496));
            bEditCustomers.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        try {
                            new TableListFrame(MainMenu.this, "customers");
                        catch (Exception e) {
                            e.printStackTrace();
            bAccounting.addActionListener(
                    new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            try {
                                new AccountCategoryListFrame(MainMenu.this, "accountCategories");
                            catch (Exception e) {
                                e.printStackTrace();
            bEditReminders.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        try {
                            new CurrentRemindersFrame(MainMenu.this);
                        catch (Exception e) {
                            e.printStackTrace();
            bPublish.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        try {
                            new Designer(MainMenu.this);
                        catch (Exception e) {
                            e.printStackTrace();
            bExit.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent actionEvent) {
                        System.exit(0);
            Font buttonFont = bEditCustomers.getFont();
            buttonFont = new Font("Times New Roman", Font.ITALIC+Font.BOLD, 24);
            bEditCustomers.setFont(buttonFont);
            bAccounting.setFont(buttonFont);
            bEditReminders.setFont(buttonFont);
            bPublish.setFont(buttonFont);
            bExit.setFont(buttonFont);
            pane.add(lImage);
            pane.add(bEditCustomers);
            pane.add(bAccounting);
            pane.add(bEditReminders);
            pane.add(bPublish);
            pane.add(bExit);
            int appWidth = 500;
            int appHeight = 700;
            this.setSize(new Dimension(appWidth,appHeight));
            this.setResizable(false);
            this.getContentPane().add(pane);
            Insets insets = pane.getInsets();
            lImage.setBounds(((appWidth-4-icon.getIconWidth())/2)+insets.left, 35+insets.top, icon.getIconWidth(), icon.getIconHeight());
            bEditCustomers.setBounds(((appWidth-4-235)/2)+insets.left,  200 + insets.top, 235, 40);
            bAccounting.setBounds(((appWidth-4-235)/2)+insets.left,  250 + insets.top, 235, 40);
            bEditReminders.setBounds(((appWidth-4-235)/2)+insets.left,  300 + insets.top, 235, 40);
            bPublish.setBounds(((appWidth-4-235)/2)+insets.left,  350 + insets.top, 235, 40);
            bExit.setBounds(((appWidth-4-235)/2)+insets.left,  400 + insets.top, 235, 40);
            //center application window on desktop
            Dimension screenSize = null;;
            screenSize = getToolkit().getScreenSize();
            this.setBounds((screenSize.width - appWidth)/2,
                (screenSize.height - appHeight)/2, appWidth, appHeight);
            // make the frame visible
            this.setVisible(true);
        }

    As a newbie to the forum you obviously didn't understand how to post a simple direct question, with only the relevant code to demonstrate the problem, which is why I provided you with all the extra information to help you get better answers in the future.
    Did you bother to read the link of creating an SSCCE?
    Your question is about setting the background color of a button. 99% of the code you posted is not related to that issue. Keep the code simple so we don't waste time reading through unnecessary code. That way we can determine whether the problem is with your code or the environment as I already mentioned.
    1) Though the information about setting the text color is helpful, the
    background color of the button is the subject of the posting. Please
    limit your replies to the subject of the posting.If the code posted was only related to the background color then we wouldn't have this issue now would we? When I see something strange or wrong I make a comment whether it is directly related to the question or not. It has been my experience that most people appreciate the bonus advice, so I will not change my behaviour for you. If you don't like the advice, then just ignore it.
    2) Regarding, "I don't use 1.5 so I can't really help you, but neither can
    anybody else...", please read Michael_Dunn's post, who remarkably
    was able to provide help.My comment was related to the code you provided. Nobody could use the code to compile and execute to see if it ran on their machine. So, Michael, had to waste time creating his own simple test program to see if it worked, which it did.
    My point was if you provided the same simple demo program that Michael did, then all he (or anybody else) would have had to do would be to copy, compile and test the program. You should be spending the time creating the simple test program not each of us individually. Think of how much time is wasted if everybody who wanted to help you had to create their own program? Thats why I included the link on creating an SSCCE, so the next time we don't need to waste time.
    3) ..... Otherwise, it's alright not to reply to a subject. Nobody will think less of you.Of course I don't have to replay to every question (and I don't), but if you don't learn to post a question properly you will make the same mistake again and again. That was the context of my answer. It was designed to help you ask a better question the next time.
    4) Your comment, "And don't forget to use the Code Formatting Tags > so the code retains its original formatting." That was a standard message I use for many newbies to the forum. I'm amazed at the number of people who think we are mind readers and can guess exactly what is causing the problem without posting any code. So I got tired of typing in a different message every time and I now just cut and paste. Yes I could have edited the last line out, but you would be amazed at how many people format the code the first time but then forget to do it when prompted for more detail. So I just keep it in all messages.
    Please keep your comments related to the problem. I think I've learned a think or two over the years on how to ask and answer a question.

  • Usage of setPreferredSize(Dimension) and setbackground(Color)

    Hi,
    I'm using BorderLayout panel, this panel in-turn holds FlowPanels which has all the components. Now, I'm trying to set the background color and the preferred size to the Borderlayout panel, but its not reflecting. My panel is taking the default gray color and some default font.
    I want this panel use the color that the frame has and also want to set the Dimension, to which Panel has to resize.
    Please help me out, how to do this ?
    Code snippets will be a gr8 help.
    Thanks in advance,
    Chandrasekhar.

    I'm using BorderLayout panel, this panel in-turn holds FlowPanels which has all the components. Now, I'm trying to set the background color and the preferred size to the Borderlayout panel, but its not reflecting. My panel is taking the default gray color and some default font.
    I doubt those grey bits you see are the BorderLayout panel: they're the FlowPanels or even the components in them. Bear in mind that most components are opaque by default - so if you create a JPanel with a BorderLayout, add a JPanel in its center and then set the background of the original, it won't matter because what you're seeing is the child panel.
    As for the preferred size, how that gets used depends on what layout that component is placed in. So what's it in?

  • Jpanel setBackground color thread safe?

    is this method thread safe?
    meaning do i have to use Invoke on the dispatch thread everytime or
    it doesn't really matter

    is this method thread safe?
    meaning do i have to use Invoke on the dispatch
    thread everytime or
    it doesn't really matterThat's not what thread safe means, but yes, you should be able to call it from any thread.

  • Window painting problem

    I have a JFrame with lots and lots of JLabels on it...I want to paint the JFrame background and make the JLabels' background transparent...I use the following in my JFrame's paint method:
    public static class statWindow extends JFrame {
    statWindow(String caption) {
    super(caption);
    public void paint(Graphics g) {
    super.paint(g);
    window.setBackground(Color.white);
    the window flickers white for a second, but then returns to that dull gray...two of the JLabels whose background i explicitly set to the window's bgcolor turn white; why does that matter? am i tying a reference to the window's background? and why won't the window stay white?

    1. Setting a JLabel to be transparent means calling setOpaque(false).
    So you should only see the text, not a rectangle of white around it.
    2. Look at the paint() routine.
    You're choosing the colour after the paint has been done.
    You should just need to call JFrame.setBackground(Color.white) in your the JFrame constructor.
    regards,
    Owen

  • Background Color change JFrame

    I have to change the background color when the result is either too high or low. Program runs great except the background color doesn't change. And before you complain about my code, I hit the "CODE" button before and after my code in here and it does nothing. The videos wouldn't play. So I don't know how to add code correctly.
    import java.awt.*;
    import java.util.Random;
    import javax.swing.*;
    public class NumberGuess extends JFrame {
    Random rand = new Random ( ) ;
    int randomNumber = 1 + rand.nextInt(1000);
    int count = 0;
    private JFrame panel = new JFrame();
    private JFrame panelButtons = new JFrame();
    private JFrame panelBottom = new JFrame();
    private void compareResult() {
    int userInput = Integer.parseInt(tempTextField.getText().trim());
    if ( userInput > randomNumber )
    resultLabel.setText( "Too High. Try a lower number." );
    setBackgroundColor(Color.blue);
    private void setBackgroundColor(Color color)
    panel.setBackground(color);
    panelBottom.setBackground(color);
    panelButtons.setBackground(color);

    Goofy_1969 wrote:
    And before you complain about my code, I hit the "CODE" button before and after my code in here and it does nothing.Well, you did manage to create 2 empty code blocks though.
    I know this is New To Java, so I need to be nicer and most of you people don't probably have the intrinsic knowledge of "start tag" and "end tag".
    But still. All you need is to put your code between tags and everything will work great.
    AND HEY, There's the preview button too! So you can actually try and try and try until it works. It's just that programming is a difficult hobby and if you can't work the code tags, you really need to rethink whether you're ready for something that's actually complicated.
    (Also if you're not using the code tags, your code will totally get screwed up and people can't help you even if they wanted to.)
    As for your code, try using SwingUtilities.invokeLater(). That's the only way you can modify the GUI when you're not running in the event thread.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • HSlider used for time/ranges

    I have an app that needs to program open/close hours. So far I have a HSlider that starts at 0 and ends at 86400 (seconds in a day). I can easily convert the second value to a standard date time value, so all works great as long as I only want standa

  • Error in deploying Webdynpro DC.

    Hi All I have created a Webdynpro DC which consumes Webservice using adaptive webservices model,also it uses KM apis for km document updation.I have created a separate library DC for KM jars. The issue is when i am deploying WDJ DC then i get an Depl

  • Select PreparedStatement execution slowdown overtime - Oracle 10.2.0.1

    This is a very confusing issue. We have a batch type application built on Hibernate using Oracle JDBC 10.2.0.1 drivers. Currently using a Spring configured connection pool (don't think this is the issue). Basically, the first step of the process invo

  • Extended Classic Scenario Pricing issue, can I over come by using SRM-MDM?.

    Hi SRM GURU'S, I am using  ECC 6.0, SRM 5.5, SUS, LAC, cFolders and SRM-MDM with Extended Classic Scenario. My Question is : In case of Extended classic scenario, there is issue with Pricing and conditions. Is there any possibility to overcome this i

  • JAX-WS contract first solution help needed

    Hi, I am trying to create a bunch of web services using jax-ws which I will deploy on Jboss. I would like to create xml schemas and wsdl files before I create my solution because I want a clearer contract betweent client and server that is not define