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

Similar Messages

  • 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 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 setContentPane() in JFrame class

    I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
    I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.

    I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
    Here is the method I use to switch screens in my app:
    public static void changeScreen (JPanel panel){
              try{
                   appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
                   appFrame.setContentPane(panel);
                   appFrame.setSize(appFrame.getContentPane().getPreferredSize());     
                   appFrame.getContentPane().setBackground(backColour);
                   for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
                        appFrame.getContentPane().getComponents().setForeground(textColour);
                   //System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
                   appFrame.validate();
              catch (Exception e){
                   //System.out.println("change");
                   e.printStackTrace();
    And it is called like this:
    changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it.

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

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Thread problem with displaying to JFrame :(

    Hi everyone I have a problem, I have a JFrame which I use to submit a transaction. I am submitting a multiple number but would like to do so sequentially. SO for now i am starting one transaction thread, waiting for it to finish then starting the next etc.
    My problem is that once a transaction is finished it will not print the msg to areaOutput untill all transactions have finished processing. But the call to system.out will print at the correct time.
    I am sure i have missed a point just don't know what.
    Thread m = new Thread(transactionN);
    m.start();
    try{
    m.join();
    areaOutput.append("Finshed thread #: " + threadNum + newline);
    System.out.println("Thread done");
    }catch(InterruptedException ie){
    System.out.println("interrupted.");
    threadNum ++;Thanks for any advice!!
    luv M

    Yes, like the previous poster said. If you are running your example code from the event thread (as response to some gui-interaction like pressing a button), you are blocking the event thread. The event thread is also the same thread that paints the screen. So nothing is painted until that piece of code is finished.

  • 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

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

  • Problem with backspace on JFrame

    Hello,
    I have a problem on a JFrame. Indeed, I add a keyListener to the frame, but the "Bakcspace" don't work. There is anything when a I press on Backspace (with KeyTyped, KeyReleased and KeyPressed). All other keys are working.
    Thanks.

    the solution of the problem is :
    Version note: This page reflects the focus API introduced in released 1.4. As of that release, the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you need to prevent the focus traversal keys from being consumed, you can call
    component.setFocusTraversalKeysEnabled(false)
    on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you can use a KeyEventDispatcher to pre-listen to all key events. The focus page (in the Creating a GUI with JFC/Swing trail) has detailed information on the focus subsystem.

  • Problem with jpanel size

    Hi I want to add a view port to a JPanel
    the main problem is that the Jpanel change size as the frame.
    how can i make it independent from the frame so having it; own w, h
    thanks
    package help;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private static JButton drawCircle, drawRectangle, drawSquare, drawStar, start, clear,quit,back, screenshoot;
    static final int FPS_MIN = 0;
    static final int FPS_MAX = 150;
    static final int FPS_INIT = 0;
    static int fps;
    double x1,x2;
    double y1,y2;
    int dr =1;
    int dy= 1;
    int Selection=0;
    boolean click=true; //check if start has been clicked
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;     //screen higth
    protected static int count;
    int R,G,B;  //color
    Cursor c;                    //cursor object
    private static ShapePanel bpnl;
    public MyFrame()
            R=G=B=0;
            int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
            int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            frame.setTitle("Game");
            //panel to hold buttons
            JPanel upPanel = new JPanel();
            upPanel.setLayout(new FlowLayout());
            upPanel.setSize(width, height/5);
            //panel to hold SLIDERS
            JPanel leftPanel = new JPanel();
            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
            leftPanel.setSize(50, height);
            //initialize buttons and add to the upPanel
            drawCircle=new JButton("Draw Circle");
            upPanel.add(drawCircle);
            drawStar=new JButton("Draw Star");
            upPanel.add(drawStar);
            drawRectangle=new JButton("Draw Rectangle");
            upPanel.add(drawRectangle);
            drawSquare=new JButton("Draw Square");
            upPanel.add(drawSquare);
            start=new JButton("Start");
            start.setBackground(Color.GREEN);
            //upPanel.add(start);
            clear=new JButton("Clear");
            upPanel.add(clear);
            back=new JButton("Back");
            upPanel.add(back);
            quit=new JButton("Quit");
            quit.setBackground(Color.red);
            upPanel.add(quit);  
            screenshoot=new JButton("ScreenShoot");
            c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
         this.setCursor (c);
            //new object spanel to hold TIMER
            JPanel spanel=new JPanel();
                spanel.setLayout(new GridLayout());
                //slider dimension construction
                JSlider sDimension = new JSlider(JSlider.HORIZONTAL,FPS_MIN, FPS_MAX, FPS_INIT);
                sDimension.setMajorTickSpacing(30);
                sDimension.setMinorTickSpacing(3);
                sDimension.setPaintTicks(true);
                sDimension.setPaintLabels(true);
                Font font = new Font("Serif", Font.ITALIC, 15);
                sDimension.setFont(font);
                sDimension.setBorder(BorderFactory.createTitledBorder("Shape Dimension"));
                //slider speed construction
                int FPS_MIN_s = 0;
                int FPS_MAX_s = 60;
                int FPS_INIT_s = 0;    //initial frames per second
                JSlider sSpeed = new JSlider(JSlider.HORIZONTAL,FPS_MIN_s, FPS_MAX_s, FPS_INIT_s);
                sSpeed.setBorder(BorderFactory.createTitledBorder("Shape Speed"));
             ////////////////////////// // slider colors////////////////////////////////////////////////////
                int FPS_MIN_C = 0;
                int FPS_MAX_C = 250;
                int FPS_INIT_C = 0;  
                JSlider sliderR= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderR.setBorder(BorderFactory.createTitledBorder("Red Channel"));
                JSlider sliderG= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderG.setMajorTickSpacing(50);
                sliderG.setMinorTickSpacing(25);
                sliderG.setPaintTicks(true);
                sliderG.setPaintLabels(true);
                sliderG.setFont(font);
                sliderG.setBorder(BorderFactory.createTitledBorder("Green Channel"));
                JSlider sliderB= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderB.setBorder(BorderFactory.createTitledBorder("Blue Channel"));
              //     spanel.add(sSpeed,BorderLayout.EAST);
                  frame.add(upPanel,BorderLayout.NORTH);
                  frame.add(leftPanel,BorderLayout.WEST);
                  bpnl = new ShapePanel(3000,3000);
                        System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
                        bpnl.setFocusable(true);
                  upPanel.setBackground(Color.DARK_GRAY);
                  upPanel.setBorder(BorderFactory.createLineBorder(Color.white));
            frame.add(spanel,BorderLayout.SOUTH);       
            frame.add(bpnl, BorderLayout.CENTER);
            frame.setSize(width, height);
            frame.setVisible(true);               
               leftPanel.add(sliderR);
               leftPanel.add(sliderB);
               leftPanel.add(sliderG);
               leftPanel.add(sDimension,BorderLayout.WEST); 
                 System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private javax.swing.Timer animationTmr;
         private float heigth;
         private float width;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
        thanks

    sorry i hope this is better
    package help;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    int dr =1;
    int dy= 1;
    int Selection=0;
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;     //screen higth
    private static ShapePanel bpnl;
    public MyFrame()
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            bpnl = new ShapePanel(3000,3000);
            System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
            bpnl.setFocusable(true);
              frame.add(bpnl);
            frame.setSize(width, height);
               pack();
            frame.setVisible(true);               
    System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
       

  • Problem with JPanel inside JScrollPane

    I want to make a simple graphic editor (like MS-Paint) with Java.
    I create the frame using JFrame, and use many Swing component. But I found
    some difficult when I tried to create the drawing area (the area where user
    performs drawing). I use JPanel as drawing area and I put it in JScrollPane.
    I use JScrollPane in case if user want to create a big drawing area.
    What I want to do with drawing area is, to put it in JScrollPane with size smaller than JScrollPane but I can't get it because the size of drawing area (JPanel) is always be the same as JScrollPane size. In MS-Paint you can see that the canvas (drawing area) size is able to be resize. And the canvas default color is white, and the Scroll Box around it has darkgray color. How can I make it like that (MS-Paint)? Please help. Thanks...
    Irfin

    I haven't actually tested this, but I think it should work...
    Add a JPanel to the scrollpane setting it's background to grey (i think the dark grey in MSPaint is something easy like 128,128,128). Set the layout on that panel to null, then add a second panel to that panel, at freeze it's size (ie. setMaximumSize). Doing it this way will allow you to set like a (10,10) position or something like that, giving the second panel a position away from the edge of the scrollpane.
    Seeing as you will be using mouse listeners anyways, you might even be able to allow for the second panel to be resized by checking the mouse position to see if the mouse is over the edge of the panel. I won't go into detail, that'll ruin the fun for you.
    Good luck, hope this helps.
    Grant.

Maybe you are looking for

  • Error reading zip file in Java 6

    We have a bespoke installer program that fails, intermittently, in Java 6 on Windows. After installing some files, it then fails with a stack trace like this: java.util.zip.ZipException: error reading zip file      at java.util.zip.ZipFile.read(Nativ

  • DEVICES NO LONGER SHOWN IN ITUNES

    I installed the lates version of ITunes.  Now I no longer have devices shown and my IPOD Nano will no longer sync.  How do I correct this problem? 

  • Gaps in data

    Hi.  I am trying to save a lot of data at a high frequency: 36 Analog Channels, 400 samples @ 4kHz per channel, each iteration. I am saving the data inside my loop and this seems to cause a 20ms gap after each pass through.  Is there a way to use the

  • Creative Suite 4

    For a while Illustrator wouldn't open without an error message. Then after a while I couldn't click open a pdf file. I had to right click "open with". So, I tried reinstalling the whole package. It errored with message 1603. The installation of Adobe

  • VENDOR MASTER-ACCOUNTING INFORMATION

    Hi gurus,            Any standard report to see the accounting information in vendor master ? Regards, T.Murugu