Problem with JPanel sizing!

Hi,
Just having a bit of difficulty with the sizing of JPanels. For example, if I create a JPanel and add it to a Frame, no matter what I set the size to the JPanel fills the entire Frame. I don't really know whats going on here and I'm just making guesses! If anyone has a good resource on the whole sizing thing or can point out what I'm doing wrong, that would be great. Thanks!
// Constructor
public void ClassName()
        mainWindow = new JFrame();
        mainWindow.setSize(mainWindowWidth, mainWindowHeight);
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel aPanel = new JPanel();
        aPanel.setSize(mainWindowWidth/2,mainWindowHeight/2); );
        aPanel.setBackground(Color.GREEN);
        mainWindow.add(aPanel);
        mainWindow.validate();
}Edited by: LeWalrus on May 18, 2009 5:03 AM

By default, JFrame uses a BorderLayout which gives the center component (your panel in this case) all available height and width.
For absolute positioning you need to use a null layout.
If you want a layout manager that can let your panel fill half the height/width, I think it might be possible with GridBagLayout or more recommended MiGLayout (but that adds a third party jar dependency).
See the [layout tutorial|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html].

Similar Messages

  • Problem with Jpanel repaintingl

    Hi!
    I have a problem with Jpanel.
    First , I add a Jscrollpane to the panel and I don't
    see it.
    Second, I have a paint method in the Jpanel and I do there some painting but when I exe the application I can see the panel painting only when I put the mouse cursor
    on the place where the panel need to be.
    It is very strange.
    Help me.
    Yair.

    Example code??
    Can't tell what's wrong otherwise.
    First , I add a Jscrollpane to the panel and I don't
    see it.Have you added anything to this JScrollPane? Unless you set the scroll bar policies to always on you won't see anything if you haven't added anything to the scrollpane.
    Also, if you're only adding this scrollPane to your JPanel initilise it with
    JPanel whippet = new JPanel(new BorderLayout())
    .. then when you add your scrollPanel to your JPanel do this to make sure its added slap in the in middle of it:
    whippet.add(yourScrollPanel, BorderLayout.CENTER);
    Bit more info please - duuuuuuuuuuuuuuuude (man, "Finding Nemo" was well funny didn't you think.. anyways, that's besides the point.... could just be my 8 year old mental age though.. who knows.)?

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

  • Problem with JPanel.updateUI()

    Hello,
    i have a problem with updateUI(), here's a simple example what's wrong. just compile and run the following piece of code and look what happens after 2 seconds: the left panel will be decrease its width after calling updateUI(), but why? is it a bug of updateUI() or is it my fault?
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JPanel
            private JList m_list;
            private DefaultListModel m_listModel;
            private JPanel m_buttons;
            public static GridBagConstraints creategbc (int x, int y, int w, int h, int wx, int wy, int f)
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = x;
                    gbc.gridy = y;
                    gbc.gridwidth = w;
                    gbc.gridheight = h;
                    gbc.weightx = wx;
                    gbc.weighty = wy;
                    gbc.fill = f;
                    gbc.insets = new Insets(5, 5, 5, 5); // kleinen Rahmen ziehen
                    return gbc;
            public Test ()
                    GridBagLayout gbl = new GridBagLayout();
                    setLayout(gbl);
                    GridBagConstraints gbc;
                    initButtons();
                    gbc = creategbc(0, 0, 1, 1, 20, 100, GridBagConstraints.NONE);
                    gbc.anchor = GridBagConstraints.NORTH;
                    gbl.setConstraints(m_buttons, gbc);
                    add(m_buttons);
                    initList();
                    JScrollPane sp = new JScrollPane(m_list);
                    gbc = creategbc(1, 0, 1, 1, 100, 100, GridBagConstraints.BOTH);
                    gbl.setConstraints(sp, gbc);
                    add(sp);
            public void addItem (String item)
                    m_listModel.addElement(item);
            public void initList ()
                    m_listModel = new DefaultListModel();
                    m_list = new JList(m_listModel);
            public void initButtons ()
                    m_buttons = new JPanel();
                    m_buttons.setLayout(new GridLayout(4, 1, 0, 20));
                    m_buttons.add(new JButton("Neu"));
                    m_buttons.add(new JButton("Bearbeiten"));
                    m_buttons.add(new JButton("L�schen"));
                    m_buttons.add(new JButton("Abfrage"));
            public static void main (String[] args)
                    JFrame f = new JFrame();
                    Test t = new Test();
                    f.setContentPane(t);
                    f.setSize(600, 450);
                    f.setVisible(true);
                    try
                            Thread.sleep(2000);
                    catch (Exception e)
                    t.addItem("Hallo");
                    t.updateUI();

    Hello,
    i have a problem with updateUI(), here's a simple
    example what's wrong. just compile and run the
    following piece of code and look what happens after 2
    seconds: the left panel will be decrease its width
    after calling updateUI(), but why? is it a bug of
    updateUI() or is it my fault?updateUI() its called when the L&F is changed, there is
    rarely a case when you need to call updateUI().
    Why do you call updateUI() if you remove the call to updateUI()
    everything will work OK.
    merry xmas

  • Problem with JPanel and JDesktopPane

    Hi,
    I am having a problem with my app and I wonder if someone can see what I am doing wrong. I have a class that extends JFrame that holds a centered JPanel to draw on. There are also 3-4 other JInternalFrames that are in use.
    From what I have read to use JDesktopPane to organize the JInternalFrames, all you do is add the JInternalFrames to the JDesktopPane and setContentPane to be the JdesktopPane:
            Jpanel panel = new JPanel();
            JDesktopPane dm = new JDesktopPane();
            setContentPane(dm);
            dm.add(panel, BorderLayout.CENTER);
            dm.add(internalFrame1);
            dm.add(internalFrame2);
            dm.add(internalFrame3);But as soon as I add the panel to the JDesktopPane then my JPanel doesnt show up. As I had it before I was adding the panel to the content pane of the Jframe, and adding the JinternalFrames to the layeredPane like this:
            getContentPane().add(panel, BorderLayout.CENTER);
            lp = getLayeredPane();
            lp.add(internalFrame1);
            lp.add(internalFrame2);
            lp.add(internalFrame3);and this worked but the JInternalFrames behaved badly, not getting focus or moving to the top frame when clicked, which I guess is what JDesktopPane is supposed to do. But how do I get my original JPanel in my JFrame to show up when added to the JDesktopPanel?
    Am I missing something here?
    Thanks,
    Paul

    Thanks for your response. I will try that when I get home, although I will be surprised if that works because I am already using setPreferredSize() . It seemed to me that once a Jframe's content pane gets assigned to a JDesktopPane, then the JPanel no longer has anywhere to draw itself, as according to the Sun documentation, you can only add a JInternalFrame to a JDesktopPane.
    So I am thinking its not possible to have a JPanel as the content pane of a JFrame while having a JDesktopPane containing my JInternalFrames. Is this indeed the case?
    Thanks,
    Paul

  • Weird problem with jpanel vs jframe

    I'm using jmathplot.jar from JMathTools which lets me do 3d plotting. I used a JFrame to get some code to work and it worked fine. Here's the code that worked for a JFrame:
    public class View extends JFrame
        private Model myModel;
        private Plot3DPanel myPanel;
        // ... Components
        public View(Model m)
            myModel = m; 
            // ... Initialize components
            myPanel = new Plot3DPanel("SOUTH");
            myPanel.addGridPlot("Test",myModel.getXRange(),myModel.getYRange(),myModel.getZValues());
            setSize(600, 600);
            setContentPane(myPanel);
            setVisible(true);
    }Here's the class that starts everything:
    public class TestApplet extends JApplet
        public void init()
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        createGUI();
            catch (Exception e)
                e.printStackTrace();
        private void createGUI()
            System.out.println("Creating GUI");
            Model model = new Model();
            View view = new View(model);
    }And here's the Model:
    public class Model
        private double[] myXRange,myYRange;
        private double[][] myZValues;
        public Model()
            createDataSet();
        public double[] getXRange()
            return myXRange;
        public double[] getYRange()
            return myYRange;
        public double[][] getZValues()
            return myZValues;
        private void createDataSet()
            myXRange = new double[10];
            myYRange = new double[10];
            myZValues = new double[10][10];
            for(double i=0;i<10;i++)
                for(double j=0;j<10;j++)
                    double x = i/10;
                    double y = j/10;
                    myXRange[(int) i] = x;
                    myYRange[(int) j] = y;
                    myZValues[(int) i][(int) j]= Math.cos(x*Math.PI)*Math.sin(y*Math.PI);
    }However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and changed:
    setSize(600, 600);
    setContentPane(myPanel);
    setVisible(true);to
    this.add(myPanel);and added these two lines to createGUI():
            view.setOpaque(true);
            setContentPane(view);When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet. I don't know if it's a problem with the library or if I'm doing something wrong in my applet.

    However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and (...)What do you mean? View extends JApplet? I thought View was meant to extend JPanel in the end...
    When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet.Or, the panel has its preferred size, and this latter is too small. Actually the panel has the size its container's layout manager awards it (taking or not the panel's preferred, minimum, and maximum sizes into account). See the tutorial on [layout managers|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html] .
    In particular, this line adds the myPanel to a parent panel (presumably, it is in class View which extends JPanel, whose default layout is FlowLayout):
    this.add(myPanel);
    I don't know if it's a problem with the library or if I'm doing something wrong in my applet.Likely not (presumably the library interfers only in how it computes the Plot3DPanel's preferred size). There's an easy way to tell: try to layout correctly a custom JPanel of yours, containing only e.g. a button with an icon. Once you understand the basics of layout management, revisit the example using ther 3rd-party library.
    N.B.: there are a lot of "likely" and "presumably" in my reply: in order to avoid hardly-educated guesses especially on what is or isn't in your actual code, you'd better provide an SSCCE , which means reproducing the problem without the 3rd party library.

  • Problem with JPanel, JMenuBar

    Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
    I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
    When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
    This is the whole JPanel class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanneauDe extends JPanel
      private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
                                                   "De4.GIF", "De5.GIF", "De6.GIF" };
      private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
      private static final int SIDE = 100;
      private De unDe;
      private ImageIcon imageDe;
      private boolean aFirstTime;
      private int aX, aY; 
      public PanneauDe()
        unDe = new De();
        aX = aY = 0;
        aFirstTime = true;  
        addMouseListener(new EcouteurSouris());   
      public String getStats()
        String statsMsg = "";
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
        return statsMsg;
      public String getTotal()
        int total = 0;
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          total += TAB_FREQUENCE[iPos];
        return "Le d� a �t� lanc� " + total + " fois";
      public void throwDice()
        unDe.throwAgain();
        TAB_FREQUENCE[unDe.getFace() - 1] ++;   
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          repaint();
    }When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
    I tried ...
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        //g.drawImage (imageDe.getImage(), aX, aY, null);
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          Graphics g = getGraphics();
          g.drawImage (imageDe.getImage(), aX, aY, null);
          g.dispose();
        }Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
    I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
    If you see some weird words in the code, it's because i'm canadian-frenchy! :)
    Full program is here

    The real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
    However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null.

  • Problem with JPanel after rotation

    Hi,
    I am developing a graphics editor like mspaint. I have JPanel as my drawing canvas. now the problem is when I rotate the canvas, co-ordinates on the canvas are also getting rotate with it. for example if top-left corner is (0,0) initially then after rotating it 90 degree top-right corner becomes (0,0) and same for all the points on the canvas.
    the code i m using for rotation is
    contentPanel = new JPanel(){
    @Override
    protected void paintComponent(Graphics g) {                       
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect=g2.getClipBounds();
    if(rotation!=0){
    double angle = rotation * Math.PI/2;
    g2.rotate(angle,getWidth()/2,getHeight()/2);
    rect=g2.getClipBounds();
    setPreferredSize(new Dimension(rect.width,rect.height));
    super.paintComponent(g);
    revalidate();
    };

    Whats your question?
    If you rotate it, of course the points will rotate, they have to.

  • Problem with JPanel on Mac

    Hi,
    I have a Jpanel with BorderLayout which has two components. First one is a JScrollpane which sits at CENTER and another is JEditorPane which sits at south. JScrollPane itself is over a JEditorPane ..... PROBLEM is I can't see the component sitting at SOUTH, any focus???

    Hi,
    I haven't seen this before.  Is it possible to get some sample code that illustrates the problem?  Feel free to email me at [email protected] (please remove any attachment extension) and I'll take a look.
    Moving discussion to the Problems & Bugs forum.
    Thanks,
    Chris

  • Problem with JPanel's mouse listener!

    I am developing a Windows Explorer-like program. I have an JPanel and added JLabels to that panel to reprensent the folders. I think, I kind of have to add mouse listener to JPanel to interact with mouse clicks, gaining and losing focus of JLabels etc. instead of adding every JLabel to mouse listener. So when I added to JPanel a mouse listener, it didn't work how I had expected. When I clicked on labels mouse click events didn't fire but when I clicked somewhere else in the panel it did fire. Is this a bug or am I using mouse listener incorrectly??
    Thank for advance :)
    Here is my JPanel's mouse listener ->
    public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    System.out.println("Mouse Clicked");
    Component c = this.getComponentAt(x,y);
    if(c instanceof JLabel){
    JLabel label = (JLabel) c;
    label.setBackground(Color.LIGHT_GRAY);
    }

    My main problem is as in windows explorer (if CTRL or SHIFT not pressed) there is only one selected folder (in my case JLabel) and transfering "selection" to one label to another might need lots of extra code.. So I thought using JPanel's mouse listener can overcome this handling problem. But if you are saying, this is the way it has to be done, then so be it :D :D

  • Problem with JPanel, CardLayout and Applets

    Hello All,
    I have a JPanel with a CardLayout as layout manager. In this JPanel i'm gonna show a few applets.
    My problem is when i'm showing an applet for second time and try to click a button it does nothing... I think the action method is not called again...
    How can i solve this?
    Thanks in advance ; )

    Here is a few parts of my code...
    public class InitAll{
    JPanel cards = new JPanel( new CardLayout() );
    JComboBox selector = new JComboBox();
    Object objetosV[][] ={
         {"Ventas",venta.class},
         {"Compras",compras.class}, //These are applets.
         {"Traspasos",traspasos.class},
         {"Facturas",factura.class},
    public void load( Applet app ){
    cards.removeAll();
    selector.removeAll();
    cards.add( "Entrada", app );
    selector.addItem( "Entrada" );
    for ( int i=0; i < objetosV.length; i++ ){
         selector.addItem( (String)objetosV[0] );
         Applet temp=createPanel( ( Class ) objetosV[i][1] );
         temp.setSize( 800,750 );
         cards.add( ( String ) objetosV[i][0], temp );
    public void itemStateChanged(ItemEvent e) {
    ((CardLayout)cards.getLayout()).show(cards, selector.getSelectedItem().toString() );
    Applet tmp = (Applet)cards.getComponent(selector.getSelectedIndex() );
    tmp.start();
    After i show for second time an Applet and select a button from it. the button does nothing...
    Thanks...

  • Problem with jpanel and revalidate()

    i have made a calendar. on click on jlabel you can switch month/year and there is the problem. for example when i switch from february to march and back again, then the panel don�t update. but why?
    i hope you understand what i mean.(I am german and can�t englisch)
    here is the code(i have mixed german in english in the code, i hope you understand even so.)
    package organizer.gui;
    import organizer.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Kalender extends JPanel {
    private Calendar calendar;
    private JPanel days;
    private JLabel monthLabel;
    private SimpleDateFormat monthFormat = new SimpleDateFormat("dd MMM yyyy");
    private TerminManager manger;
    public Kalender(TerminManager manager) {
       super();
       this.manger=manager;
       this.calendar=Calendar.getInstance();
       this.initializeJPanel();
       this.updatePanel();
    protected void updatePanel() {
       monthLabel.setText(monthFormat.format(calendar.getTime()));
       if(days!=null) {
         days.removeAll();
       }else {
         days = new JPanel(new GridLayout(0, 7));
       days.setOpaque(true);
       for (int i = 1; i <=7; i++) {
         int dayInt = ( (i + 1) == 8) ? 1 : i + 1;
         JLabel label = new JLabel();
         label.setHorizontalAlignment(JLabel.CENTER);
         if (dayInt == Calendar.SUNDAY) {
           label.setText("Son");
         else if (dayInt == Calendar.MONDAY) {
           label.setText("Mon");
         else if (dayInt == Calendar.TUESDAY) {
           label.setText("Die");
         else if (dayInt == Calendar.WEDNESDAY) {
           label.setText("Mit");
         else if (dayInt == Calendar.THURSDAY) {
           label.setText("Don");
         else if (dayInt == Calendar.FRIDAY) {
           label.setText("Fre");
         else if (dayInt == Calendar.SATURDAY) {
           label.setText("Sam");
         days.add(label);
       Calendar setupCalendar = (Calendar) calendar.clone();
       setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
       int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
       for (int i = 1; i < (firstday - 1); i++) {
         days.add(new JLabel(""));
       for (int i = 1; i <=setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
         int day = setupCalendar.get(Calendar.DAY_OF_MONTH);
         final Date d = setupCalendar.getTime();
         final JLabel label = new JLabel(String.valueOf(day));
         label.setOpaque(true);
         if(this.manger.isTerminAtDay(d)) {
           String s="<html><center>" + day + "<br>";
           if(this.manger.isBirthdayAtDay(d)) {
             s+="Geburtstag<br>";
           if(this.manger.isOtherTerminAtDay(d)) {
             s+="Termin";
           label.setText(s);
           label.addMouseListener(new MouseListener() {
              * mouseClicked
              * @param e MouseEvent
             public void mouseClicked(MouseEvent e) {
               Termin[] t = Kalender.this.manger.getTermineAtDay(d);
               if (t.length == 1) {
                 new TerminDialog(null, t[0]);
               else {
                 new TerminAuswahlDialog(null, t, d);
              * mouseEntered
              * @param e MouseEvent
             public void mouseEntered(MouseEvent e) {
              * mouseExited
              * @param e MouseEvent
             public void mouseExited(MouseEvent e) {
              * mousePressed
              * @param e MouseEvent
             public void mousePressed(MouseEvent e) {
              * mouseReleased
              * @param e MouseEvent
             public void mouseReleased(MouseEvent e) {
         final Color background=label.getBackground();
         final Color foreground=label.getForeground();
         label.setHorizontalAlignment(JLabel.CENTER);
         label.addMouseListener(new MouseAdapter() {
           public void mouseEntered(MouseEvent e) {
             label.setBackground(Color.BLUE);
             label.setForeground(Color.RED);
           public void mouseExited(MouseEvent e) {
             label.setBackground(background);
             label.setForeground(foreground);
         days.add(label);
         setupCalendar.roll(Calendar.DAY_OF_MONTH,true);
       this.add(days, BorderLayout.CENTER);
       this.revalidate();
    private JLabel createUpdateButton(final int field,final int amount) {
       final JLabel label = new JLabel();
       final Border selectedBorder = new EtchedBorder();
       final Border unselectedBorder = new EmptyBorder(selectedBorder
           .getBorderInsets(new JLabel()));
       label.setBorder(unselectedBorder);
       label.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e) {
           calendar.add(field, amount);
           Kalender.this.updatePanel();
         public void mouseEntered(MouseEvent e) {
           label.setBorder(selectedBorder);
         public void mouseExited(MouseEvent e) {
           label.setBorder(unselectedBorder);
       return label;
    private void initializeJPanel() {
       JPanel header = new JPanel();
       JLabel label;
       label = this.createUpdateButton(Calendar.YEAR, -1);
       label.setText("<<");
       header.add(label);
       label = this.createUpdateButton(Calendar.MONTH, -1);
       label.setText("<");
       header.add(label);
       monthLabel=new JLabel("");
       header.add(monthLabel);
       label = this.createUpdateButton(Calendar.MONTH, 1);
       label.setText(">");
       header.add(label);
       label = this.createUpdateButton(Calendar.YEAR, 1);
       label.setText(">>");
       header.add(label);
       this.setLayout(new BorderLayout());
       this.add(header, BorderLayout.NORTH);
    }

    I got you code to compile and run and made a single change to get it to work; adding a call to repaint at the end of the updatePanel method.
            this.add(days, BorderLayout.CENTER);
            this.revalidate();
            repaint();
        }Whenever you change the size of a containers components or add/remove components you must ask the container to run through its component hierarchy and check the size requirements of all its children and lay them out again, ie, do a new layout. The JComponent method for this isrevalidate. If you are working in the AWT you must use the Component/(overridden in)Container method validate, sometimes preceded by a call to the invalidate method. Some people prefer the validate method over revalidate. These are methods used to update guis by asking for a renewed layout. For economy you can call one (sometimes with invalidate, but rarely) of these methods on the smallest component/container that includes all the containers needing the renewed layout, ie, keep the action as localized as possible.
    When the rendering of components has changed, things like colors, borders and text, we need to ask the components to repaint themselves. The easy way to do this is to call repaint on the gui. For economy you can call repaint on the smallest component that contains all the components needing repainting. Some classes like those in the JTextComponent group have their own internal repainting calls so they will repaint themselves when changes are made.
    In making guis, especially elaborate ones, it seems to take some playful experimentation to find out what is needed to get what you want. Sometimes it is a call to revalidate, sometimes a call to repaint, sometimes both. You just have to experiment.

  • Problem with jpanel and image

    i have a jinternalframe with gridbaglayout which has several jpanels. one of the jpanels has to display an image.
    i have searched through the forum and i have made a method to draw the image,
    but the problem is that when i added to the jpanel the last (jpanel) gets much bigger and as a result to break down the layout.
    any help is appreciated!

    i have searched through the forum and i have made a method to draw the image,Just add the image to a JLabel.
    when i added to the jpanel the last (jpanel) gets much bigger[url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers

  • Transparency problems with JPanel

    I wrote a color chooser application, where I can change the RGB values and
    the alpha value by a JSlider. If a slider is changed the background
    color of an additional JPanel is set. If alpha is lesser 1.0 (255), than
    a slider is shown in the additional Panel (jPanelColor).
    Following my source code, only with the red and alpha slider.
    Thanks in advance for helping
    Markus
    import java.awt.Color;
    public class ColorView extends javax.swing.JFrame {
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanelAlpha;
    private javax.swing.JPanel jPanelColor;
    private javax.swing.JPanel jPanelLabel;
    private javax.swing.JPanel jPanelRed;
    private javax.swing.JSlider jSliderAlpha;
    private javax.swing.JSlider jSliderRed;
    private javax.swing.JTextField jTextFieldAlpha;
    private javax.swing.JTextField jTextFieldRed;
    private int red;
    private int alpha;
    public ColorView() {
    red = 0;
    alpha = 0;
    initComponents();
    updateView();
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
    jPanelColor = new javax.swing.JPanel();
    jPanelLabel = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jPanelRed = new javax.swing.JPanel();
    jSliderRed = new javax.swing.JSlider();
    jTextFieldRed = new javax.swing.JTextField();
    jPanelAlpha = new javax.swing.JPanel();
    jSliderAlpha = new javax.swing.JSlider();
    jTextFieldAlpha = new javax.swing.JTextField();
    getContentPane().setLayout(new java.awt.GridBagLayout());
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jPanelColor.setLayout(new java.awt.GridBagLayout());
    jPanelColor.setPreferredSize(new java.awt.Dimension(100, 100));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    getContentPane().add(jPanelColor, gridBagConstraints);
    jPanelLabel.setLayout(new java.awt.GridBagLayout());
    jLabel1.setFont(new java.awt.Font("MS Sans Serif", 1, 24));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("My Label");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    jPanelLabel.add(jLabel1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    getContentPane().add(jPanelLabel, gridBagConstraints);
    jPanelRed.setLayout(new java.awt.GridBagLayout());
    jPanelRed.setBorder(new javax.swing.border.TitledBorder("Red"));
    jSliderRed.setMaximum(255);
    jSliderRed.setValue(red);
    jSliderRed.addChangeListener(new javax.swing.event.ChangeListener() {
    public void stateChanged(javax.swing.event.ChangeEvent evt) {
    redStateChanged(evt);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 1.0;
    jPanelRed.add(jSliderRed, gridBagConstraints);
    jTextFieldRed.setColumns(3);
    jTextFieldRed.setEditable(false);
    jTextFieldRed.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    jTextFieldRed.setText(Integer.toString( red));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
    jPanelRed.add(jTextFieldRed, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 1.0;
    getContentPane().add(jPanelRed, gridBagConstraints);
    jPanelAlpha.setLayout(new java.awt.GridBagLayout());
    jPanelAlpha.setBorder(new javax.swing.border.TitledBorder("Alpha"));
    jSliderAlpha.setMaximum(255);
    jSliderAlpha.setValue(alpha);
    jSliderAlpha.addChangeListener(new javax.swing.event.ChangeListener() {
    public void stateChanged(javax.swing.event.ChangeEvent evt) {
    alphaStateChanged(evt);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 1.0;
    jPanelAlpha.add(jSliderAlpha, gridBagConstraints);
    jTextFieldAlpha.setColumns(3);
    jTextFieldAlpha.setEditable(false);
    jTextFieldAlpha.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    jTextFieldAlpha.setText(Integer.toString( alpha));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
    jPanelAlpha.add(jTextFieldAlpha, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 1.0;
    getContentPane().add(jPanelAlpha, gridBagConstraints);
    pack();
    private void alphaStateChanged(javax.swing.event.ChangeEvent evt) {
    alpha = jSliderAlpha.getValue();
    jTextFieldAlpha.setText( Integer.toString( alpha));
    updateView();
    private void redStateChanged(javax.swing.event.ChangeEvent evt) {
    red = jSliderRed.getValue();
    jTextFieldRed.setText( Integer.toString( red));
    updateView();
    private void updateView() {
    jPanelColor.setBackground( new Color( red, 0, 0, alpha));
    // repaint();
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new ColorView().show();
    }

    My problem is, the slider must not visible in the additional
    panel (called jPanelColor). I do not add the slider into the jPanelColor.
    This behavior exists only if the transparancy is lesser than 1.0
    An additional info, I use java version 1.4.2_04

  • Problems with Export: Sizing.

    OK, here's a weird one. I had to turn a bunch of RAW files into 16bit Tiffs. I did the usual select>export, etc. I chose to resize such that the long edge was 12 inches. About 3 of the files came out that way and the rest were exported to native size (long edge about 18 inches). I did this several times always with the same result.
    Anybody else having this sort of problem?
    -Hopper Stone

    10 inches as the long edge (since Adobe gives inches as a choice of parameter, I am using that) at 240 ppi.
    Some files are coming out at 3600x2400 pixels and some are coming out at 1600x2400 pixels.
    If you really set it to long edge that is then a bug as your files should all come out with 2400 pixels on the long side. I've never seen Lightroom do this wrong however, and I would really check the export dialog carefully if I were you. Make sure you do not select "do not enlarge" and that you don't have any post process actions or plugins such as LR/mogrify enabled. The export panel should look like this:
    If you still get wrongly sized exports, you probably want to report it as a bug.

Maybe you are looking for

  • A Playlist folder full of a lot of important playlists is no longer visible in iTunes

    To complicate matters, a few months ago I moved my entire iTunes library to an external hard drive, and that is not backed up by Time Machine.  But, the folder was there after I moved all the files.  It just recently seemed to disappear.  Is there a

  • Can you use iCloud with garageband on a mac?

    i know you can use it on a phone and ipad.but i cant figure out how to do it with mac.(i want to upload songs on there to access from other devices)

  • Payment Run not posting to the Vendor

    I have created a payment proposal which shows one payment processed. But for some reason it is not being posted to the vendor account. Am I missing some step? After creating the payment proposal, I had scheduled the payment run and run it in SM37.

  • Printer won't work - CUPS failed

    I am trying to get my new Canon MF4890DW printer to work with Mac OS X v10.7.5 Lion to no avail. When trying to print any document (web page, or a simple TextEditor file), the printer queue pops up and it errors out with "/Library/Printers/Canon/CUPS

  • Officejet 7110 wont print

    Trying to print from PC to the Hp Officejet 7110 all-in-one, Printer says printing but its not??? Also while trying to print from word it says scanner failure, but im not scanning.  Can't print from internet either. Tried rebooting both but it didn'