Switching JPanels

I've 2 JPanels in a CordLayout.
When I switch from one JPanel to the other by pressing a JButton some methods a running which take some time.
I want to add a third JPanel which displays an Image with a "please stand by" text.
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src instanceof JButton) {
if(src==switch) {
myCardLayout.show(textContainer,"STANDBY");
some methods...
myCardLayout.show(textContainer,"2ndJPanel");
The Problem is that the changes in the CardLayout are done after the rest of the Action is finished so that there is no visual effect.
Any ideas?
Thank you
Jörn

Thank you, but how does this work?
I tried to define a new Thread as
public class showWait extends Thread {
CardLayout textLayout;          
public showWait(CardLayout tL)
textLayout=tL;
public void run()
textLayout.show(textContainer,"STANDBY");
public CardLayout getLayout()
return textLayout;
and I used this thread in the actionPerformed method:
showWait sw = new showWait(textLayout);
sw.run();
textLayout=sw.getLayout();
but with this I have not divided the thread into 2 threads...
So what am I doing wrong?

Similar Messages

  • Switching jpanels implemented in different classes

    Hi,
    I'm quite new to swing applications (not to java) and I run into a problem I couldn't solve.
    I got a frame and in that frame a jMenu and a jPanel.
    I want to create an application where you have to log in, so my first jPanel represents the login (LogInPanel). After a succesful login I want to replace the LogInPanel with an other (LoggedInPanel). This class doesn't belong to my main class and is implemented separatly.
    My questions are:
    1.)is it possible create a gui like that or is there an other, better way, beside doing everything in one class?
    2.)how can I change from the LogInPanel to the LoggendInPannel after I called the jButtonLogin_actionPerformed(ActionEvent e) from the LogInPanel
    3.)I also want to change the state of some values in my jMenu after successful login, but I don't know how to get access to them from my LoggedInPannel class.
    Thanks for any help
    Jens

    I don't really understand your problem, but I've had headaches with managing a GUI before (as many programmers have, I'm sure).
    My best advice, if the scheme your using to build and manage a GUI is too confusing for you, the programmer, to easily understand/manage, change the scheme. Even if this means recoding a good deal of your program (though, hopefully, you've kept the GUI as seperate from your functional code as possible) it should be worth it.
    Perhaps a clearer explination of your problem would help better illustrate your problem?
    -Rejun

  • How to use a backgroud image in a JPanel.....

    hi,
    How can I display a background image for a JPanel.....
    I have searched this forum but all solutions I found are where JPanel at the end has to be displayed on a frame in an application...
    I need to use JPanel on Applet.......
    Actually I am switching JPanels on JApplet as screens for a game....
    I need to display background image for one of the JPanel class that has to be called by an Applet class....
    Thanks a lot for any help.

    Thanks a lot for your help.
    How do we specify URL to use an image from net. Is itt like I open an image file on some website & use its address? Kindly add here some website too so that its more clear for me.
    Thanks a lot for any help & all help your provided previously.
    String imageFilePath = "urlOfMyImageFile"; // I am asking about parameter to be used here
    ImageIcon ii = new ImageIcon(imageFilePath);
    Image image = ii.getImage();

  • How do you switch between jpanels in a jframe?

    I have, what seems, a relatively simple question; however I cant find a solution to it anywhere!
    I have a jframe with a jmenubar which has 4 menu items. When each item is clicked a new JFrame is displayed with certain content. What I am trying to do, instead of creating a new Jframe each time a menu item is clicked, is display all jpanels within the current jframe. When different menu items in the jmenu are clicked it "switches" the main jpanel to display the required content.
    So basically I want 1 JFrame, which has 4 JPanels, (alhough only 1 is shown at any given time). When a menu item in the jmenubar is clicked the JPanel which corresponds to the menu item is displayed on the jframe.
    If your still confused, I basically want jtabbedpane functionality only I want to control the switching through tabs via the jmenubar (and I dont want the jtabbedpane tabs obviously).
    Thanks

    Myles wrote:
    Okay that seems obvious ;)
    What do you mean by "validating the content pane" though?
    Thanks for your quick reply.Containers have a method called validate() which will update them when components are added and removed. Without this, you won't see added components.
    And yes, you can have more than 1 container. JPanels are containers themselves and can have components added and removed from them as well. You only have one content pane in the JFrame, but you could add two JPanels to this, one static and one to act as your swapping container.

  • Switch Between Jpanels within a JFrame

    Hi, I am new to this java thing and I need a hand with the following problem
    I have 3 classes
    Invaders
    Game
    OptionsMenu
    Basically, you execute the program which executes Invaders, which then creates a JFrame with a border layout and adds the menu bar to the top, JPanel with either game or OptionsMenu to the center and a further JPanel to the bottom containing buttons and labels
    The specifics of the problem is I can not work out how to change between the panels in the center of the border layout in the frame created by invaders.
    When the program loads its ment to load with the options menu, which is no problem, the problem comes when I need to change the frame from the options menu to the game via a button on the options menu, the options menu passes the variables its gathered to the game constructor and it is then ment to display in the center of the border layout in the JFrame from invaders, any help would be appreciated, I have spent 2 days trying to get it to work and have not been sucessful

    I can not work out how to change between the panels in the center of
    the border layout in the frame created by invaders.Use a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout.

  • JFrame switching to JPanel

    My JFrame is working perfectly. Its got a button on it that when pressed I want my panel to appear. I don't mind if the other one dissapears or stays there.
    I have created a JPanel in a seperate java file. Its fine aswell, but now I want it to appear when I hit my add button.
    I expecetd it to be a case of a new instance the following would work;
    JPanelAdd panel = new JPanelAdd();But no joy. Then I thought I could do something like panel.show();
    So, I'm obviously doing something basic wrong. I'd appreciate the help.

    No joy with the following:
    private void
    jButtonAddMouseClicked(java.awt.event.MouseEvent evt)
    JPanelAdd panel = new JPanelAdd();
    this.getContentPane().add(panel);
    panel.setVisible(true);
    System.out.println("got here");
    Being a novice myself, I can only tell you that these two code snippets:
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            dlgPrueba.setVisible(true);
        private void miFilePreferencesLoadActionPerformed(java.awt.event.ActionEvent evt) {                                                     
            PrefDialog pf = new PrefDialog();
            System.out.println("Option 'Load Preferences...' has been choosed.");
            pf.setVisible(true);
        }                                                     work for me. The first one launches a jDialog created inside the jFrame (when I say "inside", I mean that you add a jDialog from the Palette Manager while editing the jFrame; that jDialog is bound to be used exclusively as part of the jFrame).
    The second one is closest to your environment. I've got a separate .java file to define the class "PrefDialog" which, as you may suppose, extends jDialog.
    In both cases, the dialogs work fine. As a side note, the first runs on a button click, while the second one gets launched by choosing a menu item.
    Sorry to not be able to help you further.

  • 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 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 tint a JPanel that paints an Image

    Hello all,
    I have a basic understanding of Java Swing architecture and the Drawing capabilities of the Graphics and Graphics2D classes. However, i am utterly confused how to implement a basic tint over an image.
    Overview:
    I have a GCard (Graphical Card) class that extends JPanel. This class contains a BufferedImage so that when the GCard is added to a higher-level Container, it paints the BufferedImage. What I want to do is tint that card image to a user specified color (let's say RED) via the GCard.setTint(Color.RED) method and then allow them to control if the tint is on/off via the GCard.setTinted(true) method.
    What I have:
    Currently, I have the following in my GCard.paintComponent(Graphics g) method:
         @Override
         protected void paintComponent(Graphics g) {
              int xPosition = 0;
              int yPosition = 0;
              if(image != null) {
                   g.drawImage(image, xPosition, yPosition, null);
                   if(isTinted() && tint != null) {
                        g.setColor(tint);
                        for(int x = xPosition; x < (xPosition + image.getWidth()); x += 2)
                             for(int y = yPosition; y < (yPosition + image.getHeight()); y += 2)
                                  g.drawLine(x, y, x, y);
         }All this does is implement a rudimentary tinting scheme by setting every other pixel in the panel to the tint color.
    What I want:
    What I'd like to see instead is a red haze over the entirety of the image. Much like the multiple item selection process that occurs when you select multiple things in a modern-day OS.
    How can i do this?
    From what I've read/thought out, I can either edit the actual image data to increase the level of the appropriate tint color, but I would prefer to be non-destructive to the image I'm holding in memory. I would prefer to imitate the 'layer' functionality of Adobe Photoshop where my image is the 'background' and I have a transparent panel that is tinted which can be switched on and off. Can I accomplish all of this in the paintComponent() method or will i need to add a JPanel (let's call it a tintPanel)to the GCard object and then add/remove that component from the GCard as necessary?
    Thanks for the help!
    -Pheez

    Something likeprotected void paintComponent(Graphics g) {
       super.paintComponent(g);
       g.drawImage(....);
       g.setColor(new Color(r, g, b, a)); // where a <1.0
       g.fillRect(aRectThatOverlapsTheImage);
    }db

  • Problem with jpanel and revalidate()

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

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

  • JPanel loses keyboard focus

    Ok, i have a JTextField which is initially disabled. A JPanel draws some stuff and receives keyboard input. When i enable the textfield, type some stuff, then press Esc (which disables it), i cant get the keyboard focus back on the JPanel. Here is an example:
    (you can move the red circle before you enable the textfield, after you disable it, you cant move it anymore).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.util.Vector;
    public class example extends JPanel implements ActionListener,Runnable {
        JFrame frame;
        JMenuBar menubar;
        JMenu m_file;
        JMenuItem mi_open,mi_close;
        JPanel canvas,northpanel;
        JTextField textfield;
        Image canvasimg;
        Thread thread=new Thread(this);
        private Image dbImage;     // for flickering
         private Graphics dbg;     // for flickering
         int x1=400,y1=200;
        public example() {
            frame = new JFrame("Example");                         // window
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setPreferredSize(new Dimension(1000,700));
            frame.setLayout(new BorderLayout());
            northpanel=new JPanel();
            northpanel.setLayout(null);
            northpanel.setPreferredSize(new Dimension(1000,20));     northpanel.setLocation(0,0);
            menubar=new JMenuBar();
            m_file=new JMenu("File");   
            mi_open=new JMenuItem("Open");
            mi_close=new JMenuItem("Close");
            m_file.add(mi_open);
            m_file.add(mi_close);   
            m_file.getPopupMenu().setLightWeightPopupEnabled(false);   
            menubar.add(m_file);
            northpanel.add(menubar);
            menubar.setLocation(0,0);     menubar.setSize(80,20);
            textfield=new JTextField();
            northpanel.add(textfield);
            textfield.setSize(200,20);     textfield.setLocation(500,0);   
            textfield.setEnabled(false);
            frame.add(northpanel,BorderLayout.NORTH);
            canvas=new JPanel();
            canvas.setLayout(null);
            canvas.setSize(1000,600);
            canvas.setBackground(Color.white);
             frame.add(canvas,BorderLayout.CENTER);      
            frame.pack();
            frame.setVisible(true);       
            thread.start();                                   // start the thread
            textfield.addMouseListener(new MouseAdapter(){
                    public void mousePressed(MouseEvent e){
                         textfield.setEnabled(true);
               textfield.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){
                      int key=e.getKeyCode();
                      if(key==27){     // esc
                           textfield.setEnabled(false); 
                           canvas.setEnabled(true);                // not working
                           canvas.requestFocus();
                           canvas.requestFocusInWindow();
               frame.addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e){                   
                      int key=e.getKeyCode();
                      if(key==37){ //left
                           x1-=5;
                      if(key==38){ //up
                           y1-=5;
                      if(key==39){ //right
                           x1+=5;
                      if(key==40){ //down
                           y1+=5;
        // Create the GUI and show it. 
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            example ex = new example();
        public void run(){
             while(true){
                  try{
                       if(canvasimg==null)repaint();                   
                       Graphics g=canvas.getGraphics();
                       update(g);
                       thread.sleep(30);                                             // 1 sec
                  }      catch(InterruptedException ex){}
        // ActionPerformed handles button and menu events
        public void actionPerformed(ActionEvent e){              
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void update (Graphics g){          // get rid of flicker
              if (dbImage == null){
                   dbImage = canvas.createImage (canvas.getSize().width, canvas.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (canvas.getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (canvas.getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
         public void paint(Graphics g){
              g.drawImage(canvasimg,0,0,this);          
              g.setColor(Color.red);
             g.fillOval(x1,y1,10,10);
        public void repaint(){     
             if(canvas!=null && canvasimg==null)canvasimg=canvas.createImage(1000,670);
             if(canvasimg==null)return;
             Graphics g=canvasimg.getGraphics();
             if(g==null)return;
             g.setColor(Color.white);
             g.fillRect(0,0,1000,600);
    }  

    OK great guru since you're so damn confident that you're doing everything right, find out for yourself why this works and yours doesn't.
    I could list a few dozen things wrong with your code, but I'd be wasting my keystrokes.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TextFieldDisableNoProblem extends JPanel {
       JPanel northPanel;
       JMenuBar menubar;
       JMenu m_file;
       JMenuItem mi_open,mi_close;
       JTextField textField;
       int x1 = 400;
       int y1 = 200;
       public TextFieldDisableNoProblem () {
          setBackground (Color.WHITE);
          addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                switch (key) {
                   case KeyEvent.VK_LEFT:
                         x1 -= 5;
                         break;
                   case KeyEvent.VK_UP:
                         y1 -= 5;
                         break;
                   case KeyEvent.VK_RIGHT:
                         x1 += 5;
                         break;
                   case KeyEvent.VK_DOWN:
                         y1 += 5;
                         break;
                repaint ();
       void makeUI () {
          JFrame frame = new JFrame ("");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (600, 500);
          frame.setLocationRelativeTo (null);
          menubar=new JMenuBar ();
          m_file=new JMenu ("File");
          mi_open=new JMenuItem ("Open");
          mi_close=new JMenuItem ("Close");
          m_file.add (mi_open);
          m_file.add (mi_close);
          menubar.add (m_file);
          frame.setJMenuBar (menubar);
          textField=new JTextField ();
          textField.setEnabled (false);
          textField.setBounds (200, 0, 200, 20);
          textField.addMouseListener (new MouseAdapter (){
             public void mousePressed (MouseEvent e){
                textField.setEnabled (true);
          textField.addKeyListener (new KeyAdapter () {
             public void keyPressed (KeyEvent e){
                int key = e.getKeyCode ();
                if(key == KeyEvent.VK_ESCAPE){
                   textField.setEnabled (false);
                   requestFocus ();
          northPanel=new JPanel ();
          northPanel.setLayout (null);
          northPanel.setPreferredSize (new Dimension (600,20));
          northPanel.add (textField);
          frame.add (northPanel,BorderLayout.NORTH);
          frame.add (this, BorderLayout.CENTER);
          frame.setVisible (true);
          requestFocus ();
       public void paintComponent (Graphics g) {
          super.paintComponent (g);
          g.setColor (Color.RED);
          g.fillOval (x1, y1, 10, 10);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                JFrame.setDefaultLookAndFeelDecorated (true);
                new TextFieldDisableNoProblem ().makeUI ();
    }db

  • How can I hide a JPanel?

    I have some JPanels and using the mouse motion listeners you can scribble on them. I want to be able to switch between these panels but the problem is the drawings get wiped off when I use repaint() and frame.add(panel).
    Any ideas how else I could try doing this?

    Ok thanks everyone. I've taken the MyPanel class from here http://java.sun.com/docs/books/tutorial/uiswing/painting/step3.html
    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
        private void moveSquare(int x, int y) {
            int OFFSET = 1;
            if ((squareX!=x) || (squareY!=y)) {
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
                squareX=x;
                squareY=y;
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);      
            g.drawString("This is my custom Panel!",10,20);
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX,squareY,squareW,squareH);
    }Now if I use this class to make two panels, how can I hide one and bring the other one up and vice versa, using two buttons? setVisible() still doesn't work properly.
    Here's the whole code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseMotionAdapter;
    public class PanelTest extends JFrame {
        private MyPanel panelOne;
        private MyPanel panelTwo;
        private BorderLayout layoutManager;
        private PanelTest() {
            layoutManager = new BorderLayout();
            this.setLayout(layoutManager);
            panelOne = new MyPanel();
            panelTwo = new MyPanel();
            panelOne.add(new JLabel("This is Panel One"));
            panelTwo.add(new JLabel("This is Panel Two"));
            setCurrentPanel(panelOne);
            JButton switchButton = new JButton("Switch");
            switchButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(getCurrentPanel() == panelOne) {
                        setCurrentPanel(panelTwo);
                    } else {
                        setCurrentPanel(panelOne);
            this.getContentPane().add(switchButton, BorderLayout.SOUTH);
            this.pack();
            this.setVisible(true);
        private void setCurrentPanel(MyPanel panel) {
            this.getContentPane().add(panel, BorderLayout.CENTER);
            panel.revalidate();
            panel.repaint();
        private JPanel getCurrentPanel() {
            return (JPanel)layoutManager.getLayoutComponent(BorderLayout.CENTER);
        public static void main(String[] args) {
            new PanelTest();
    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
        private void moveSquare(int x, int y) {
            int OFFSET = 1;
            if ((squareX!=x) || (squareY!=y)) {
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
                squareX=x;
                squareY=y;
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);      
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX,squareY,squareW,squareH);
    }Edited by: atom.bomb on Mar 30, 2010 11:25 AM

  • Help with adding a JPanel with multiple images to a JFrame

    I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
    20
    SXXXXXXXXXXXXXXXXXXX
    XXXX XXXXXXXXXXX
    X XXXXX
    X X XX XXXXXXXXXXXX
    X XXXXXXXXX XXX
    X X XXXXXXXXX XXXXX
    X XXXXX XXXXX XXXXX
    XX XXXXX XX XXXX
    XX XXXXX XXXXXXXX
    XX XX XXXX XXXXXXXX
    XX XX XXXXXXXX
    XX XXX XXXXXXXXXXXXX
    X XXXXXXXXXXXXX
    XX XXXXXXX !
    XX XXXXXX XXXXXXXXX
    XX XXXXXXX XXXXXXXXX
    XX XXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXX
    Generated by the Random Maze Generator
    And the code for the "translator" is this:
    package project;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    public class Translator extends JFrame {
       private FileReader Reader;
       private int size;
       Image wall,blank,exit,start,step1,step2;
      public Translator(){}
      public Translator(File F){
      try {
           Reader=new FileReader(F);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      try {
      size=Reader.read();
      System.out.write(size);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      Toolkit theKit=Toolkit.getDefaultToolkit();
      wall=theKit.getImage("wall.gif");
      blank=theKit.getImage("blanktile.jpg");
      exit=theKit.getImage("exit.jpg");
      start=theKit.getImage("start.jpg");
      step1=theKit.getImage("start.jpg");
      step2=theKit.getImage("step1.jpg");
      JPanel panel=new JPanel(){
      public void paintComponent(Graphics g) {
      super.paintComponents(g);
      int ch=0;
      System.out.print("a1 ");
      int currentx=0;
      int currenty=0;
      try {ch=Reader.read();
          System.out.write(ch);}
      catch (IOException e){}
      System.out.print("b1 ");
      while(ch!=-1){
        try {ch=Reader.read();}
        catch (IOException e){}
        System.out.write(ch);
        switch (ch){
            case '\n':{currenty++;
                      break;}
            case 'X':{System.out.print(">x<");
                     g.drawImage(wall,(currentx++)*20,currenty*20,this);
                     break;}
           case ' ':{
                     g.drawImage(blank,(currentx++)*20,currenty*20,this);
                     break;}
            case '!':{
                     g.drawImage(exit,(currentx++)*20,currenty*20,this);
                      break;}
            case 'S':{
                     g.drawImage(start,(currentx++)*20,currenty*20,this);
                      break;}
            case '-':{
                     g.drawImage(step1,(currentx++)*20,currenty*20,this);
                      break;}
            case 'o':{
                      g.drawImage(step2,(currentx++)*20,currenty*20,this);
                      break;}
            case 'G':{ch=-1;
                      break;}
                  }//Swith
          }//While
      }//paintComponent
    };//Panel
    panel.setOpaque(true);
    setContentPane(panel);
    }//Constructor
    }//Classforget all those systems.out and that stuff, that is just for the testing
    i call it in another class in this way:
    public Maze(){
        firstFrame=new JFrame("Random Maze Generator");
        firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        (...)//more constructor code here
        Translator T=new Translator(savefile);
        firstFrame.add(T);
        firstFrame.getContentPane().add(c);
        firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
        firstFrame.setVisible(true);
        c.setSize(d.width/2,d.height/4);
        c.show();
        }i know it may be a very basic or concept problem, but i can't get it solved
    thanks for any help

    Try this. It's trivial to convert it to use your images.
    If you insist on storing the maze in a file, just read one line at a
    time into an ArrayList than convert to an array and pass that to the
    MazePanel constructor.
    Any questions, just ask.
    import java.awt.*;
    import javax.swing.*;
    public class CFreman1
         static class MazePanel
              extends JPanel
              private final static int DIM= 20;
              private String[] mMaze;
              public MazePanel(String[] maze) { mMaze= maze; }
              public Dimension getPreferredSize() {
                   return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
              public void paint(Graphics g)
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, getSize().width, getSize().height);
                   for (int y= 0; y< mMaze.length; y++) {
                        String row= mMaze[y];
                        for (int  x= 0; x< row.length(); x++) {
                             Color color= null;
                             switch (row.charAt(x)) {
                                  case 'S':
                                       color= Color.YELLOW;
                                       break;
                                  case 'X':
                                       color= Color.BLUE;
                                       break;
                                  case '!':
                                       color= Color.RED;
                                       break;
                             if (color != null) {
                                  g.setColor(color);
                                  g.fillOval(x*DIM, y*DIM, DIM, DIM);
         public static void main(String[] argv)
              String[] maze= {
                   "SXXXXXXXXXXXXXXXXXXX",
                   "    XXXX XXXXXXXXXXX",
                   "X              XXXXX",
                   "X  X XX XXXXXXXXXXXX",
                   "X    XXXXXXXXX   XXX",
                   "X  X XXXXXXXXX XXXXX",
                   "X  XXXXX XXXXX XXXXX",
                   "XX XXXXX XX     XXXX",
                   "XX XXXXX    XXXXXXXX",
                   "XX  XX XXXX XXXXXXXX",
                   "XX  XX      XXXXXXXX",
                   "XX XXX XXXXXXXXXXXXX",
                   "X      XXXXXXXXXXXXX",
                   "XX XXXXXXX         !",
                   "XX  XXXXXX XXXXXXXXX",
                   "XX XXXXXXX XXXXXXXXX",
                   "XX          XXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XXXXXXXXXXXXXXXXXXXX"
              JFrame frame= new JFrame("CFreman1");
              frame.getContentPane().add(new MazePanel(maze));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

  • Canvas3D JPanel and Behavior

    Hello,
    I am a student’s geomatic and I do my memory on 3D object implementation in a data base.
    To do that, I have a 3D graphic interface. I use Java 3D and Swing.
    Now, my program load only 3D points. There are 3 parts:
    - a 3D viewer,
    - a table,
    - buttons for the actions.
    I would like to get the 3D mouse coordinates in my 3D world.
    I succeed in a first program’s version. There were two windows JFrame, one included the Canevas3D and the other the table with the buttons.
    For the mouse’s action, I modify this source code :
    http://deven3d.free.fr/telechargements/fichiers/java3d/chap07/SimpleBehavior/SimpleBehavior.java
    Then, I put the Canevas3D in a JPanel (and neither in a separate window). And I add this JPanel to the JFram (those contain the table and the buttons for the actions).
    And after that my class Behavior don’t work.
    I think it’s due to my ActionListener (it’s use to catch the buttons’ press) who intercept the mouse action.
    This is my class Behavior :
    import java.awt.AWTEvent;
    import java.awt.Point;
    import java.awt.event.*;
    import java.util.Enumeration;
    import javax.media.j3d.*;
    import javax.vecmath.Point3d;
    public class InterGraph3d extends Behavior {
           // Condition qui va declencher le stimulus
           private WakeupCondition wakeupCondition =
                new WakeupOnAWTEvent(MouseEvent.MOUSE_PRESSED);
           private Canvas3D caneva;
           InterGraph3d (Canvas3D cane){
                   this.caneva = cane;
         public void initialize() {
             this.wakeupOn(wakeupCondition);
         public void processStimulus(Enumeration criteria) {
              WakeupCriterion critere;
             AWTEvent[] events;
             MouseEvent evt;
             // On boucle sur les critères ayant declenche le comportement
             while (criteria.hasMoreElements()) {
               // On recupere le premier critere de l'enumeration
               critere = (WakeupCriterion)criteria.nextElement();
               // On ne traite que les criteres correspondant a un evenement AWT
               if (critere instanceof WakeupOnAWTEvent) {
                 // On récupère le tableau des evements AWT correspondant au critere
                 events = ((WakeupOnAWTEvent)critere).getAWTEvent();
                 if (events.length > 0) {
                   // On récupère l'événement
                   evt = (MouseEvent)events[events.length-1];
                   // Traitement au cas par cas selon la touche pressée
                   switch(evt.getButton()) {
                   // Obtenir les coordonnées 3D du point cliqué
                     case MouseEvent.BUTTON1: // clic gauche
                     // pour avoir les coordonnées du point cliqué dans l'univers en 3D
                     // on déclare un point 3D
                     Point3d ptSourie = new Point3d();
                     // on utilise la fonction pour avoir les coordonnées de la sourie en 3D.
                     ptSourie = obtenirPointSourieCaneva(caneva, evt.getPoint());
                     // ici faire une liaison avec l'interface graphique
                     System.out.println("Coor sourie");
                       System.out.println(ptSourie.x);
                       System.out.println(ptSourie.y);
                       System.out.println(ptSourie.z);
                       break;
              // Une fois le stimulus traite, on réinitialise le comportement
             this.wakeupOn(wakeupCondition);
         // fonction pour récupérer les coordonnées de la sourie dans le
         public Point3d obtenirPointSourieCaneva(Canvas3D myCanvas, Point clickPos)
              Point3d mousePos = new Point3d();
              //pixel value in image-plate coordinates and copies that value into the object provided.
             myCanvas.getPixelLocationInImagePlate(clickPos.x, clickPos.y, mousePos);
              //This block of code converts our image plate coordinates out to virtual world coordinates
              Transform3D motion = new Transform3D();
              myCanvas.getImagePlateToVworld(motion);
              //We do this convertion the mouse position.
              motion.transform(mousePos);
              return mousePos;
    }

    The ScrollDemo uses the column and row header as well as the corner to create the rulerIt adds a component to the colum and row header and the corner. That component may or may not be a JPanel, or JComponent which they have used for custom painting.
    Can I change the ScrollDemo to use a JPanel instead?Makes no sense. There are 9 areas to add a Component. Any of those 9 areas can hold a JPanel.
    Does a JPanel provide the same elements A panel uses a LayoutManager to place components. Check the scroll pane source code to see what LayoutManager it uses.

  • How to resize JPanel at Runtime ??

    Hi,
    Our Project me t a problem as below, we hope to resize JPanel at Runtime , not at design time, ie, when we first click the button called "Move JPanel" , then we click the JPanel, then we can drag it around within main panel, but we hope to resize the size of this JPanel when we point to the border of this JPanel then drag its border to zoom in or zoom out this JPanel.
    Please advice how to do that??
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
    import javax.swing.event.*;
    public class ResizeJPanels extends JPanel
        protected JLabel label1, label2, label3, label4, labeltmp;
        protected JLabel[] labels;
        protected JPanel[] panels;
        protected JPanel selectedJPanel;
        protected JButton btn  = new JButton("Move JPanel");
        int cx, cy;
        protected Vector order = new Vector();      
         public static void main(String[] args)
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ResizeJPanels().GroupJLabels());
            f.setSize(600,700);
            f.setLocation(200,200);
            f.setVisible(true);
         private MouseListener ml = new MouseAdapter() {  
              public void mousePressed(MouseEvent e) {   
                   Point p = e.getPoint();      
                   JPanel jp = new JPanel();
                   jp.setLayout(null);
                   Component[] c = ((JPanel)e.getSource()).getComponents();
                   System.out.println("c.length = " + c.length);      
                   for(int j = 0; j < c.length; j++) {        
                        if(c[j].getBounds().contains(p)) {     
                             if(selectedJPanel != null && selectedJPanel != (JPanel)c[j])
                                  selectedJPanel.setBorder(BorderFactory.createEtchedBorder());
                             selectedJPanel = (JPanel)c[j];            
                             selectedJPanel.setBorder(BorderFactory.createLineBorder(Color.green));
                             break;             
                        add(jp);
                        revalidate();
    public JPanel GroupJLabels ()
              setLayout(null);
            addLabels();
            label1.setBounds( 125,  150, 125, 25);
            label2.setBounds(425,  150, 125, 25);
            label3.setBounds( 125, 575, 125, 25);
            label4.setBounds(425, 575, 125, 25);
            //add(btn);
            btn.setBounds(10, 5, 205, 25);
                add(btn);
           determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
             ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     ComponentMover mover = new ComponentMover();
                           addMouseListener(mover);
                           addMouseMotionListener(mover);
              btn.addActionListener(lst);
              addMouseListener(ml); 
              return this;
        public void paintComponent(final Graphics g)
             super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
             Point[] p;
            g2.setStroke(new BasicStroke(4f));
           for(int i = 0 ; i < order.size()-1; i++) {
                JPanel l1 = (JPanel)order.elementAt(i);
                JPanel l2 = (JPanel)order.elementAt(i+1);
                p = getCenterPoints(l1, l2);
                g2.setColor(Color.black);
               // g2.draw(new Line2D.Double(p[0], p[1]));            
        private Point[] getCenterPoints(Component c1, Component c2)
            Point
                p1 = new Point(),
                p2 = new Point();
            Rectangle
                r1 = c1.getBounds(),
                r2 = c2.getBounds();
                 p1.x = r1.x + r1.width/2;
                 p1.y = r1.y + r1.height/2;
                 p2.x = r2.x + r2.width/2;
                 p2.y = r2.y + r2.height/2;
            return new Point[] {p1, p2};
        private void determineCenterOfComponents()
            int
                xMin = Integer.MAX_VALUE,
                yMin = Integer.MAX_VALUE,
                xMax = 0,
                yMax = 0;
            for(int i = 0; i < labels.length; i++)
                Rectangle r = labels.getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < panels.length; i++)
    Rectangle r = panels[i].getBounds();
    if(r.contains(p))
    selectedJPanel = panels[i];
    order.addElement(panels[i]);
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    repaint(); //added
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedJPanel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedJPanel.setBounds(r.x, r.y, r.width, r.height);
    //determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
    jl.setBackground(Color.green);
    jl.setOpaque(true);
              jl.setFont(new Font("Helvetica", Font.BOLD, 18));
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    panels = new JPanel[]{jp};
              jp.setBorder(new LineBorder(Color.black, 3, false));
    jp.setPreferredSize(new Dimension(400,200));
    jp.add(jl, BorderLayout.NORTH);
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    jp.add(labels[i], BorderLayout.CENTER);
    jp.setBounds(100, 100, 400,200);
    add(jp);

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.MouseInputAdapter;
    public class Resizing extends JPanel {
        public Resizing() {
            super(null);
            addPanel();
            PanelControlAdapter control = new PanelControlAdapter(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        private void addPanel() {
            JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
            jl.setBackground(Color.green);
            jl.setOpaque(true);
            jl.setFont(new Font("Helvetica", Font.BOLD, 18));
            JPanel jp = new JPanel();
            jp.setLayout(new BorderLayout());
            jp.setBorder(new LineBorder(Color.black, 3, false));
            jp.add(jl, BorderLayout.NORTH);
            jp.setBounds(50,50,400,200);
            add(jp);
        public static void main(String[] args) {
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Resizing());
            f.setSize(500,400);
            f.setLocation(100,100);
            f.setVisible(true);
    class PanelControlAdapter extends MouseInputAdapter {
        Resizing host;
        Component selectedComponent;
        LineBorder black;
        LineBorder green;
        Point offset = new Point();
        Point start = new Point();
        boolean dragging = false;
        boolean resizing = false;
        public PanelControlAdapter(Resizing r) {
            host = r;
            black = new LineBorder(Color.black, 3, false);
            green = new LineBorder(Color.green, 3, false);
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            boolean hovering = false;
            Component c = host.getComponent(0);
            Rectangle r = c.getBounds();
            if(r.contains(p)) {
                hovering = true;
                if(selectedComponent != c) {
                    if(selectedComponent != null)  // reset
                        ((JComponent)selectedComponent).setBorder(black);
                    selectedComponent = c;
                    ((JComponent)selectedComponent).setBorder(green);
                if(overBorder(p))
                    setCursor(p);
                else if(selectedComponent.getCursor() != Cursor.getDefaultCursor())
                    selectedComponent.setCursor(Cursor.getDefaultCursor());
            if(!hovering && selectedComponent != null) {
                ((JComponent)selectedComponent).setBorder(black);
                selectedComponent = null;
        private boolean overBorder(Point p) {
            Rectangle r = selectedComponent.getBounds();
            JComponent target = (JComponent)selectedComponent;
            Insets insets = target.getBorder().getBorderInsets(target);
            // Assume uniform border insets.
            r.grow(-insets.left, -insets.top);
            return !r.contains(p);
        private void setCursor(Point p) {
            JComponent target = (JComponent)selectedComponent;
            AbstractBorder border = (AbstractBorder)target.getBorder();
            Rectangle r = target.getBounds();
            Rectangle ir = border.getInteriorRectangle(target, r.x, r.y, r.width, r.height);
            int outcode = ir.outcode(p.x, p.y);
            Cursor cursor;
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_TOP + Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT + Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM + Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT + Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
                    break;
                default:
                    cursor = Cursor.getDefaultCursor();
            selectedComponent.setCursor(cursor);
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(selectedComponent != null) {
                Rectangle r = selectedComponent.getBounds();
                if(selectedComponent.getCursor() == Cursor.getDefaultCursor()) {
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                } else {
                    start = p;
                    resizing = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
            resizing = false;
        public void mouseDragged(MouseEvent e) {
            Point p = e.getPoint();
            if(dragging || resizing) {
                Rectangle r = selectedComponent.getBounds();
                if(dragging) {
                    r.x = p.x - offset.x;
                    r.y = p.y - offset.y;
                    selectedComponent.setLocation(r.x, r.y);
                } else if(resizing) {
                    int type = selectedComponent.getCursor().getType();
                    switch(type) {
                        case Cursor.N_RESIZE_CURSOR:
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.NW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.W_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            break;
                        case Cursor.SW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.S_RESIZE_CURSOR:
                            r.height += p.y - start.y;
                            break;
                        case Cursor.SE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.E_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            break;
                        case Cursor.NE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        default:
                            System.out.println("Unexpected resize type: " + type);
                    selectedComponent.setBounds(r.x, r.y, r.width, r.height);
                    start = p;
    }

Maybe you are looking for