Jpanel woes...

Hi!
Im trying to make a way to highlight a button on my application... What I would like to do, is to have a jpanel behind the button, extending beyond the edges of the button just a bit, and have the color of the jpanel vary a bit.
So it would wind up bringing the users attention to the button, when I want it there.
I tried to extend JPanel to do this, and override the paint method with new background colors, but the main problem is that it makes the rest of my application run like shit. Buttons are not displayed until my mouse runs over them, etc.
So what should I do to get this to work? Code below...
public class JPanelColorVary extends JPanel {
     static final long serialVersionUID = 18971234651L;
     private static final int fiRed = 0;
     private static final int fiGreen = 107;
     private static int m_iBlue = 136;
      * paint - modified to vary the background color
      * with a blue tint.
     public void paint(Graphics g) {
          super.paint(g);
          if (m_iBlue < 255){
               m_iBlue++;
          }else{
               m_iBlue = 150;
          this.setBackground(new Color(fiRed, fiGreen, m_iBlue));
}Thanks!

I think a much similiar way would be to add a border to the button.
See BorderFactory in the API.

Similar Messages

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

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

  • How to give Common Background color for all JPanels in My Swing application

    Hi All,
    I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
    Now is there any way to set a common background color for the all the JPanel's available in the application??
    I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
    Also let me know if SAF has some inbuilt method or way to do this.
    Your inputs are valuable.
    Thanks in Advance,
    Nishanth.C

    It is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
    I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
    NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
    To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
    Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
    If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
    I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
    One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
    Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
    Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
    Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
    Edited by: jduprez on Feb 15, 2010 10:07 AM

  • 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

  • Continual Mac woes (no question, just a rant)

    It's Tuesday, and I am having terrible problems with my Mac. But then, why should Tuesday be different from any other day of the week.
    Here is a typical day for me. The computer appears to be working OK. I need to watch a DVD for my work. I turn on DVD player, and put one in. The machine can't read the disc. It clicks and whirls, but the icon does not show up on the desktop. Meanwhile, so distressed is the machine that it freaks out. What was up until now was a fluidly operating machine suddenly reverts back to its old ways (i.e., its ways of two days ago). The hold ups and spinning pinwheels begin to eat of hours of my work day. (Remember the old days when computers made life easier?) The machine becomes sticky, gummy. Oh, I can move the curser and it seems to work for a second but then gets stuck in the dock, which explodes in icons and then freezes for five minutes. Yes. Five minutes.
    Would love to use Force Quit, but the cursor is spinning, and nothing is responding. Funny about that old Mac. You can't force quit Force Quit. I guess I need to leave it open all the time.
    Of course, FQ usually works on Safari. I have never just "quit" Safari. It always requires Force Quit, otherwise I can't turn off my computer. It stalls shut down.
    Now I have a DVD trapped in there and can't get it out. [But I just got an answer from another posting.]
    In the old macs, there used to be a pin hole you could stick a needle into ... can't find one on my flatpanel iMac.
    I bought my Apple flat panel iMac in August of 2002. Yes, I know that that is a long time to have a computer, but I am not rich nor attached to a corporation that can splurge on computers. The first weekend I had the machine, I had three kernal panics.
    Among the other problems I have documented are the following: the dock hiding itself unbidden and other features checking and unchecking themselves (Aug 2002); bus errors connected with OS 9 (Sept); some problems that inspired the tech person (Eric)) to talk me through deleting my user i.d., resulting in the loss of two months worth of e-mail (Thursday, 12 September); Preview problems (September); a bizarre box with an unmovable and undeletable red stop sign in it that no tech person or other Mac user I know had ever hear of (Monday 30 September); printing problems; computer won't shut down, numerous disconnection errors, which turned out to be caused by an OS X update (beginning December, 2002, or later); Kernel panics (Feb); computer won't shut down (March); Faxstexx problems, program won't allow me to set it up, finally just deleted the software (April); keys like "V" freeze and repeat endlessly (May 21); DVD Player freezes (May); Safari and Mail begin quitting unexpectedly (May); cursor begins to blink and fade out, plus odd sounds come out of the speakers, a constant error beeping (Sept 9); DVD Player problems (Oct 4).
    I called AppleCare while I had it about once a week (the total between August 2002 and the time it ran out was about 155 calls). Naturally, some of these calls are motivated by user error. On the other hand, many of the issues I have called about were unprecedented as far as the Tech person was concerned, such as the blinking mouse, the red stop sign, and the DVD Player woes.
    Things improved with Panther, but in Tiger many of the same old issues have returned.
    I have been having so many problems with my Mac that I once wrote a letter to the company asking when do I qualify for a new replacement machine. I never received an answer, but I felt better for about a day. Then I turned on my Mac again.

    The spinning ball of death as we used to call it is often caused by a lack of RAM, it is hard to be sure as I am not working on your machine, but sometimes things can be improved with additional RAM, it makes it seem like a whole new computer.
    A lot of your problems sound like stuff that can be fixed easily enough, and although frustrating things happen here and there with updates. It sounds like you are in fairly good spirits with it all, I would suggest just researching a bit more into maintenance you can do to help maintain the computer and educate yourself a bit more (sounds like you already have learned quite a bit along the way) and you will find a lot of these issues take you a few seconds to rid yourself of. I would start by making sure you are repairing permissions regularly and running the most up to date software. If a lot of problems persist, try creating a second user that is a "test" user to see if the problem is replicated on that user (don't delete your other one, but if you do find the problem not on the other user, you might have a corrupt user, however you don't have to lose all your emails there are plenty of ways to back it up and import it in, or even just bring the entire Mail folder from your library over to the new user). Another thing you can do if you find a lot of system problems is archive and install the OS, it takes a bit of time, but doing it overnight shouldn't be an issue, and you won't lose any of your stuff.

  • If statement doesn't work in JPanel

    Hi everybody.
    I'd like somebody tell me the reason why the "if" statement doesn't work in a Jpanel but works in a Japplet. I'm including the fragments of code that are relevant to the question.
    Thanks in advance.
    public class Applet_INVEN extends JApplet {
    jTabbedPane jTabbedPane1 = new JTabbedPane();
    Panel_1 p_1 = new Panel_1();
    JLabel jLabel1 = new JLabel();
    JTextField jTextField1 = new JTextField();
    JButton jButton1 = new JButton();
    void jButton1_actionPerformed(ActionEvent e) {
    if (jTextField1.getText() != "0") //------Executes when the condition is true
    jLabel1.setText("bingo");
    public class Panel_1 extends JPanel {//------INSIDE a JPANEL
    JTextField jTextField1 = new JTextField();
    JTextField jTextField2 = new JTextField();
    JTextField jTextField3 = new JTextField();
    JButton jButton1 = new JButton();
    void jButton1_actionPerformed(ActionEvent e) {
    jTextField2.setText(jTextField1.getText()); //----Ever executes, of course!
    if(jTextField1.getText() != "0") //----Never executes, even when
    jTextField3.setText("ojo"); //----the condition is true!

    You shouldn't use the != operator to test equality of Objects. Use Object.equals() instead.
    if (jTextField1.getText() != "0")
    should be
    if ( ! jTextField1.getText().equals("0"))
    or better:
    if ( ! "0".equals(jTextField1.getText())) <-- avoids null pointer exception.

  • Need help:JPanel not being displayed in the JFrame

    Hello,
    I have a class called ConstructRoom.java which extends JFrame and another class called DimensionsPanel.java which extends JPanel. In the ConstructRoom class I use the following theContainer.add(new DimensionsPanel());, so I can display my JPanel. Well I get the JFrame but no JPanel. When the this call is made the DimensionsPanel.java code is cycled through, Where has my JPanel gone to?
    If I change the DimensionPanel.java extend JFrame and add the the JFrame code. Then I get the JFrame and the JPanel.
    Whats going on here?
    Thanks

    I made some of the changes with no luck. Here is some of the code:
    ---------from ConstructRoom.java--------
    //Imports
    public class ConstructRoom extends JFrame
    //----Member objects and varibles
    private static String theTitle; //Varible for title of frame
    private JFrame theFrame; //Object for the JFrame
    // ----------------------------------------------------------- ConstructRoom
    public ConstructRoom(String theTitle)
    super(theTitle); //JFrame super class
    theFrame = new JFrame("My frame");
    Container theContainer = theFrame.getContentPane(); //Frame container
    theContainer.setLayout(new FlowLayout());
    theContainer.add(new DimensionsPanel());
    theFrame.pack();
    theFrame.setBounds(10,10,400, 400);
    theFrame.addWindowListener(new WindowHandler());
    theFrame.setVisible(true);
    }//end ConstructRoom(String theTitle)
    // -------------------------------------------------------------------- main
    public static void main(String args[])
    ConstructRoom theRoom = new ConstructRoom(theTitle);
    }//end main(String args[])
    //----WindowHander
    }//end class ConstructRoom extends JFrame
    --------from DimensionsPanel.java
    //Imports
    public class DimensionsPanel extends JPanel
    //----Member objects and varibles
    private JPanel dimensionsPanel; //The main panel to hold all info
    private Box panelBox; //Box for all boxes which is added to the JPanel
    private Box furnListBox; //Box for all related items of the furnList
    private Box dimensionsBox; //Box for all dimensions (x, y, z)
    private Box xFieldBox; //Box for all related items of the xField
    private Box yFieldBox; //Box for related items of the yField
    private Box zFieldBox; //Box for related items of the zField
    private Box buttonsBox; //Box for all buttons
    private Box clearBox; //Box for related clear button items
    private Box buildBox; //Box for related build button items
    private JLabel furnListLabel; //Label for the furnList comboBox
    private JLabel xFieldLabel; //Label for the xField
    private JLabel yFieldLabel; //Label for yField
    private JLabel zFieldLabel; //Label for zField
    private JTextField xField; //Text field to enter the x dimension
    private JTextField yField; //Text field to enter the y dimension
    private JTextField zField; //Text field to enter the z dimension
    private JComboBox furnList; //List of selectable furniture objects
    private JButton clearButton; //Clear button
    private JButton buildButton; //Build button
    // --------------------------------------------------------- DimensionsPanel
    public DimensionsPanel()
    //----Setting up dimensions panel
    dimensionsPanel = new JPanel();
    dimensionsPanel.setLayout(new BorderLayout());
    dimensionsPanel.setPreferredSize(new Dimension(150,150));
    dimensionsPanel.setBorder(new TitledBorder(new EtchedBorder(),
    "Select Furniture and Enter Dimensions"));
    //----Initializing GUI components
    furnListLabel = new JLabel("Select from list ");
    furnList = new JComboBox();
    xFieldLabel = new JLabel("Enter Width ");
    xField = new JTextField();
    yFieldLabel = new JLabel("Enter Height ");
    yField = new JTextField();
    zFieldLabel = new JLabel("Enter Depth ");
    zField = new JTextField();
    buildButton = new JButton("Build Object");
    clearButton = new JButton("Clear Object");
    //-----Setting up the combo box and adding items
    furnList.addActionListener(new ComboProcessor());
    furnList.addItem(" "); //Default item
    furnList.addItem("Color Cube");
    furnList.setMaximumRowCount(6); //Max number of items before scrolling
    furnList.setSelectedItem(" "); //Set initial to default item
    //--Add the furnList to its box for placement in the JPanel
    furnListBox = Box.createHorizontalBox();
    furnListBox.add(Box.createHorizontalStrut(5));
    furnListBox.add(furnListLabel); //Adding the combo box label
    furnListBox.add(furnList); //Adding the combo box
    furnListBox.add(Box.createHorizontalStrut(5)); //Spacing
    //-------------------------------- Start Dimensions Components
    //----Setting up the xField
    xField.setEnabled(false); //Disabled at start
    xField.setFocusTraversalKeysEnabled(false); //Disabling the Tab Key
    //----Adding the event listeners
    xField.addActionListener(new XTextProcessor()); //Enter Key
    xField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the xField to its box for placement in the dimensionsBox
    xFieldBox = Box.createHorizontalBox();
    xFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    xFieldBox.add(Box.createGlue()); //Take up extra space
    xFieldBox.add(xFieldLabel); //Adding the text field label
    xFieldBox.add(xField); //Adding the text field
    xFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the yfield
    yField.setEnabled(false); //Disabled at start
    yField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    yField.addActionListener(new YTextProcessor()); //Enter Key
    yField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the yField to its box for placement in the dimensionsBox
    yFieldBox = Box.createHorizontalBox();
    yFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    yFieldBox.add(Box.createGlue()); //Take up extra space
    yFieldBox.add(yFieldLabel); //Adding the text field label
    yFieldBox.add(yField); //Adding the text field
    yFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the zfield
    zField.setEnabled(false); //Disabled at start
    zField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    zField.addActionListener(new ZTextProcessor()); //Enter Key
    zField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the zField to its box for placement in the dimensionsBox
    zFieldBox = Box.createHorizontalBox();
    zFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    zFieldBox.add(Box.createGlue()); //Take up extra space
    zFieldBox.add(zFieldLabel); //Adding the text field label
    zFieldBox.add(zField); //Adding the text field
    zFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Adding all dimension components to the dimensionsBox
    dimensionsBox = Box.createVerticalBox();
    dimensionsBox.add(xFieldBox); //Adding the xFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(yFieldBox); //Adding the yFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(zFieldBox); //Adding the zFieldBox
    //-------------------------------- End Dimension Components
    //----Setting up the clearButton
    clearButton.setEnabled(false); //Disabled at start
    //----Adding the event listener
    clearButton.addActionListener(new ClearProcessor());
    //--Add the clear button to its box for placement
    clearBox = Box.createHorizontalBox();
    clearBox.add(Box.createHorizontalStrut(5)); //Spacing
    clearBox.add(clearButton); //Adding the clearButton
    //----Setting up the buildButton
    buildButton.setEnabled(false); //Disabled at start
    //--Add the action listener here
    buildBox = Box.createHorizontalBox();
    buildBox.add(buildButton); //Adding the buildButton
    buildBox.add(Box.createHorizontalStrut(5)); //Spacing
    //----Adding both buttons the buttonsBox
    buttonsBox = Box.createHorizontalBox();
    buttonsBox.add(clearBox); //Adding the clearBox
    buttonsBox.add(Box.createHorizontalStrut(10)); //Spacing
    buttonsBox.add(buildBox); //Adding the buildBox
    //----Create the JPanel (dimensionsPanel)
    //--Creating the main box to be added to the JPanel
    panelBox = Box.createVerticalBox();
    panelBox.add(furnListBox); //Adding the furnListBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(dimensionsBox); //Adding the dimensionBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(buttonsBox); //Adding the buttonsBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsPanel.add(panelBox); //Adding all components to the JPanel
    System.out.println("end dimensionpanel");
    }//end DimensionsPanel()
    //------ActionListeners
    }//end class DimensionsPanel extends JPanel

  • Displaying the content of JPanel

    hello, I have a JPanel which contains a JScrollPane displaying data from a database. I have created a JButton which permit to hide and show the content
    of jpanel (hide and show jscrollpane alternaly). but when I hide the content the first once I cant re-show it. the code of the JButton is :
    // first click
    jPanel3.add(jScrollPane1, null);
    jPanel3.repaint();
    // second click
    jPanel3.removeAll();
    this.repaint();
    Best Regards.

    Instead of actually removing the component from the GUI and then trying to put it back, why don't you just make use of the setVisible() method?

  • Displaying the content of one JPanel in an other as a scaled image

    Hi,
    I'd like to display the content of one JPanel scaled in a second JPanel.
    The first JPanel holds a graph that could be edited in this JPanel. But unfortunately the graph is usually to big to have a full overview over the whole graph and is embeded in a JScrollPanel. So the second JPanel should be some kind of an overview window that shows the whole graph scaled to fit to this window and some kind of outline around the current section displayed by the JScrollPanel. How could I do this?
    Many thanks in advance.
    Best,
    Marc.

    Hi,
    I'd like to display the content of one JPanel scaled
    in a second JPanel.
    The first JPanel holds a graph that could be edited
    in this JPanel. But unfortunately the graph is
    usually to big to have a full overview over the whole
    graph and is embeded in a JScrollPanel. So the second
    JPanel should be some kind of an overview window that
    shows the whole graph scaled to fit to this window
    and some kind of outline around the current section
    displayed by the JScrollPanel. How could I do this?
    Many thanks in advance.
    Best,
    Marc.if panel1 is the graph and panel2 is the overview, override the paintComponent method in panel2 with this
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.scale(...,...);
    panel1.paint(g2);
    }

  • How to enable a scrollbar in a JPanel

    Hi
    I am adding some components in a JPanel and I am adding the JPanel to a JScrollPane.The JScrollPane is finally added to the container.Now I could manage to get only the scrollbars added but it does not work!How should I use the scrollbars to view all the components that are added inside the JPanel.
    Here is my source code:
    tagPanel = new JPanel();
    tagPanel.setLayout(new FlowLayout());
    tagPanel.setPreferredSize(new Dimension(100,100));
    tagPanel.setBackground(Color.white);
    tagPanel.setAutoscrolls(true);
    for(int i = 0; i<=20; i++)
    tempButton = new JButton("Testing");
    tagPanel.add(tempButton);
    container.add(forbiddenscroll= new JScrollPane
    (tagPanel),BorderLayout.WEST);
    forbiddenscroll.setHorizontalScrollBarPolicy
    (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    forbiddenscroll.setVerticalScrollBarPolicy
    (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    Thank you for your reply!
    Your help is very much appreciated.

    don't set prefered size of the tag panel.
    run this code pasted below. it work fine.
    regards,
    Pratap
    import java.awt.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
         JScrollPane forbiddenscroll;
         JPanel tagPanel;
         JButton tempButton;
         public Frame1() {
              tagPanel = new JPanel();
              tagPanel.setLayout(new FlowLayout());
              tagPanel.setBackground(Color.white);
              tagPanel.setAutoscrolls(true);
              for(int i = 0; i<=20; i++)
                   tempButton = new JButton("Testing");
                   tagPanel.add(tempButton);
              forbiddenscroll = new JScrollPane();
              forbiddenscroll.getViewport().setView(tagPanel);
              getContentPane().add(forbiddenscroll, BorderLayout.CENTER);
              forbiddenscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
              forbiddenscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         public static void main(String[] args) {
              Frame1 f = new Frame1();
              f.pack();
              f.setLocation(200,200);
              f.show();
    }

  • How to draw a 3Drect in a JPanel.

    Hi, I'd like to draw a 3D rectangle in a panal to make some components looks grouped. e.g. if I have a name(JLabel: JTextField) and address(JLabel:JTextField) in a panel and want to draw a 3D rectangle around these two fields, how can I do that? Looks that the paint(Graphics g) doesn't work here.
    The following is my test program, it has two files, an applet as program entrance and a Panel to draw on:
    // TestApplet.java
    import javax.swing.*;
    public class TestApplet extends JApplet     {
         public void init()     {
              TopPanel tp = new TopPanel();
              add(tp);
    // TopPanel.java
    import javax.swing.*;
    public class TopPanel extends JPanel     {
         public TopPanel()     {
              JLabel lb = new JLabel("test");
              add(lb);
              Choice c = new Choice();
              c.add("1");
              c.add("2");
              add(c);
         public void paint(Graphics g)     {
              g.draw3DRect(5, 5, 40, 40, false);
              super.paint(g);
    }

    sorry for the messy code.
    I've tried switching the two lines, but it doesn't
    work. :(
    Here is the repost of the code, I don't know why I
    can't edit the original post....
    // TestApplet.java
    import javax.swing.*;
    public class TestApplet extends JApplet     {
         public void init()     {
              TopPanel tp = new TopPanel();
              add(tp);
    // TopPanel.java
    import javax.swing.*;
    import java.awt.*;
    public class TopPanel extends JPanel     {
         public TopPanel()     {
              JLabel lb = new JLabel("test");
              add(lb);
              Choice c = new Choice();
              c.add("1");
              c.add("2");
              add(c);
         public void paint(Graphics g)     {
              super.paint(g);
              g.draw3DRect(5, 5, 40, 40, false);
    1. You can only edit posts that have not been replied to.
    2. Your code worked for me? (What is the problem).
    3. Suggestions use a JComboBox instead of Choice. (It is not good to mix AWT and Swing.) Also you should be overiding paintComponentinstead of paint.
              @Override
              public void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   g.draw3DRect(5, 5, 40, 40, false);
              }

  • How to add a JScrollPane in a JPanel

    I have a JPanel (layout = null, size = 200*400).
    I would like to add a JScrollPane, that sizes 100*100 and that contains an other JPanel, at the location 0,200 in the first JPanel. I would like too that the JScrollBar is always visible.
    How is it possible ?

    The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scroll pane. So you probably need to add:
    panel.setPreferredSize(...);
    Of course if you use LayoutManagers, instead of a null layout, then this is done automatically for you.
    If you want the scroll bars to appear all the time then read the JScrollPane API.

  • How to Fit a component in a JPanel

    Hy, I am actually creating a Graphical Programming Language Appln and I am facing some problems.
    My source code is found below. Here is my problem:
    I have inserted some buttons have been inserted in the Main panel until both scroll bar appear,
    what I want is that when I click on the button label "Fit", a new window opens,
    where it shows the buttons which have been fitted in that window, without any scrollbar.How to do that?
    Please send me the code for solving this problem. Its very very urgent.Here are my Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import javax.swing.tree.*;
    import java.io.*;
    public class MainDesktop extends JFrame implements ActionListener {
    JSplitPane splitPane = new JSplitPane();
    JPanel mainPane = new JPanel();
    JScrollPane mainScrollPane = new JScrollPane();
    Container contentPane = getContentPane();
    public MainDesktop() {
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Adding the ToolBar to the main window
    JToolBar toolBar = new JToolBar();
    myToolBar(toolBar);
    contentPane.add(toolBar, BorderLayout.NORTH);
    //create a list of button and add them to a pane
    JButton bgButton = new JButton("Begin");
    JButton rdButton = new JButton("Read");
    JButton wrButton = new JButton("Write");
    JButton efButton = new JButton("If-Else");
    JButton ifButton = new JButton("End-If");
    JButton wlButton = new JButton("While-Loop");
    JButton flButton = new JButton("For-Loop");
    JButton elButton = new JButton("End-Loop");
    JButton swButton = new JButton("Switch");
    JButton arButton = new JButton("Arithmetic");
    JButton enButton = new JButton("End");
    bgButton.setActionCommand("Begin");
    rdButton.setActionCommand("Read");
    wrButton.setActionCommand("Write");
    efButton.setActionCommand("If-Else");
    ifButton.setActionCommand("End-If");
    wlButton.setActionCommand("While-Loop");
    flButton.setActionCommand("For-Loop");
    elButton.setActionCommand("End-Loop");
    swButton.setActionCommand("Switch");
    arButton.setActionCommand("Arithmetic");
    enButton.setActionCommand("End");
    bgButton.addActionListener(this);
    rdButton.addActionListener(this);
    wrButton.addActionListener(this);
    efButton.addActionListener(this);
    ifButton.addActionListener(this);
    wlButton.addActionListener(this);
    flButton.addActionListener(this);
    elButton.addActionListener(this);
    swButton.addActionListener(this);
    arButton.addActionListener(this);
    enButton.addActionListener(this);
    JPanel toolPane = new JPanel();
    toolPane.setLayout(new GridLayout(15,0));
    toolPane.add(bgButton);
    toolPane.add(rdButton);
    toolPane.add(wrButton);
    toolPane.add(efButton);
    toolPane.add(ifButton);
    toolPane.add(wlButton);
    toolPane.add(flButton);
    toolPane.add(elButton);
    toolPane.add(swButton);
    toolPane.add(arButton);
    toolPane.add(enButton);
    //Create a pane for the drawing area and add scroll pane to it
    mainPane.setLayout(new FlowLayout());
    mainScrollPane = new JScrollPane(mainPane);
    mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    mainScrollPane.setHorizontalScrollBarPolicy (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    mainScrollPane.setLayout(new ScrollPaneLayout());
    //Create a split pane with the two scroll panes in it
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,toolPane, mainScrollPane);
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(100);
    splitPane.setPreferredSize(new Dimension(1000, 650));
    getContentPane().add(splitPane);
    protected void myToolBar(JToolBar toolBar) {
    //Fit button
    JButton fitButton = new JButton("Fit");
    fitButton.setToolTipText("Fit Flowchart to drawing area");
    fitButton.setActionCommand("Fit");
    fitButton.addActionListener(this);
    toolBar.add(fitButton);
    public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    if (cmd.equals("Fit")) {
    //fit flowchart to drawing area
    if (cmd.equals("Delete")) {
    //Delete a node from flowchart
    //Action command for the list of button from the toolbox
    if (cmd.equals("Begin")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("Read")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("Write")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("If-Else")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("End-If")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("While-Loop")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("For-Loop")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("End-Loop")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("Switch")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    if (cmd.equals("Arithmetic")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    //mainPane.repaint();
    if (cmd.equals("End")) {
    dragbutton drag = new dragbutton();
    mainPane.add(drag);
    //mainPane.repaint();
    class dragbutton extends JButton implements DragGestureListener, DragSourceListener {
    public dragbutton() {
    super("Begin");
    DragSource dragSource = DragSource.getDefaultDragSource();
    dragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_COPY_OR_MOVE,this);
    public void dragGestureRecognized(DragGestureEvent e) {
    e.startDrag(DragSource.DefaultCopyDrop,
    new StringSelection(null),this);
    public void dragDropEnd(DragSourceDropEvent e) {}
    public void dragEnter(DragSourceDragEvent e) {}
    public void dragExit(DragSourceEvent e) {}
    public void dragOver(DragSourceDragEvent e) {}
    public void dropActionChanged(DragSourceDragEvent e) {}
    public static void main(String [] args) {
    MainDesktop mainWindow = new MainDesktop();
    mainWindow.setTitle("Graphical Programming Language");
    mainWindow.setSize(700, 600);
    mainWindow.setVisible(true);

    Instead of using:
    frame.setSize(int, int);
    use:
    frame.pack();

  • How to replace a component in the JPanel?

    Hi,
    I want to replace a component in the JPanel. My panel has GridBagLayout.
    Thanks in advance.

    because my application demands me to use GridBagLayout.No it doesn't, that a choice you made. You are never forced to use a specific layout manager. In fact most layout problems are solved by using combinations of layout managers. You two main choices are:
    a) use a GridbagLayout for the main panel and then a CardLayout for the two components you want to sway, although it may look strange if the components are a different size as the preferred size of the panel will be the size of the largest component
    b) Simulate a card layout using:
    panel.remove(...)
    panel.add(...);
    panel.revalidate(...)

Maybe you are looking for

  • Function Module for open Purchase Order & Sales Order?

    Hi, commonly I read the data from tables and calculate the open quantity for sales order and purchase order, but I want to know, are there any standard function modules for getting the list of open "purchase order" and "sales order" respectively? Tha

  • Applet not showing in browser/only getting a grey box

    Hell to all.... I am using a trial version of MS J++ and every time i execute to the browser i dont see my output all i get is a lil grey box on left side with header rules (<hr> tage in HTML) surounding the box. Can anyone help me out??? if you need

  • Can I activate a 5S on a network that only "allows" up to an iPhone 5?

    Hello, I am looking to start service with FreedomPop using a phone. They currently only sell the iPhone 5, but say the 4 and 4s are okay to bring to the network. They even told me the 5S and 5C were not allowed due to some software concern... Can som

  • Issue with Output designer and  Konica bizhub Pro 920 Driver:

    Hi, i would appreciate if someone could help me with the following issue: I have designed a document using Adobe Output Designer and need to print it on Konica printer which uses above driver. Konica is not included in Adobe Presentment Target List s

  • Duplicate Routing with dependencies

    Hi all, I'm trying to copy a Routing changing the Application (VERWE = 'C' instead of '1') I'm using the FM CARO_ROUTING_READ to take the original Routing and then call FM BAPI_ROUTING_CREATE passing tables TASK, MATERIALTASKALLOCATION,  SEQUENCE and