Unexpected width of a JPanel

Hi,
Yesterday I had a problem with a Traffic Light I am creating, as a part of a bigger project. I got helped (thanks for the help), and that problem is solved. Today I noticed something else. The construction I use is a JPanel, containing a button above a traffic light. The button contains a customer name. Under this button, the traffic light displays the severity of a customer problem. What I noticed is that the space to the right of the button is bigger than the space to the left of the button. This problem does not exist when I use a Gridlayout. I use the Boxlayout so the button does not get the same size as the lights of the traffic lights. Does anyone know what I can do to get that space to the right of the button away?
The code (which should compile and run without a problem) I use is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
* Temporary class to be loaded into the TlsFrame for testing purposes
public class TrafficLight extends JPanel
                          implements ActionListener {
     private Border raisedBevel;
     private JButton tlsButton;
     private JComponent component;
     private TlsLight redLight;
     private TlsLight yellowLight;
     private TlsLight greenLight;
     private String name;
     private String problemLevel;
     private boolean isNewProblem;
     public TrafficLight (String theName, String theProblemLevel, boolean theNewProblem) {
          name = theName;
          problemLevel = theProblemLevel;
          isNewProblem = theNewProblem;
          // Create the borders
          raisedBevel = BorderFactory.createRaisedBevelBorder();
          setUp();
      * Places all items on this Panel.
     private void setUp() {
          component = createComponent();
          add(component);
          if (isNewProblem)
              component.setBackground(Color.GRAY);
          else
              component.setBackground(Color.BLACK);
          setVisible (true);
     private JComponent createComponent () {
          // JPanel panel = new JPanel( new GridLayout(4, 1) );
          JPanel panel = new JPanel ();
          panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
          panel.setBorder(raisedBevel);
          // Create the button containing the Customer name
          tlsButton = new JButton(name);
          tlsButton.setActionCommand(name);
          tlsButton.addActionListener(this);
          panel.add(tlsButton);
          // Create the lights
          boolean isOn = true;
          boolean isNewProblem = true;
          redLight = new TlsLight (Color.RED, isOn, isNewProblem);
          panel.add(redLight);
          yellowLight = new TlsLight (Color.YELLOW, !isOn, isNewProblem);
          panel.add(yellowLight);
          greenLight = new TlsLight (Color.GREEN, isOn, !isNewProblem);
          panel.add(greenLight);
          return panel;
     public void actionPerformed(ActionEvent event) {
          String command = event.getActionCommand();
          if (name.equals(command)) {
               component.setBackground (Color.BLACK);
               // Set redLight to black and greenLights background to gray
               redLight.setLight(false);
               redLight.setBackground(false);
               yellowLight.setBackground(false);
               greenLight.setBackground(false);
               repaint();
     static public class TlsLight extends JPanel {
          protected boolean isOn;
          protected boolean isNewProblem;
          protected int xPos;
          protected int yPos;
          protected int width = 80;
          protected int height = 80;
          protected Dimension preferredSize;
          protected Color theColor;
          protected Color background;
          private int insets = width/20;
          public TlsLight (Color aColor, boolean lightIsOn, boolean hasNewProblem) {
               theColor = aColor;
               isOn = lightIsOn;
               isNewProblem = hasNewProblem;
              preferredSize = new Dimension( width, height );
          public Dimension getPreferredSize() {
               return preferredSize;
          public void paint (Graphics graphics) {
               int diameter = width - 2 * insets;
               // Paint the background (square) based on Customer having a new problem or not
               if(isNewProblem) {
                    background = Color.GRAY;
               else {
                    background = Color.BLACK;
               graphics.setColor(background);
               graphics.fillRect(xPos + 10, yPos, width, height);
               // Set color light based on problemStatus
               if(isOn) {
                    graphics.setColor(theColor);
               } else {
                    graphics.setColor(background);
               graphics.fillOval(xPos + insets + 10, yPos + insets, diameter, diameter);
               // Set the background of the light
               graphics.setColor(Color.WHITE);         
               // Paint the background
               graphics.drawOval(xPos + insets + 10, yPos + insets, diameter, diameter);
          public void setLight (boolean setLight) {
               isOn = setLight;          
          public void setBackground (boolean setBackground) {
               isNewProblem = setBackground;
     public static void main (String [] args) {
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          TrafficLight light = new TrafficLight("A Customer", "ERR", true);
          frame.add(light);
          frame.pack();
          frame.setVisible(true);
}The code contains both layouts, so it should not be a big problem to see what I mean. Hope someone can help me.
TIA,
Abel

Nest panels and layouts. Put the button in its own jpanel, set the panel's opaque to false so the underlying color comes through and then add the panel to the main panel:
        // Create the button containing the Customer name
        tlsButton = new JButton(name);
        tlsButton.setActionCommand(name);
        tlsButton.addActionListener(this);
        //using flowlayout is redundant here -- it's the default layout
        // but i'm doing this to illustrate what's happening.
        JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        btnPanel.setOpaque(false);  // so underlying color isn't changed
        btnPanel.add(tlsButton);
        panel.add(btnPanel);

Similar Messages

  • How do you define the width of a JPanel?

    How do you define the width of a JPanel?

    it may not be perfect but this is what i have tried:
    import javax.swing.*;
    import java.awt.event.*;
    public class myPane extends JFrame {
         public myPane() {
              super("myPane");
              setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
              JButton myButt = new JButton("press");
              JPanel pane = new JPanel();
              pane.add(myButt);
              setContentPane(pane);
         public static void main(String args[]) {
              myPane p1 = new myPane();
              p1.setBounds(20, 20, 600, 400);
              p1.setVisible(true);
    }

  • How do i get the width of a JPanel

    Hey
    Im trying to get the width of my JPanel with this code, but it just prints 0, what am i doing wrong?
    public class GamePanel extends JPanel implements Runnable {
         private static final int PWIDTH = 500;   // size of panel
         private static final int PHEIGHT = 400;
         private static final int NO_DELAYS_PER_YIELD = 16;     
         private static int MAX_FRAME_SKIPS = 5;
         private MovingGame frame;
         private Thread animator;
         private volatile boolean running = false;   // used to stop the animation thread
         private long gameStartTime;   // when the game started
         private BallSprite ball;
         //      off-screen rendering
         private Graphics dbg;
         private Image dbImage = null;
         //      holds the background image
         private BufferedImage bgImage = null;
         public GamePanel(MovingGame frame){     
              this.frame = frame;
              setDoubleBuffered(true);
              setBackground(Color.blue);
              setPreferredSize( new Dimension(PWIDTH, PHEIGHT));
              setFocusable(true);
              requestFocus();
              addKeyListener( new KeyAdapter() {
                   public void keyPressed(KeyEvent e)
                       { processKey(e);  }
              ball = new BallSprite(40, 40, this);
              System.out.println("Width: " + getWidth());    <------- this prints 0
         }

    veldhanas wrote:
    Hi,
    Use
    setSize(PWIDTH, PHEIGHT); instead of
    setPreferredSize( new Dimension(PWIDTH, PHEIGHT));ThanksWrong Wrong Wrong Wrong
    .setSize() sets the size of the component at that instant in time and has no effect on anything the layout managers do with the component. .setPreferredSize() sets the size the layout manager will look at (assuming it cares about what size you want the component at).

  • How to set Width of a JPanel?

    I am overwirting paintComponent(Graphics g) method to
    draw some g2D in a JPanel.
    I want the drawing processing shown on screen (not flashed out after drawn because it is VERY SLOW).
    So that I CAN NOT use setsize() or setBound() because to change JPanle.width because this is NOT what I wanted(the graphics is shown AFTER is drawn).
    Everytime I call paintComponent(), the width of JPanel is changed.
    My question is : How can change JPanel.width without calling method like setsize() or setBound() .
    Thanks a lot!!

    My code too large, I just show some idea here:
    class caller (){
    myPanel p;
    Graphics2D g2 = (Graphics2D)p.getGraphics();
    //I nee to increase the p.width before call my_paint
    //I CAN NOT use setsize() or setBound()
    //because I want show the drawing process
    //on screen( and that is fast)
    p.my_paint(g2); // how to set p.width ??
    public class myPanel extends JPanel
    public void my_paint(Graphics2D g2)
    //Do my drawing here ,
    // I need to draw thousands of Line2D.
    public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D)g;
    my_paint(g2);

  • Weird JPanel Resizing Problem

    This program works as I want it to with one exception: sometimes when resizing the frame, the contained JPanels do not fully cover the frame's BorderLayout center region. If you run the program you'll discover that a light gray area often appears on the right and bottom edges of the frame when it's resized. Any ideas? Thanks. I'm using version 1.3.1._01 on Windows 98.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Grid extends JPanel implements ComponentListener
    private int rows, columns;
    private Block[][] block;
    public Grid()
    rows = 20;
    columns = 10;
    block = new Block[rows][columns];
    setLayout(new GridLayout(rows,columns,0,0));
    for (int i = 0; i < rows; i++)
    for (int j = 0; j < columns; j++)
    block[j] = new Block();
    if ((i % 4) >= 1)
    block[j].turnOn();
    else
    block[j].turnOff();
    add(block[j]);
    }//end inner for loop
    }//end outer for loop
    setBorder(BorderFactory.createLineBorder(Color.black,4));
    addComponentListener(this);
    }//end default constructor
    public Dimension getPreferredSize()
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    return new Dimension((block[0][0].getBlockWidth() * columns) + horizontalInsets,
    (block[0][0].getBlockHeight() * rows) + verticalInsets);
    }//end getPreferredSize
    public void componentHidden(ComponentEvent ce)
    //Invoked when the component has been made invisible.
    public void componentMoved(ComponentEvent ce)
    //Invoked when the component's position changes.
    public void componentResized(ComponentEvent ce)
    //Invoked when the component's size changes.
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    setPreferredSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
    setMinimumSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
    public void componentShown(ComponentEvent ce)
    //Invoked when the component has been made visible.
    public static void main(String[] args)
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Grid(),BorderLayout.CENTER);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Block extends JPanel implements ComponentListener
    private int blockWidth, blockHeight;
    private Color blockBackgroundColor, blockBorderColor, onColor;
    private String blockOwner;
    private boolean isOn;
    public Block()
    blockWidth = 20;
    blockHeight = 20;
    //setSize(20,20);
    //setPreferredSize(new Dimension(20,20));
    blockBackgroundColor = Color.gray;
    blockBorderColor = Color.black;
    setLayout(new BorderLayout(0,0));
    setBorder(BorderFactory.createLineBorder(blockBorderColor,1));
    setBackground(blockBackgroundColor);
    isOn = false;
    blockOwner = "1";
    onColor = Color.orange;
    addComponentListener(this);
    setVisible(true);
    }//end default constructor
    public Block(int blockWidth, int blockHeight)
    this();
    this.blockWidth = blockWidth;
    this.blockHeight = blockHeight;
    }//end two-arg constructor
    public void setBlockWidth(int blockWidth)
    this.blockWidth = blockWidth;
    public int getBlockWidth()
    return blockWidth;
    public void setBlockHeight(int blockHeight)
    this.blockHeight = blockHeight;
    public int getBlockHeight()
    return blockHeight;
    public void setBlockBorderColor(Color blockBorderColor)
    this.blockBorderColor = blockBorderColor;
    public Color getBlockBorderColor()
    return blockBorderColor;
    public void setBlockBackgroundColor(Color blockBackgroundColor)
    this.blockBackgroundColor = blockBackgroundColor;
    public Color getBlockBackgroundColor()
    return blockBackgroundColor;
    public void setOnColor(Color onColor)
    this.onColor = onColor;
    public Color getOnColor()
    return onColor;
    public void turnOn()
    setBackground(onColor);
    isOn = true;
    public void turnOff()
    setBackground(blockBackgroundColor);
    isOn = false;
    public void setBlockOwner(String blockOwner)
    this.blockOwner = blockOwner;
    public String getBlockOwner()
    return blockOwner;
    public Dimension getPreferredSize()
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    return new Dimension(blockWidth + horizontalInsets,
    blockHeight + verticalInsets);
    }//end getPreferredSize
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    if (isOn)
    FontMetrics fm = g.getFontMetrics();
    int blockOwnerWidth = fm.stringWidth(blockOwner);
    int blockOwnerAscent = fm.getAscent();
    int x = (blockWidth / 2) - (blockOwnerWidth / 2);
    int y = (blockHeight / 2) + (blockOwnerAscent / 2);
    g.drawString(blockOwner,x,y);
    }//end paintComponent
    public void componentHidden(ComponentEvent ce)
    //Invoked when the component has been made invisible.
    public void componentMoved(ComponentEvent ce)
    //Invoked when the component's position changes.
    public void componentResized(ComponentEvent ce)
    //Invoked when the component's size changes.
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    blockWidth = this.getWidth();
    blockHeight = this.getHeight();
    setPreferredSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
    setMinimumSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
    public void componentShown(ComponentEvent ce)
    //Invoked when the component has been made visible.

    Your problem is due to the use of a GridLayout.
    With a GridLayout, all components must have the same dimension. And the extra space has to be divisible by the number of components to be distributed to each component :
    For example : In a component with a GridLayout, you have a line with 10 JPanels. The width of the component is initially 100. In this case, each JPanel will have a width of 10 (10*10=100).
    If you resize the main component to a width of 110, each JPanel will have a size of 11 (11*10=110).
    But in the case where the width is not divisible by the number of JPanels, there will be an extra-space :
    if the width of the component is 109, the width of each JPanel will be 10 and there will be an extra-space of 9 (10*10+9 = 109).
    I hope this helps,
    Denis

  • Screen dump of JPanel to Image

    I'm working on an extensive error dialog which will send all relevant information to a support apparatus. This includes collecting the stack-trace received from the exception, java console log and a screen dump of the underlying JPanel.
    The dialog is a modal dialog residing on top of the JPanel in question. I can retreive the parent panel's Graphics object and need to print the JPanel with all it's children to an Image object.
    This should be possible, but how?
    Another thing, is the java console available from the client code? The code runs as an applet on Windows clients.

    I've never tried this, but the idea I have is to create a BufferedImage, and getGraphics() of the BufferedImage. Now call paint() of the JPanel and pass it the graphics object.
    Maybe you also have to pre-obtain the height/width of the JPanel for the size of the Image.

  • Question about relative sizing on JPanels

    Hi,
    My question is about relative sizing on components that are not drawn yet. For example I want to draw a JLabel on the 3rd quarter height of a JPanel. But JPanel's height is 0 as long as it is not drawn on the screen. Here is a sample code:
    JPanel activityPnl = new JPanel();
    private void buildActivityPnl(){
            //setting JPanel's look and feel
            activityPnl.setLayout(null);
            activityPnl.setBackground(Color.WHITE);
            int someValue = 30;  // I use this value to decide the width of my JPanel
            activityPnl.setPreferredSize(new Dimension(someValue, 80));
            //The JLabel's height is 1 pixel and its width is equal to the JPanel's width. I want to draw it on the 3/4 of the JPanel's height
            JLabel timeline = new JLabel();
            timeline.setOpaque(true);
            timeline.setBackground(Color.RED);
            timeline.setBounds(0, (activityPnl.getSize().height * 75) / 100 , someValue , 1);
            activityPnl.add(timeline);
        }Thanks a lot for your help
    SD
    Edited by: swingDeveloper on Feb 24, 2010 11:41 PM

    And use a layout manager. It can adjust automatically for a change in the frame size.
    Read the Swing tutorial on Using Layout Managers for examples of the different layout managers.

  • BoxLayout not respecting maximumSize?

    Hi,
    When the preferred width of a JPanel is long enough but its maximum width is restricted using setMaximumSize it seems that BoxLayout does not respect the maximum width.
    If the preferred size is also set then the max width is respected, but then some of the text is not displayed despite the scrollbar...
    Anyone has any explanation for this or is this expected?
    An example is below where the max width of labelPanel (105) is not respected:
    static String value = "Part One of the Essential Information Record (Questions 1-22) provides baseline information for ggggg in an ggggggggg. All these questions MUST be answered before any uuuuu/lllll person can be left in a placement. The information should be given to ggggg with the ggggggggg Agreement. Wherever possible, Part Two (Questions 22-63) should be completed BEFORE the person is looked after. In the case of an ddddddddd admission it should be completed AS SOON AS POSSIBLE thereafter. Both parts of the Essential Information Record should be updated before each review, on a supplementary sheet if necessary. Copies should be sent to residential people and ggggg. A further copy should be kept on the uuuuu/lllll person's file.";
    Label label = new JLabel("<html>" + value + "</html>");
    label.setBorder(BorderFactory.createLineBorder(new Color(255, 0, 0)));
    JPanel labelPanel = createVBox();
    labelPanel.add(label);
    labelPanel.setAlignmentY(Component.TOP_ALIGNMENT);
    labelPanel.setMaximumSize(new Dimension(105, 20000000));
    labelPanel.setBorder(BorderFactory.createLineBorder(new olor(255, 0, 0)));
    JPanel hbox3 = createHBox();
    JPanel vb3 = createVBox();
    vb3.setPreferredSize(new Dimension(160, 100));
    vb3.setMaximumSize(new Dimension(160, 100));
    vb3.setBorder(BorderFactory.createLineBorder(new Color(255, 0, 0)));
    vb3.setAlignmentY(Component.TOP_ALIGNMENT);
    hbox3.add(labelPanel);
    hbox3.add(vb3);
    JPanel b1 = createVBox();
    b1.add(new ScrollPane(hbox3));
    JFrame frame = new JFrame("");
    frame.setContentPane(b1);
    where
    private static JPanel createVBox() {
    JPanel jp = new JPanel();
    jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
    return jp;
    private static JPanel createHBox() {
    JPanel jp = new JPanel();
    jp.setLayout(new BoxLayout(jp, BoxLayout.X_AXIS));
    return jp;

    BoxLayout assumes that a component's minimum size is smaller than the component's preferred size and that the preferred size is smaller that the maximum size. The first thing BoxLayout checks is whether the preferred size will fit. If not, the BoxLayout will make the component smaller than the preferred size, but no smaller than the minimum size. There is no reason to check the maximum size if the preferred size is already too big and the assumption holds true. Setting the maximum size to be smaller than the preferred size is an error which causes unexpected behavior. Just make sure the min <= pref <= max and everything will work as it is supposed to.

  • Webcam is not working on skype with Ubuntu 12.04

    I posted a week ago that I had solved the problem by downloading Skype 4.0 for Linux. However it turns out I spoke too soon. The video just freezes in Skype, though it is fine in Cheese, the Ubuntu webcam app. So I'm still high and dry and have to resort to booting Windows, darn it. I am running 64 bit Xubuntu 12.04 on an AMD quadcore system.

    bash -c 'LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so skype'64 Bit
    bash -c 'LD_PRELOAD=/usr/lib32/libv4l/v4l1compat.so skype'
    https://help.ubuntu.com/community/Webcam/Troubleshooting Make a launcher and try either of the above. Below may help you.Copy and paste the line below into the Terminal and press Enter.sudo gedit /usr/local/bin/skypeThis will open your editor with a blank text file, copy and paste the following lines into your blank text file.Use lines below for x86(32bit)#!/bin/bash
    LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so /usr/bin/skype Use lines below for x64(64bit)#!/bin/bash
    LD_PRELOAD=/usr/lib32/libv4l/v4l1compat.so /usr/bin/skypeSave the file and close it.Now to make the file executable, copy and paste the following line into Terminal.sudo chmod a+x /usr/local/bin/skypePress Enter and close the Terminal, start Skype and webcam works.Now your webcam is working you can optionally (to improve the quality of your webcam picture), install v4l2ucp(video for linux 2 universal control panel) from the Software Manager.Type "v4l2ucp" in the search box and then select it.After installation go toMenu> Preferences > Video4Linux Control PanelThis will allow you to adjust the Contrast, Gamma, Auto Gain and Sharpness of your video. Simply click "Preview" and adjust the sliders to suit your requirements.If your webcam has a built-in microphone, to set it to default for use with Skype, go toMenu> Preferences > SoundClick on the input tab and select your webcam microphone from the choices listed for input devices.(Make sure microphone volume is not muted).As an alternative if the above fix does not work try using the lines below instead.Use lines below for x86(32bit)#!/bin/bash
    LD_PRELOAD=/usr/lib/libv4l/v4l2convert.so /usr/bin/skype Use lines below for x64(64bit)#!/bin/bash
    LD_PRELOAD=/usr/lib32/libv4l/v4l2convert.so /usr/bin/skypeMake file executable as above.Tested on Linux Mint 9(Isadora) 32 and 64 bit, Linux Mint 10(Julia) 32 and 64 bitSkype 2.1.0.81(Beta) with Logitech E1000 and Genius VideoCAM GE111 webcams
    1.1. SkypeThis information might be for the old versions of Skype and obsolete in 2010 and laterGo to main menu, System, Preferences, Menus: Applications, Internet, Items: Skype, Properties, and replace the Command withbash -c 'LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so skype'1.1.1. 64-bitbash -c 'LD_PRELOAD=/usr/lib32/libv4l/v4l1compat.so skype'If you get an error similar to the following:ERROR: ld.so: object '/usr/......../v4l1compat.so' from LD_PRELOAD cannot be preloaded: ignored.Check the correct path to "v4l1compat.so" on your system: Go to the menu places, "search for files" and search for "v4l1compat.so" Then, substitute the right path into the previous commands as follows:bash -c 'LD_PRELOAD=/The/Right/Path/v4l2convert.so skype'If the above doesn't work then try running the command from a terminal and look at the output. If it is complaining about "error unexpected width / height in JPEG headerexpected: 320x240, header: 1600x1200" then try the followingbash -c 'LD_PRELOAD=/usr/lib/libv4l/v4l2convert.so skype'1.1.2. 64-bitbash -c 'LD_PRELOAD=/usr/lib32/libv4l/v4l2convert.so skype'If the above even doesn't work then try the followingexport XLIB_SKIP_ARGB_VISUALS=1
    bash -c 'LD_PRELOAD=/usr/lib/libv4l/v4l2convert.so skype'1.1.3. 64-bitexport XLIB_SKIP_ARGB_VISUALS=1
    bash -c 'LD_PRELOAD=/usr/lib32/libv4l/v4l1compat.so /usr/bin/skype'1.2. A clean start for skypeThis can be tidied up by writing a small script in /usr/local/bin called skype that comes higher in the loading sequence that the script of the same name in /usr/bin/. That script is in charge of running skype; the new script loads the correct libraries then hands control to the former script.In terminal type:$ sudo gedit /usr/local/bin/skypeand paste the following 2 line code snippet into gedit:LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so
    /usr/bin/skypesave and close. Now back in terminal make it executable$ sudo chmod a+x /usr/local/bin/skypeReboot type skype and the web cam just works. This was tested on Lucid with a Logitech Quick Cam Communicator.https://help.ubuntu.com/community/Webcam/Troubleshooting

  • How to see all of TitledBorder?

    I've got a JPanel with a TitledBorder, but the contents of the panel are narrower than the title in the border and the title gets truncated.
    I note that the "minimum width" of the JPanel is set to the "minimum width" of the TitledBorder, which the documentation says is wide enough to display all the text, but the "preferred width" of the JPanel seems to have been calculated ignoring the border and is in fact narrower than its own minimum width!!
    What have I missed here?
    (1) How come the panel has calculated its preferred width to be less than its minimum width?
    (2) What am I supposed to do to get the TitledBorder to display all its title? (the default behaviour does seem rather odd, as I wouldn't have gone to all the trouble of creating a TitledBorder and giving it a title if I didn't want the users to actually be able to read it).

    I note that the "minimum width" of the JPanel is set
    to the "minimum width" of the TitledBorder, which the
    documentation says is wide enough to display all the
    text...Got a URL reference for that documentation? I looked in the API but didn't find it...

  • Rezised editable regins

    Hey all,
    I am running into an issue when I paste text into an
    editable region in an xhtml file--it automatically resizes the
    region width (to wider), and will not shrink again. I tried just
    copying unformatted text, that doesn't work. I also tried resetting
    the width of the table cell, and that of the editable region in the
    property inspector, but nothing happens.
    Seems like if the region width is set in the template (which
    it is) it shouldn't change in the xhtml file that it is applied to.
    Right?
    Thanks!
    Paul

    Two things that could be related to XHTML and the strict
    manner that tags must be closed
    If you are using tables and you have unexpected width changes
    in columns - then you can specify the width of your <td>...
    For example, if you have a <table width="100%"></table>
    - specify the width of the cells via the <td> tags - either
    relative with a percentage <td width="50%"></td> - be
    consistent for the first <tr> of the table, and you should
    see a remarkable difference. If you are using absolute sizing,
    i.e., <table width="760"></table> - inplying pixels,
    then set your <td width="300">... Take care that you don't
    have any conflicts in your style sheets (assuming you use CSS) that
    would confuse a browser
    Do you format your text with a CSS class? If so, you might
    have an issue where a <span class="classname"></span>
    is applied, but not closed or nested properly... Or you could have
    accidentally put content outside of the closed </td> tag - or
    worse yet, not closed the tag properly at all... perhaps
    accidentally deleted it when you pasted in the new content...
    That's a no-no in XHTML.
    Consider setting the overall content style in a class - this
    includes all the margins, cell widths, padding, etc. I prefer
    applying the class to the actual <p
    class="classname"></p> and only using a <span> tag
    when a temporary style change is used. Use contextual ids to define
    your major tags, too. CSS provides considerable strength if used
    cleverly.
    Quite honestly, I never build table structured sites any
    longer and love the freedom of CSS positioned sites - give me a
    <div> any day. But with clients, one has to work around
    existing site constructs and that often includes the necessity to
    use their tables... So... I'm used to trouble-shooting.
    In situations where XHTML is concerned, it is quite
    unforgiving if you haven't closed a tag or nested properly...
    unlike HTML, hierarchy is very important. If you're scratching your
    head, seriously just go to the WC3.org and try to validate your
    page... if there is a bona fide error in your coding - it will flag
    it for you.
    Hope this helps... good luck.

  • BlackjackGame

    Hi,
    For one of my college classes I volunteered to change a gui line blackjack program to a gui based on swing. This is my first time actually creating something useful with swing so my code probably sucks but it works for the most part.
    heres my problem...
    the cards are loaded onto the frame first by the GUIGame which makes a call to my addCard class and either executing one of the following methods, addCardDealer or addCardPlayer. My problem is that I have no idea how to load images and what would be the best way of loading my card images on to the screen.
    here is the relivant code that i'm working with...
    package blackjackpackage;
    * @author villajo
    public class GUIGame
    public void playGUI()
    BlackJackGUI GUI = new BlackJackGUI();
    addCard add = new addCard();
    //Instantiates our deck of cards object. Constructor builds the arraylist of Card Objects.
    Deck gameDeck = new Deck();
    Hand playerHand = new Hand();
    Hand dealerHand = new Hand();
    boolean continueGame = true;
    gameDeck.shuffle();
    //playerHand.add(gameDeck.draw());
    GUI.add(add.addCardPlayer(gameDeck.draw()));
    GUI.add(add.addCardDealer(gameDeck.draw()));
    GUI.add(add.addCardPlayer(gameDeck.draw()));
    GUI.add(add.addCardDealer(gameDeck.draw()));
    This is the BlackjackGUI. This is responsable for the buttons, menus, action handlers and anything that has to do with the BlackjackGUI..(I know that there aren't action handlers yet for the buttons.. thats coming in time..)
    * BlackJackGUI.java
    * Created on June 22, 2007, 10:38 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package blackjackpackage;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    * @author villajo
    public class BlackJackGUI extends JFrame
    /** Creates a new instance of BlackJackGUI */
    public BlackJackGUI()
    /*finds screenheight and width and sets the program to center.
    int screenHeight;
    int screenWidth;
    FindScreenSize screen = new FindScreenSize();
    screenHeight = screen.returnHeight();
    screenWidth = screen.returnWidth();
    setLocation(screenWidth / 4, screenHeight / 4);
    //create our JFrame
    setTitle("BlackJack");
    setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
    //this makes it so we CANNOT resize the window
    setResizable(false);
    //all menu stuff..
    BlackJackMenuBar MenuBar = new BlackJackMenuBar();
    BlackJackButtons buttons = new BlackJackButtons();
    add(buttons);
    setVisible(true);
    class BlackJackMenuBar
    protected BlackJackMenuBar()
    JMenu File = new JMenu("File");
    JMenu About = new JMenu("About");
    //File menu attributes..
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //adding the menus..
    menuBar.add(File);
    menuBar.add(About);
    //adding functions to menubar..
    File.addSeparator();
    File.add(new AbstractAction("Exit")
    public void actionPerformed(ActionEvent event)
    System.exit(0);
    About.add(
    new AbstractAction("About")
    public void actionPerformed(ActionEvent event)
    aboutWindow about = new aboutWindow();
    class addCard extends JPanel
    private static final int DEFAULT_WIDTH = 640;
    private static final int DEFAULT_HEIGHT = 480;
    public int playerScore = 0;
    public int dealerScore = 0;
    class BlackJackButtons extends JPanel
    public BlackJackButtons()
    BlackjackGame game = new BlackjackGame();
    JButton Hit = new JButton("Hit");
    JButton Stand = new JButton("Stand");
    //JButton Smack = new JButton("Smack");
    //adding the cute java image..
    setLayout(null);
    add(Hit);
    add(Stand);
    //add(Smack);
    Insets buttonInsets = getInsets();
    Dimension size = Stand.getPreferredSize();
    Hit.setBounds(220 + buttonInsets.left, 385 + buttonInsets.bottom, size.width, size.height);
    Stand.setBounds(310 + buttonInsets.left, 385 + buttonInsets.bottom, size.width, size.height);
    //Jpanel S
    //add action Listeners...
    //add JLabels
    //pastes our label on the panel..
    PlayerMessage player = new PlayerMessage();
    DealerMessage dealer = new DealerMessage();
    add(player);
    add(dealer);
    Insets playerInsets = getInsets();
    Insets dealerInsets = getInsets();
    Dimension dealerSize = dealer.getPreferredSize();
    Dimension playerSize = player.getPreferredSize();
    player.setBounds(15 + playerInsets.left, 80 + playerInsets.bottom, playerSize.width, playerSize.height);
    dealer.setBounds(15 + dealerInsets.left, 205 + dealerInsets.bottom, dealerSize.width, dealerSize.height);
    class PlayerMessage extends JPanel
    public PlayerMessage()
    JLabel player = new JLabel("Player:");
    add(player);
    class DealerMessage extends JPanel
    public DealerMessage()
    JLabel dealer = new JLabel("Dealer:");
    add(dealer);
    class addImage extends JLabel
    public void addImage(String card)
    //retrieve the card from the file of cards..
    ImageIcon icon = new ImageIcon("/home/villajo/blackjackPackage/src/blackjackpackage/Cards/" + card);
    icon.getImage();
    //this determines the bounds or the placement of the cards..
    class addCard extends JPanel
    public JLayeredPane addCardPlayer(Card card)
    *What i'm doing is finding the deck and tally so that I can put it on screen..
    //This finds the card and the score for that card and adds it to player..
    GUIHelper findNumber = new GUIHelper();
    int localScore = findNumber.WhatScoreAmI(card);
    String cardtype = card.toString() + ".jpg";
    //Load the appropriate Image..
    JLayeredPane layeredPane = new JLayeredPane();
    layeredPane.setPreferredSize(new Dimension(76,110));
    ImageIcon img = new ImageIcon(cardtype);
    img.getImage();
    JLabel label = new JLabel(img);
    layeredPane.add(label);
    return layeredPane;
    public JLayeredPane addCardDealer(Card card)
    GUIHelper findNumber = new GUIHelper();
    int localScore = findNumber.WhatScoreAmI(card);
    String cardtype = card.toString() + ".jpg";
    System.out.println(cardtype);
    //load the appropriate image..
    JLayeredPane layeredPane = new JLayeredPane();
    layeredPane.setPreferredSize(new Dimension(76,110));
    ImageIcon img = new ImageIcon(cardtype);
    img.getImage();
    JLabel label = new JLabel(img);
    layeredPane.add(label);
    return layeredPane;
    I know that I dont have the bounds set or any of the properties set up, I'm just wanting it to load up and from there I think I can figure it out. Some other information, the images are of JPG format and are located in the source file where all of the other sources and classes are located for the project.
    addCard class handles the adding of cards to new layers of the LayeredPanel. I thought this might be easier if I used a layered pane instead of adding a new JPanel.
    card takes in a card from another class called card but is passed through GUIgame to addCard. This is probably bad design practice, but i'm just trying to get it to work. What card does is takes a shuffled deck of cards and takes a card from it.
    thanks in advance for any help
    Joseph Villa

    I've used code like the following to load small images/icons for display:
        private static ImageIcon createImageIcon(String path) {
            if (path != null) {
                URL imgURL = MyMainClass.class.getResource(path);
                if (imgURL != null) {
                    return new ImageIcon(imgURL);
                } else {
                    log.error("Couldn't find file: " + path);
                    return null;
            } else {
                log.error("Cannot search for null image file.");
                return null;
        }which gets invoked with something like:
        public static final ImageIcon ICON_EXPAND_ALL = createImageIcon("/images/expandAll.gif");Note the path passed to the method is the path within the jarfile holding the application (which is what I think you meant in your problem description).
    Naturally, if you're loading a lot of images, you should move that code into a distinct thread, so the application doesn't seem to hang while loading them.
    Message was edited by:
    mbmerrill - to change name of main class to make it clear that it is, in fact, the main class

  • JSplitPane problems : how to set the size of one component to be constant?

    I have a horizontal JSplitPane, the left side of which is occupied by a JTextArea and the right side by a JPanel, which will later contain a JList.
    my problem is:
    when resize I resize the window:
    1. on expanding: the right side of the JSplitPane increases in size ( hence the JPanel increases in size ), while the JTextarea remains the same.
    2. on contracting: the JTextArea keeps becoming smaller and until it nearly vanishes, and then the JPanel starts contracting.
    It does not matter what corner or what size of the JFrame I use to resize it: the result is the same.
    what do i do to reverse the effect but with the following difference:
    On resizing, the following happens:
    1. on expanding: the size of the JPanel remains the same, and the JTextArea keeps getting bigger
    2. on contracting: the size of the JTextArea remains the same, and the JPanel contracts UNTIL IT REACHES A MINIMUM WIDTH. After this width, the JTextArea starts contracting, UNTIL THIS TOO REACHES A MINIMUM SIZE (both height and width). After this limit, no more contraction is possible.
    My code is:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    class MultiEditClient extends JFrame
         public MultiEditClient( String title )
              super(title);
              addComponents();
              addMenu();
         protected void addComponents()
              this.setBounds( 100,100,      500,500 );
              JPanel panel = new JPanel();
              JLabel label = new JLabel( "The to-be status bar." );
              label.setFont( new Font( Font.SANS_SERIF , Font.PLAIN , 14 ) );
              label.setMinimumSize( label.getMaximumSize() );
              JTextArea textarea = new JTextArea();
              textarea.setPreferredSize( new Dimension(400,400) );
              textarea.setMinimumSize( textarea.getMaximumSize() );
              JScrollPane scrollForTextArea = new JScrollPane(textarea);
              JPanel anotherpanel = new JPanel();
              anotherpanel.add( new JButton("Sample Button") );
              JSplitPane splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, scrollForTextArea, anotherpanel );
              splitPane.setOneTouchExpandable(true);
              panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS ) );
              Box vBox = Box.createVerticalBox();
              Box hBox2 = Box.createHorizontalBox();
              hBox2.add( splitPane );
              vBox.add( hBox2 );
              vBox.add( Box.createVerticalStrut(5) );
              Box hBox = Box.createHorizontalBox();
              hBox.add( Box.createHorizontalStrut(5) );
              hBox.add( label );
              hBox.add( Box.createHorizontalGlue() );
              vBox.add( hBox );
              vBox.add( Box.createVerticalStrut(2) );
              panel.add( vBox );
              add( panel );
         protected void addMenu()
              JMenuBar menubar = new JMenuBar();
              JMenu session = new JMenu( "Session" );
              JMenuItem joinSession = new JMenuItem( "Join Session" );
              session.add( joinSession );
              menubar.add( session );
              this.setJMenuBar( menubar );
         public static void main( String args[] )
              MultiEditClient theFrame = new MultiEditClient( "MultiEdit Client" );
              theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              theFrame.pack();
              theFrame.setVisible( true );
    }

    okay...
    I have a JFrame, that contains a JSplitPane with the splitter placed vertically so that it has a left side and a right side.
    In the left side a JTextArea is placed. In the right side a JPanel is placed, whic h will also contain a JList later.
    When I resize the frame along the height of the JFrame, the height of both the components (JTextArea and JPanel) increases - quite natural, no problems here.
    But when I resize the frame along the width I see the following behaviour:
    1. on expanding: the JTextArea retains its width, and the JPanel increases in width.
    2. on contracting: the JTextArea retains its width, and the JPanel contracts.
    after contracting to its minimum width, the JTextArea starts contracting.
    Desired behaviour: the JPanel maintains its width, no matter what. I only what the JTextArea to change in width.
    And after the JTextArea reaches a minimum width, the frame contracts no more ( this i can do by setting the frame's min size ).
    I hope I am more clear and less confusing this time :)
    thanks

  • Vertical Scrolling and Horizontal Wrapping in a JEditorPane

    Hey guys,
    Some of you may recall my [post |http://forums.sun.com/thread.jspa?threadID=5418688] from a couple weeks back. In it, I learned how to force (or appear to force) the text of a JEditorPane to grow from the bottom-up instead of top-down (picture the difference between how a chat window grows to how a word document grows). The solution (which solves my original problem perfectly) involves simply placing the JEditorPane into the South region of a JPanel.
    That was all fine and dandy, until I tried putting long lines of text into the JEditorPane. It scrolled vertically when it should have, but the text simply ran off the right side of the JEditorPane instead of wrapping (or showing a horizontal scrollbar).
    After a gross amount of googling, I finally came across this old [post |http://forums.sun.com/thread.jspa?threadID=5318664] that seems to be related to my problem here. It hinted that I should set the width of the JPanel to match the width of the JScrollPane's Viewport. While that does indeed fix the problem with horizontal wrapping, it now creates a problem with the vertical scrolling (which works fine without the fix for horizontal wrapping)!
    I've tried setting the preferred height of the JPanel to just about everything I can think of: the height of the viewport, extremely large numbers, negative numbers, zero, itself, the height of the JEditorPane. But they all do the same thing: no vertical scrollbar ever pops up, even when the text is obviously too long to fit in the window.
    Here's an SSCCE demonstrating what I'm talking about:
    import javax.swing.*;
    import java.awt.*;
    public class EditorPaneTest {
        public EditorPaneTest() {
             JFrame frame = new JFrame("EditorPane Test");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             JEditorPane textComponent = new JEditorPane();
             textComponent.setContentType("text/html");
             String text =
                  "This sentence should wrap and not cause the horiztonal scroll bar to display.<br/>"
                  + "<br/>This<br/>sentence<br/>should<br/>cause<br/>"
                  + "the<br/>vertical<br/>scroll<br/>bar<br/>to<br/>display.<br/>";
             textComponent.setText(text);
             JPanel panel = new JPanel(new BorderLayout());
             //the purpose of putting the JEditorPane in a JPanel
             //is to force it to the bottom with BorderLayout
             panel.add(textComponent, BorderLayout.SOUTH);
             JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
             //this line enables wrapping
             //but disables vertical scrolling
             //(comment it out to switch)
             panel.setPreferredSize(new Dimension(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight()));
             frame.add(scrollPane);
             frame.setSize(100, 200);
             frame.setVisible(true);
        public static void main(String[] args) {
            new EditorPaneTest();
    }As always, any pointers / suggestions / criticisms you can give me are greatly appreciated.
    Thanks again,
    Kevin

    camickr wrote:
    You need create a custom panel that implements the Scrollable interface. The key method to override to give you the behaviour you desire is the getScrollTracksViewportWidth() to return "true". This effectively fixes the width of the JEditorPane to the width of the viewport to wrapping is done as expected.That does handle the wrapping and scrolling, but it breaks the original problem: keeping a JEditorPane at the bottom of a JPanel. Using the ScrollablePanel you posted, the JEditorPane now stays at the top of the Panel instead of growing from the bottom.
    To see what I'm talking about, check out this code (the only difference between this and the previous code is the addition of your suggestion):
    import javax.swing.*;
    import java.awt.*;
    public class EditorPaneTest {
        public EditorPaneTest() {
             JFrame frame = new JFrame("EditorPane Test");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             JEditorPane textComponent = new JEditorPane();
             textComponent.setContentType("text/html");
             String text =
                  "This sentence should wrap and not cause the horiztonal scroll bar to display.<br/>"
                  + "<br/>This<br/>sentence<br/>should<br/>cause<br/>"
                  + "the<br/>vertical<br/>scroll<br/>bar<br/>to<br/>display.<br/>";
             textComponent.setText(text);
             ScrollablePanel panel = new ScrollablePanel();
             panel.setLayout(new BorderLayout());
             //the purpose of putting the JEditorPane in a JPanel
             //is to force it to the bottom with BorderLayout
             panel.add(textComponent, BorderLayout.SOUTH);
             JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
             //this line enables wrapping
             //but disables vertical scrolling
             //(comment it out to switch)
            //panel.setPreferredSize(new Dimension(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight()));
             frame.add(scrollPane);
             frame.setSize(100, 200);
             frame.setVisible(true);
        public static void main(String[] args) {
            new EditorPaneTest();
         public class ScrollablePanel extends JPanel
              implements Scrollable
              public Dimension getPreferredScrollableViewportSize()
                   return getPreferredSize();
              public int getScrollableUnitIncrement(
                   Rectangle visibleRect, int orientation, int direction)
                   return 20;
              public int getScrollableBlockIncrement(
                   Rectangle visibleRect, int orientation, int direction)
                   return 60;
              public boolean getScrollableTracksViewportWidth()
                   return true;
              public boolean getScrollableTracksViewportHeight()
                   return false;
    }Resize the window to make it taller. The text should stay at the bottom of the window, but now it stays at the top. I tried using a BoxLayout on the ScrollablePanel instead, and adding a Box.createGlue( ) before adding the JEditorPane. But that didn't change anything.

  • Please help ! LAYOUT - PROBLEMS

    Hi !
    I have a big problem with using the rigth layoutmanager for my GUI.
    I have a JScrollPane and want to add several JPanels to it. These Panels should have to same width, but different height. So I used a GridBagLayout and it works good.
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(10,2,5,2);
    JPanel inputPanel = new JPanel(layout);
    c.gridwidth = GridBagConstraints.REMAINDER;
    // add several lines to inputPanel
    JPanel line;
    line = new JPanel(new GridLayout(1,2));
    layout.setConstraints(line,c);
    inputPanel.add(line);
    line = new JPanel(new GridLayout(1,2));
    layout.setConstraints(line,c);
    inputPanel.add(line);
    line = new JPanel(new GridLayout(1,2));
    layout.setConstraints(line,c);
    inputPanel.add(line);
    scroll = new JScrollPane(inputPanel);
    But another property should be that the width should be tried on at the current size of the JScollPane. So I used a GridLayout and the width of my JPanel's were good, but of course they all had the same height.
    GridLayout layout = new GridLayout(0,1);
    JPanel inputPanel = new JPanel(layout);
    // add several lines to inputPanel
    JPanel line;
    line = new JPanel(new GridLayout(1,2));
    layout.setConstraints(line,c);
    inputPanel.add(line);
    line = new JPanel(new GridLayout(1,2));
    layout.setConstraints(line,c);
    inputPanel.add(line);
    line = new JPanel(new GridLayout(1,2));
    layout.setConstraints(line,c);
    inputPanel.add(line);
    scroll = new JScrollPane(inputPanel);
    Is there a possibility to have both properties ( different height and conformed width) ?
    Thanks very much for help !

    hi,
    Yes it's possible. keep working with the gridbaglayout.
    There are constraints where you can set X and Y behaviour like : every component must have the same width but own height. I don't know the constraint's name because I work with a visual gridbaglayout editor.
    Xavier

Maybe you are looking for

  • RFC TO HTTP receiver scenario.Adding file name to HTTP receiver

    Hi All, Scenario is ZBAPI  ->XI-> HTTP conncetivity to EXternal Partners . ZBAPI sends the Partner data informtaion to XI .  I need to create a Partnerdata xml in XI and pass it to HTTP Connectivity (Certificates ) to External Partners Connectivity i

  • Warranty claim for B8000-H in Malaysia

    Recently bought a Lenovo B8000-H and happy with it, until i plug in a sim card & found the system shows invalid IMEI in the system & it just wont connect to 3G internet, so i send it for the warranty claim. But after a month of waiting there is still

  • Change label of Primary File

    Hi all, I want to change the default label of "Primary File" field. So we can do it and how to do? Do you have any suggestion for it? Thanks so much!

  • Cover flow for playlists

    While listening to playlists in cover flow mode on the iPhone, it actually shows the album artwork of all the music on the iPhone rather than only those from the playlist. I was expecting to see only the album artwork of the albums/songs in the playl

  • Boot camp, windows xp and macbook pro-install problem

    MacBook Pro 1,1 Mac OS X 10.6.8 Boot Camp Windows XP I installed a SSD and want to put Windows XP back on the computer. I had Windows XP running under Boot Camp on my old HDD. During the Windows XP install when it tells you to press ENTER to install