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?

Similar Messages

  • 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

  • Setting fonts and Background color

    Hi,
    Is there anyway to set the font and background color on a jLabel? Thanks for your help!

    ...emmmm lets see... for the font and the background...
    maybe setFont and maybe setBackground!
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html

  • 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.

  • Load dimensions and members in Planning application via outline load

    it is a classic planning application, after I load dimensions and members into classic Planning application, I can't see new members I added in csv file.
    How could I confirm whether it was successfully loaded.
    This is the log. Please refer to it.
    Successfully logged into "予算応用" application, Release 11.121, Adapter Interface Version 5, Workforce supported and enabled, CapEx supported and enabled, CSS Version 3
    "Account" dimension properties and information:
    Account, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Account Type, Time Balance, Skip Value, Exchange Rate Type, Variance Reporting, Source Plan Type, Plan Type (PL), Aggregation (PL), Plan Type (BS), Aggregation (BS), Plan Type (Plan3), Aggregation (Plan3), Plan Type (Wrkforce), Aggregation (Wrkforce), Plan Type (Capex), Aggregation (Capex)
    UDA's bound to "Account" dimension: HSP_NOLINK
    "Period" dimension properties and information:
    Period, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Type, Start Period, End Period, Aggregation (PL), Aggregation (BS), Aggregation (Plan3), Aggregation (Wrkforce), Aggregation (Capex)
    No UDA's defined on "Period"
    "Year" dimension properties and information:
    Year, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation
    No UDA's defined on "Year"
    "Scenario" dimension properties and information:
    Scenario, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Start Year, Start Period, End Year, End Period, Exchange Table, Include BegBal, Process Management Enabled, Aggregation (PL), Aggregation (BS), Aggregation (Plan3), Aggregation (Wrkforce), Aggregation (Capex)
    UDA's bound to "Scenario" dimension: ACTUAL
    "Version" dimension properties and information:
    Version, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Version Type, Process Management Enabled, Aggregation (PL), Aggregation (BS), Aggregation (Plan3), Aggregation (Wrkforce), Aggregation (Capex)
    No UDA's defined on "Version"
    "Currency" dimension properties and information:
    Currency, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Symbol, Scale, Triangulation Currency, Reporting Currency, Thousands Separator, Decimal Separator, Negative Style, Negative Color
    No UDA's defined on "Currency"
    "Entity" dimension properties and information:
    Entity, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Base Currency, Plan Type (PL), Aggregation (PL), Plan Type (BS), Aggregation (BS), Plan Type (Plan3), Aggregation (Plan3), Plan Type (Wrkforce), Aggregation (Wrkforce), Plan Type (Capex), Aggregation (Capex), NumericAttrib
    No UDA's defined on "Entity"
    "NumericAttrib" attribute dimension (on base dimension "Entity"). NO attributes defined on the "NumericAttrib" dimension.
    NumericAttrib, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Operation
    "Employee" dimension properties and information:
    Employee, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Aggregation (Wrkforce)
    No UDA's defined on "Employee"
    "Line Item" dimension properties and information:
    Line Item, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Aggregation (Capex)
    No UDA's defined on "Line Item"
    "Asset Class" dimension properties and information:
    Asset Class, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Operation, Aggregation (Capex)
    No UDA's defined on "Asset Class"
    Exchange Rates properties:
    Table, Description, To Currency, From Currency, Operation, Method, Historical, Beg Balance, Year, Period, Average, Ending
    UDA properties:
    Dimension, UDA, Operation
    Smartlist properties:
    SmartList Name, Operation, Label, Display Order, Missing Label, Use Form Missing Label, Entry ID, Entry Name, Entry Label
    No Planning Unit Hierarchies are defined in this application.
    Translation input file fields:
    Value, Driver Member, Point-of-View, Data Load Cube Name
    [Thu Oct 27 18:16:18 JST 2011]Successfully located and opened input file "C:\TEMP\PLNentityバージョンのエクスポート.csv".
    [Thu Oct 27 18:16:18 JST 2011]Input file being read with UTF-8 encoding.
    [Thu Oct 27 18:16:18 JST 2011]Detected a UTF-8 BOM marker in input file "C:\TEMP\PLNentityバージョンのエクスポート.csv".
    [Thu Oct 27 18:16:18 JST 2011]Header record fields: Entity, Parent, Alias: Default, Alias: FromDepartment, Alias: ToDepartment, Valid For Consolidations, Data Storage, Two Pass Calculation, Description, Formula, UDA, Smart List, Data Type, Base Currency, Plan Type (PL), Aggregation (PL), Plan Type (BS), Aggregation (BS), Plan Type (Plan3), Aggregation (Plan3), Plan Type (Wrkforce), Aggregation (Wrkforce), Plan Type (Capex), Aggregation (Capex)
    [Thu Oct 27 18:16:18 JST 2011]Located and using "Entity" dimension for loading data in "予算応用" application.
    [Thu Oct 27 18:16:18 JST 2011]Load dimension "Entity" has been unlocked successfully.
    [Thu Oct 27 18:16:18 JST 2011]A cube refresh operation will not be performed.
    [Thu Oct 27 18:16:18 JST 2011]Create security filters operation will not be performed.
    [Thu Oct 27 18:16:18 JST 2011]Examine the Essbase log files for status if Essbase data was loaded.
    [Thu Oct 27 18:16:18 JST 2011]Planning Outline load process finished (with no data load as specified (/N)). 9 data records were read, 9 data records were processed, 9 were accepted, 0 were rejected.

    Thank you for your reply.
    With your help, I can verify it easier rather than creating dataform to verify it.
    I have resolved the question now, the root cause is I had used the wrong parameter, shouldn't add '/N' in the command. for /N is a dry run to check whether there are error in CSV file, it won't perform metadata load.
    If no error occured, run the command without /N, then the metadata load will be performed.
    I refer to this artical,
    http://john-goodwin.blogspot.com/2008/08/time-to-look-in-bin.html
    Best regards,
    Samantha
    Edited by: Samantha on 2011-10-31 下午4:39

  • 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.

  • Understanding dimensions and issues w/ Bridge

    So I'm super new to Illustrator and I'm trying to wrap my head around some basic things and I'm an idiot because I'm just not getting it. What I'm trying to do actually is create a properly sized file to upload to Zazzle, if you're familiar with the site. I downloaded one of their guide files in the 5x7 size to play around with but they don't have one for the posters which is what I want to create. My problem is that while their guide file shows in Adobe Bridge with dimensions as 5x7 inches and 1400x1000 pixels at 200 PPI in the RGB color mode, but a similar file that I created from scratch with inches being the unit shows in Bridge with no value for the inches dimensions, the PPI, or color mode and with a value of pixels at 504x360. Why is there a difference? How the heck do I get 200 PPI? Why are all these values missing from the file properties in Bridge and why are the pixels so small? I've tried it the other way around and created a file using pixels as the units and entered 1400x1000 pixels but once it's created if I switch my Rulers to inches they show the size being almost 20x14 inches - what the? Either way, any document I create is missing those file property values in Bridge.
    Here are my settings when creating a file (I choose the Basic RGB profile first then change the dimensions and raster effects):
    Now here is how the Zazzle guide file's file properties look in Adobe Bridge:
    Then here is how the file properties of the file I created from scratch looks:
    It'd be really nice to figure out how to create a file that looks the same file property-wise and dimensions-wise as the Zazzle guide file. Why am I getting this wonky behavior in Bridge? What am I doing wrong?

    Thanks Jacob. Let me ask you this, can you create a raster image but it still be in the .AI file format? If so, how?
    I think I kind of get what you're saying, but I feel like everyone is telling me I can't create a white elephant even though I'm standing right next to one. Their 5x7 guide file is 1000x1400 pixels and it's an .AI file not exported as whatever - how is that possible?
    Here is the link to the recomended sizes for all their products:
    http://zazzle.custhelp.com/app/answers/detail/a_id/85/~/recommended-image-sizes-and-resolu tion
    Here is a link to the guide files:
    http://www.zazzle.com/mk/custom/guidefiles
    Here is a link to download my white elephant of a file:
    http://asset.zcache.com/assets/graphics/z2/mk/custom/guideFiles/AI/invitation_5x7_vertical .ai
    How do I recreate that file?

  • Pixel Dimensions and File Size

    Can anybody please explain the relation between pixel dimensions and file size?
    Being naive, (or straight-forward if you prefer) I had assumed that pixel dimensions wide times pix dimension high = file size. Wrong!
    For instance a .JPG file 374 X 500 has a file size of 41,275 bytes. But 374 times 500 = 18,700 so the two are different issues.

    Thanks Rich. It kind of sounds like you know something about this.
    I see 1 pixel, and 24 bit color would make 24 bits at 8 bits to a byte, so there's the 3 bytes.
    I selected a certain photo and used the APPLE i command to see if could find if it had 8 bit color or, whatever. That infomation was not on the info function, but it did say something about RGB color profile.
    Is 8 bit color a near certain bet in most applications, or was that just for the sake of illustration?
    I Googled 8 bit color and go to a Wikipedia Article
    http://en.wikipedia.org/wiki/Color_depth
    which explained a lot, but its more technical depth than what I'm prepared to deal with. The net net, as far as I can tell is that image size (before compression) is dimension times color depth in its native mode, but I suppose what the native mode is and what the displayed mode is could be separate issues?
    I was under the impression that the compression in JPG formt files comes out, or is decompressed, when the photo is printed or displayed? No?

  • 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;

  • 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

  • JTable and cell color

    Hello, hope you can help me here -
    I have a JTable, and based on the value of a certain column in a row, I want the background color of that entire row to change to a different color. How can I perform this operation?
    I have tried to override JTable's prepareRenderer, but it doesn't seem to be working.
    Any clues?
    Thanks!
    -Kirk

    Hi.
    First of all. Try searching the forum there have been plenty of posts on this subject.
    Now to answer your question of how to set the color. The trick lies in the cellrenderer.
    A JTabel contains several models internally. If I'm not mistaking the ColumnModel contains the appropriate rendere for every column. The simplest thing to do in my opinion is to use a decorator pattern on the TableCellRenderer interface. Something along the likes of this.
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class ColorTableCellRenderer implements TableCellRenderer {
    private TableCellRenderer render;
    public ColorTableCellRenderer( TableCellRenderer render ){
    this.render = render;
    * @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object,
    * boolean, boolean, int, int)
    public Component getTableCellRendererComponent( JTable table , Object value , boolean isSelected , boolean hasFocus ,
    int row , int column ) {
    if( table != null ){ //Replace with specific condition
    Component cmp = this.render.getTableCellRendererComponent( table , value , isSelected , hasFocus , row , column );
    cmp.setBackground( Color.cyan );
    //Maybe need to call a validate or setOpaque. if experiencing problems.
    return cmp;
    }else{
    return this.render.getTableCellRendererComponent( table , value , isSelected , hasFocus , row , column );
    After that the easiest to do is set the defaultCellrenderer of your table in the following fashion.
    table.setDefaultRenderer(Object.class, new ColorTableCellRenderer( table.getDefaultRenderer(Object.class) ));
    Or this should also work.
    table.getColumnModel().getColumn(0).setCellRenderer(new ColorTableCellRenderer(chosenRenderer));
    Hope this helps & Good luck!

  • 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.

  • Possible to limit dimensions and measures when creating presentations?

    We are trying to use OLAP/BI Beans to add BI functionality to our next-generation data warehouse application. This application has its own security framework, with the ability to define permissions/privileges for objects. We need to integrate BI Beans/OLAP with this security framework.
    One of the things we need to do is control which OLAP objects (like dimensions and measures) are available to a given user in the Items tab when creating a presentation. For example, user A might see dimensions Alpha, Bravo and measure Charlie, while user B might see dimensions Delta, Echo and measure Foxtrot.
    We need to be able to apply these dimension/measure restrictions without using different Oracle users, with each having access only to their own OLAP objects. Our data warehousing application does not use Oracle and Oracle users to control security; it has its own internal frameworks for privileges/permissions. We therefore need to find a way to restrict access to OLAP objects in some programmatic way.
    Here's an example of how this might work:
    - I am a clinical analyst. I sign on to the data warehouse application. The data warehouse knows that as a clinical analyst, I have access to a certain list of objects and functionality across the application. One of the apps I have privilege to is the BI Bean Presentation Creation Application, so I click the menu to bring this up. I can now create BI presentations, but since I am a clinical analyst my list of available dimensions and measures do not contain any of the G/L, payroll or other financial OLAP objects.
    - If I signed onto the data warehousing application as a different user, one that has a financial analyst role, I might see a different set of OLAP objects when I run the presentation application application.
    So what we need is some API way to specify which dimensions and measures are available to a given user when they launch the presentation wizard. I've been digging through the BI Beans help and javadoc and have found a few things, but they aren't what I need.
    Here's what I found:
    - setItemSearchPath: this allows you to specify which folders are to be displayed. We want control at the OLAP object level, not at the folder level, so this doesn't work for us
    - setVisibleDimensions: this controls which dimensions are available in the Dimensions tab, not which dimensions can be selected in the Items tab. Doesn't work for us
    - setDimensionContext/setMeasureContext: These might work for us but I haven't been able to get them to retrieve anything yet. It also seems to me that these might set which dimensions/members are initially selected in the Items tab, not the list of dims/measures that are available for selection.
    Any assistance on this matter would be greatly appreciated.
    s.l.

    Reply from one of our developers:
    The get/setMeasureContext and get/setDimensionContext methods are currently only used by the Thick CalcBuilder (in a few limited scenarios) and cannot be used "to scope the dimensions and measures listed in Query and Calc builder based on user access rights".
    The scoping of dimensions and measures based on user access rights should be performed at the MetadataManager/Database level.
    This may change going forward as the real issue here is the static nature of the metadata and a general issue with the GRANT option within the database. So from the database perspective it is not possible to grant select priviledges on a single column of a table.
    The metadata issue is more complex as the OLAP API reads the metadata only once on startup of a session. The list of available measures is based on the GRANT priviledge, so for relational OLAP this limits the data scoping capabilities. In 10g, the metadata for AW OLAP becomes more dynamic and contained and read directly from the AW. Therefore, with an AW OLAP implementation with 10g it could be possible to scope boht dimensions and measures quickly and easily.
    Hope this helps
    Business Intelligence Beans Product Management Team
    Oracle Corporation

  • I would appreciate it if someone could advise me as to the optimum resolution, dimensions and dpi for actual photographic slides that I am scanning for use in a Keynote Presentation, that will be projected in a large auditorium.  I realize that most proje

    I would appreciate it if someone could advise me as to the optimum resolution, dimensions and dpi for actual photographic slides that I am scanning for use in a Keynote Presentation, that will be projected in a large auditorium. I realize that most projectors in auditoriums that I will be using have 1024 x 1200 pixels, and possibly 1600 x 1200. There is no reference to this issue in the Keynote Tutorial supplied by Apple, and I have never found a definitive answer to this issue online (although there may be one).
                Here’s my question: When scanning my photographic slides, what setting, from 72 dpi to 300 dpi, would result in the best image quality and use up the most efficient amount of space? 
                Here’s what two different photo slide scanning service suppliers have told me: 
    Supplier No. 1 tells me that they can scan slides to a size of 1544 x 1024 pixels, at 72 dpi, which will be 763 KB, and they refer to this as low resolution (a JPEG). However, I noticed when I looked at these scanned slides, the size of the slides varied, with a maximum of 1.8 MB. This supplier says that the dpi doesn’t matter when it comes to the quality of the final digital image, that it is the dimensions that matter.  They say that if they scanned a slide to a higher resolution (2048 x 3072), they would still scan it at 72 dpi.
    Supplier No. 2: They tell me that in order to have a high quality image made from a photographic slide (starting with a 35 mm slide, in all cases), I need to have a “1280 pixel dimension slide, a JPEG, at 300 dpi, that is 8 MB per image.” However, this supplier also offers, on its list of services, a “Standard Resolution JPEG (4MB file/image – 3088 x 2048), as well as a “High Resolution JPEG (8 MB file/image – 3088x2048).
    I will be presenting my Keynotes with my MacBook Pro, and will not have a chance to try out the presentations in advance, since the lecture location is far from my home, so that is not an option. 
    I do not want to use up more memory than necessary on my laptop.  I also want to have the best quality image. 
    One more question: When scanning images myself, on my own scanner, for my Keynote presentations, would I be better off scanning them as JPEGs or TIFFs? I have been told that a TIFF is better because it is less compressed. 
    Any enlightenment on this subject would be appreciated.
    Thank you.

    When it comes to Keynote, I try and start with a presentation that's 1680 x 1050 preset or something in that range.  Most projectors that you'll get at a conference won't project much higher than that and if they run at a lower resolution, it's better to have the device downsize your Keynote.  Anything is better than having the projector try and upsize your presentation... you work hard to make it look good, and it's mangled by some tired Epson projector.
    As far as slides go, scan them in at 150 dpi or better, and make them at least the dimensions of your presentation.  Keynote is really only wanting 72dpi, but I do them at 150, just in case I need to print out the presentation as a handout later, and having the pix at 150 dpi gives me a little help with their quality on a printer.
    You'd probably have to drop in the 150 versions again if you output the Keynote to .pdf or Word or something, but at least you have the option.
    And Gary's right (above) go ahead and scan them as TIFFs.  Sooner or later you'll want to do something else with these slides (like make something for an iPad or the like) and having them as TIFFs keeps your presentation looking good.
    Finally, and this is a big one, get to the location for your presentation ahead of time if you can, and plug the laptop in and see what you get.  There's always connection problems. Don't let the AV bonehead tell you everything will work just fine ('... I don't have any adapters for a Mac...') .  See it for yourself... you're the one that's standing up there.  Unless it's your boss, then you better be really sure it works.

  • My tx is so slow, the web cam is not working, the screen freezes and got color distortions

    - My tx is so slow, and heats up very fast... so i think that the advance is not working properly
    - the web cam is not working, since the 3th time iused... when i try to use it with my msn... got freezed, then y try ending the process and doesnt work, y     have to restart it but it stay just on logging off... and do nothing more... so i have to switch off directly from the power button
    - The screen freezes... some thimes the screen got freezed... and got color distortions too... so i have to to switch off again directly from the power button
    i was thinking that it was a software problem... but i restore my lap and it doesnt work cuz it still being with the same problems... so lately im thinking that its a hardware problem... i call to technical support from mexico... but they can do nothing for me cuz i bought my lap at circuitcity from el paso... and that store close a few months ago... so i need help before de warrantie expires...
    This is the second time that my lap gives me problems, last time I made the change at the store but this time it will be impossible cuz is now closed...
    that is why I seek your help...
    i will be grateful if you answer in Spanish because my English is not very good...
    thankyou so much...

    If your warranty has not yet run out get it serviced, now!  All of the comments seem to indicate that it is the motherboard>

Maybe you are looking for

  • New iTouch...getting BSOD when trying to sync

    I got my iTouch for Christmas and am very disappointed. Every time I would try to sync it I get the BSOD once music has been uploaded to it. I've got 3 music videos on it, none of my "tv shows". Forget trying pictures. Would be nice, but...with the p

  • Student needing some questions answered about Manufacturing Scheduling software

    Greetings; I am a undergraduate senior at Arizona State University majoring in Supply Chain Management. I am currently doing a project about Oracle's Manufacturing Scheduling option and have a few general questions for those of you that have used the

  • How to create/use SAP Exit variable of Query designer

    Hello experts, Can you please guide me on how to create/use SAP Exit variables ? Is there any way we can transport customer exit include in which we write all codes related to customer exit variables? Kindly provide your valuable inputs on this. Than

  • Error 500 using parameter in Task Flow

    i am using number parameter to call Bounded task flow java.lang.IllegalArgumentException: Cannot convert 10 of type class oracle.adfinternal.view.faces.model.binding.FacesCtrlAttrsBinding to class oracle.jbo.domain.Number      at com.sun.el.lang.ELSu

  • Launch apple store from AIR app (IOS)

    Hi, How I could launch the apple store from my flex AIR app? I need the tipical "go to app store" button... Thanks! Jorge