Resizing JFrames and JPanels !!!

Hi Experts,
I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
Plese guide me, how should i do this ...
Thanknig Java Community,
Dhwanit Shah

Hey there, thanx for your kind intereset.
Here is sample code .
In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
import java.awt.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;
public class FramePanel extends JFrame {
JPanel contentPane;
GridBagLayout gridBagLayout1 = new GridBagLayout();
public FramePanel() {
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
public static void main(String[] args) {
FramePanel framePanel = new FramePanel();
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(gridBagLayout1);
this.setSize(new Dimension(296, 284));
this.setTitle("Frame and Panel Together");
MyPanel myPanel = new MyPanel();
this.getContentPane().add(myPanel);
this.setVisible(true);
class MyPanel extends JPanel {
public MyPanel() {
this.setSize(200,200);
this.setLayout(new FlowLayout());
this.setBackground(Color.black);
this.setVisible(true);
this.add(new JButton("Dhwanit Shah"));
I think i might explained my problem
Dhwanit Shah
[email protected]

Similar Messages

  • Inserting a Gui program using JFrames and JPanel

    I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?

    whatever is in the frame's contentPane now, you add to a separate JPanel.
    you also add your chat stuff to the separate panel
    the separate panel is added to the frame as the content pane

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Jframes and jpanel

    hi, can anyone help me to create a jframe with two panels on it.

    [http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]

  • How to ZOOM the JFrame and its components ?

    Hi
    I could not find any solution/suggestions for this, so I am asking help.
    I am adding multiple components (JLables, JtextFields and a JTable) in to Jpanel(s) and to a JFrame window and I want to add Zoom (+ or - ) functions.
    I don't want to take each and every component from JFrame/ JPanel(s) and resize or repaint.
    Is there any way, that you can increase and decrease the whole JFrame and JPanel's view so that the components, which are been added to them, look like their sizes are also increased / decreased?
    Any suggestions or help would be appreciated.
    Thanks.
    Regards,
    Vally.

    ok...
    god bless the "GlassPane"
    you can take a snapShot of your frame...
    draw it on your glassPane..
    and just use your glassPane
    to paint the image with the requested size...
    in this approach you cant press a button and to things..
    shay

  • Beginners Questions about Multiple JPanels in JFrame and event handling

    I am a newbie with SWING, and even a newerbie in Event Handling. So here goes.
    I am writing a maze program. I am placing a maze JPanel (MazePanel) at the center of a JFrame, and a JPanel of buttons (ButtonPanel) on the SOUTH pane. I want the buttons to be able to re-randomize the maze, solve the maze, and also ouput statistics (for percolation theory purposes). I have the backbone all done already, I am just creating the GUI now. I am just figuring out EventHandlers and such through the tutorials, but I have a question. I am adding an ActionListener to the buttons which are on the ButtonPanel which are on JFrame (SOUTH) Panel. But who do I make the ActionListener--Basically the one doing the work when the button is pressed. Do I make the JFrame the ActionListener or the MazePanel the ActionListener. I need something which has access to the maze data (the backbone), and which can call the Maze.randomize() function. I'm trying to make a good design and not just slop too.
    Also I was wondering if I do this
    JButton.addActionListener(MazePanel), and lets say public MazePanel implments ActionListenerdoesn't adding this whole big object to another object (namely the button actionlistener) seem really inefficient? And how does something that is nested in a JPanel on JFrame x get information from something nested in another JPanel on a JFrame x.
    Basically how is the Buttons going to talk to the maze when the maze is so far away?

    I'm not an expert, but here's what I'd do....
    You already have your business logic (the Maze classes), you said. I'm assuming you have some kind of public interface to this business logic. I would create a new class like "MazeGui" that extends JFrame, and then create the GUI using this class. Add buttons and panels as needed to get it to look the way you want. Then for each button that does a specific thing, add an anonymous ActionListener class to it and put whatever code you need inside the ActionListener that accesses the business logic classes and does what it needs to.
    This is the idea, though my code is totally unchecked and won't compile:
    import deadseasquirrels.mazestuff.*;
    public class MazeGui extends JFrame {
      JPanel buttonPanel = new JPanel();
      JPanel mazePanel = new JPanel();
      JButton randomizeB = new JButton();
      JButton solveB = new JButton();
      JButton statsB = new JButton();
      // create instanc(es) of your Maze business logic class(es)
      myMaze = new MazeClass();
      // add the components to the MazeGui content pane
      Component cp = getContentPane();
      cp.add(); // this doesn't do anything, but in your code you'd add
                // all of your components to the MazeGui's contentpane
      randomizeB.addActionListener(new ActionListener {
        void actionPerformed() {
          Maze newMaze = myMaze.getRandomMazeLayout();
          mazePanel.setContents(newMaze); // this is not a real method!
                                          // it's just to give you the idea
                                          // of how to manipulate the JPanel
                                          // representing your Maze diagram,
                                          // you will probably be changing a
                                          // subcomponent of the JPanel
      solveB.addActionListener(new ActionListener {
        void actionPerformed() {
          Solution mySolution = myMaze.getSolution();
          mazePanel.setContents(mySolution); // again, this is not a real
                                             // method but it shows you how
                                             // the ActionListener can
                                             // access your GUI
      // repeat with any other buttons you need
      public static void main(String[] args) {
        MazeGui mg = new MazeGui();
        mg.setVisible(true);
        // etc...
    }

  • JFram or Jpanel maximum size

    How should I set maximum and minimum size of JFrame (or JPanel using BorderLayout) ? Please note setPreferredSize() and setMaximumSize() are not effective.
    Thanks

    You can't set the min/max size of a JPanel in a BorderLayout.
    You can't directly set the min/max size of a JFrame, but you can add a ComponentListener the the JFrame and resize the JFrame when it exceeds you specified sizes.
    Search the forum using "+maximum +addcomponentlistener".
    Of course since this is a Swing question, you should be searching the Swing forum.

  • JFrame or JPanel

    Hi,
    I am new to Java.
    I am reading the Java materials. Sometimes they use JFrame and
    sometimes they use JPanel.
    Can anyone tell me in which situation they will be used ?
    Many thanks in advance.
    Ivan

    There's also the issue of LayoutManagers.
    Each Container has a default LayoutManager which is used to arrange the components within the Container.
    This behavior can be changed with the setLayout() method.
    Often times, a single JFrame will "contain" several JPanels - each with a specific layout for its Components -
    and then the panels are arranged according to the frame's LayoutManager.

  • Enlarge JFrame and its components properties  proportionally

    Hi,
    We have a simple JFrame � Container - uses Flow Layout and has got Buttons, Text Fields� All of them are using Java�s default fonts, sizes..�
    And we want to increase or enlarge all of the JFrame and its sub components properties proportionally (especially Font�.) like in for example MS-Word.
    In the Ms-Word, there is ZOOM option in the Standard tool bar menu. If you set zoom to 150%, the font is automatically increases. And if you set it to 100% the font sets back to normal. And if the window is not enough to fit, it adds the scroll bars.
    For example, if we increase the Labels Font, the height of that component also should increase proportionally. So the Frame also should increase.
    How could we achieve this sort of functionality ( i.e. Proportionally increasing the component�s properties ) in Swing?
    I believe it is hard to set/adjust the all of the Frame�s components properties (I.e. Height, Font�) proportionally by using the Component listeners.
    (Another example, you might have noticed that the Frame�s Font, hight,width �sizes are proportionally bigger in Systems screen�s 800 by 600 pixels mode compare with 1024 by 768 pixels mode. May be this is windows feature. But we are looking at achieving the same sort of feature)
    Any help or thoughts would be appreciated.
    Thanks in advance.
    Vally.

    Here is a working sample:
    package ui_graphics;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.LayoutManager;
    import java.util.Arrays;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerListModel;
    import javax.swing.SpinnerModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class ZoomableFrameTest {
       private ZoomablePanel zoomPanel;
       private JLabel label;
       public ZoomableFrameTest() {
          label = new JLabel("Essai pour le zoom");
          label.setBounds(0,0,200,16);
          zoomPanel = new ZoomablePanel();
          zoomPanel.add(label);
          JFrame frame= new JFrame("Zoom test");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(getZoomSpinner(), BorderLayout.NORTH);
          frame.getContentPane().add(zoomPanel, BorderLayout.CENTER);
          frame.pack();
          frame.setVisible(true);
       public static void main(String[] args) {
          new ZoomableFrameTest();
       public JSpinner getZoomSpinner() {
          String[] zoomValues = { "50", "100", "150" };
          SpinnerModel model = new SpinnerListModel(Arrays.asList(zoomValues));
          final JSpinner spZoom = new JSpinner(model);
          Dimension dim = new Dimension(60, 22);
          spZoom.setMinimumSize(dim);
          spZoom.setPreferredSize(dim);
          spZoom.setMaximumSize(dim);
          spZoom.setFocusable(false);
          spZoom.addChangeListener(new ChangeListener() {
             public void stateChanged(ChangeEvent e) {
                // R�cup�re le facteur d'�chelle
                int factor = Integer.parseInt((String)spZoom.getValue());
                setScaleFactor(factor);
          spZoom.setValue("100");
          return spZoom;
       private void setScaleFactor(int factor) {
          zoomPanel.setZoomFactor(factor);
    class ZoomablePanel extends JPanel {
       private int zoomFactor;
       public ZoomablePanel() {
          super(null);
       public void setZoomFactor(int factor) {
          this.zoomFactor = factor;
          if (this.isShowing()) this.repaint();
       public void paint(Graphics g) {
          super.paintComponent(g);
          double d = zoomFactor / 100d;
          Graphics2D g2 =(Graphics2D)g;
          g2.scale(d, d);
          super.paint(g2);
    }

  • Best recommendataion to work with one JFrame & Multiple Jpanels(or Windows)

    Hi all,
    I am a bit new(bie) to Java and Gui but not new to programming.
    I need to write an application in using Java. The Current editor I use is Netbeans.
    I have a rough idea on how to write this apps, but I would like to confirm if my idea is applicable to such application (from a performance and feasibility standpoint).
    The main idea for this application is to have multiple forms that users would populate, and the values entered will be stored in a Database.
    I had plan to use only one main Window (JFrame), and no MDI, no multiple Java windows.
    My plan was:
    -     Create the main form (JFrame) with menus, once the application is loaded, I will check if a database connection is available otherwise open a Jpanel to input database settings (which can be started from the menu).
    -     All menus and application/company settings would be set in the main form
    -     All features available in the Jpanel would be in a separate class for clarity/lisibility of my code. For instance : user settings would be a separate jpanel class; database settings is a new jpanel class
    -     Each Jpanel class would be stored in a separate java/class file.
    Here is my test example for now (file MainForm.java) :
    import javax.swing.*;
    public class MainForm extends JFrame {
        /* Initializing a few variables */
        String databaseServer = null;
        String databaseUserName = null;
        String databasePassword = null;
        /** Creates new form MainForm */
        public MainForm() {
            /* Initializing menus */
            initComponents();
           /* starting a new instance of database configuration */
            DbPanel test = new DbPanel();
        /* Initialization menu and graphical components */
        private void initComponents () {
            JMenuBar BarMenu;
            JMenu MenuConfiguration;
    /* �.*/
         BarMenu.add(MenuConfiguration);
         setJMenuBar(BarMenu);
         pack();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainForm().setVisible(true);
    } Here is my DBpanel class (file MainForm.java) :
    public class DbPanel extends javax.swing.JPanel {
        /** Creates new form DbPanel */
        public DbPanel() {
            initComponents();
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            java.awt.Button buttonClose;
            java.awt.Button buttonSave;
            java.awt.TextField dbName;
    /* � */
           gridBagConstraints.ipadx = 100;
            gridBagConstraints.insets = new java.awt.Insets(0, 21, 0, 21);
            add(dbPassword, gridBagConstraints);
    // </editor-fold>   
    }Here are then my questions:
    -     Would you think that is a practical plan to write such application?
    -     Once I display a Jpanel form and I close it (for instance myJpanel.setVisible=false), will the memory be freed?
    -     Is there any other way to remove entire a JPanel from RAM?
    -     How can I call my �external� Jpanel ? I have designed one Jpanel class for testing but I was not able to display it when I created the new instance of that class.
    -     Is there any other alternative to Jpanel for this application? I was thinking about opening a new window within my Jframe. But, ideally it would be best that multiple windows are not opened simultaneously.
    Thanks for your input

    I was thinking about this but requirements are the
    application development cost should be reduced to the
    minimum.
    thus one desktop application and one database
    server.Application development cost? If you are being paid to do this, the bulk of the cost will be your hourly rate times the number of hours it takes you to do it. Thus you want to minimize the number of hours it takes you to do it. Assuming that the cost of your learning Java is going to be charged to this project, it might well be a good idea for you to do it in a language you already know. Or one where it's easy to develop this sort of application.

  • Disposing a jframe, and freeing up memory

    Greetings,
    I hope this is the proper forum for memory issues.
    I have an enterprise database reporting desktop application that I am developing. The GUI application reports on a huge set of data that results in the app taking up to 125 MB worth of memory when fully loaded. There are moments in using the application that all of the data will need to be refreshed entirely, and the JFrame that reports it be reloaded in the process.
    I am wondering how to dispose the JFrame and release all of the data associated with it. I use NetBeans to develop my GUI, and so all of the data that is needed for the JFrame is a class variable of the JFrame (so the data can be accessed as it is needed). But, when the frame is disposed, I no longer need anything associated with the JFrame that gets disposed. The Javadoc for Window.dispose() seems to imply that not all of the resources will be released and GC'd when you call dispose, because it says "The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show." which to me says that the data is being remembered and not collected by the GC.
    Anyone have any tips for GUIs and memory management? It seems like any GUI app could get pretty large pretty fast if there's no way to release the data associated with the GUI.
    Here's the code I've tested that doesn't seem to be releasing the memory (stress tests of closing and re-opening the window multiple times shows the java.exe process eating more and more memory):
        public void reset(){
            this.dispose();
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PartsDashboard(partNum, dateFrom, dateTo);
            try{
                this.finalize();
            } catch (Throwable t){
                t.printStackTrace();
        }Thanks in advance.

    Three things you can always count on in life: Death, Taxes, and AndrewThompson64 telling people to post an SSCCE. =)
    Just poking fun.
    Anyways, this problem has gone from probably-should-deal-with-soon to critical issue. Here is the SSCCE to illustrate the problem. NOTE: My client is using Windows and I am using Windows, so how this acts on Linux/Mac isn't important to me. Also, a few of my client's machines are not well equipped (512 MB RAM), so they have agreed to up their hardware a bit.
    But the big problem, on my end, is that disposed windows DO NOT free up resources once disposed. My program is very data-heavy. I have considered grabbing less data from the database but this would mean the program would have to go to the database more often. The ultimate dilemma of time vs space, essentially.
    To explain the SSCCE: There is a main window with a button. If you click the button, it launches another window with a String array that is 500,000 items large (to simulate a lot of data), and a JList to view those strings. Closing the data-heavy child window does not free up the memory that it uses, and if you launch a bunch of the child windows in the same program instance (close each child before launching a new one) then you will see the amount of memory piling up.
    Am I doing something wrong? Has anyone else experienced similar problems? Does anyone have suggestions? Thank you.
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    * @author Ryan
    public class MemoryLeak {
        public static void main(String[] args) {
            // Launch Base Frame
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BaseFrame().setVisible(true);
    class BaseFrame extends JFrame{
        public BaseFrame() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setPreferredSize(new Dimension(300,300));
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 5));
            JButton button = new JButton("Launch Data-Heavy Child");
            // JButton will launch Child Frame
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            // Notice no references to ChildFrame, period.
                            new ChildFrame().setVisible(true);
            panel.add(button);
            add(panel);
            pack();
    class ChildFrame extends JFrame{
        public ChildFrame() {
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setPreferredSize(new Dimension(300,600));
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            // Simulate lots of data.
            String[] dataArr = new String[500000];
            for(int i = 0; i < dataArr.length; i++) {
                dataArr[i] = "This is # " + i;
            // Something to display the data.
            JList list = new JList(dataArr);
            JScrollPane scrollPane = new JScrollPane(list);
            scrollPane.setPreferredSize(new Dimension(200, 550));
            panel.add(scrollPane);
            add(panel);
            pack();
    }

  • Disposing JFrame from JPanel

    Right, I suspect this has an easy solution, or maybe I have already happened on it, but I thought I'd best ask just in case.
    I have an application that creates a JFrame from another JFrame, with a JPanel internal to it. What I want to happen is for the JPanel to do its business in its paintComponent method, and then dispose of its parent JFrame (that's dispose - no System.exit(0)'s here please :) ).
    The only way I can see to do it is to pass a reference to the JFrame when the JPanel is created. But this seems to be a bit messy encapsulation-wise.
    Any comers?

    you could make the parent JFrame have a thread that checked the status of the child JFrame's JPanel every second or so and then close itself when the JPanel is finished doing whatever it is doing.

  • What's difference between JPanel.remove(); and JPanel = null

    nice day,
    how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null,
    1/ because if JPanel does not contain any static JComponents
    2/ or any reference to static objects,
    then works as well as JPanel.remove or JPanel = null,
    or what and why preferred to avoid some action (to avoid to remove or to avoid to null)

    mKorbel wrote:
    nice day,
    how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null, Remove the JPanel from the container it was part of and make sure you do not keep any references to it from your own classes. Don't make it any more difficult than it has to be.

  • How can i hide a JFrame and then Show it again in runtime

    How can i hide a JFrame and then Show it again in runtime??
    Please, please help me
    Its URGENT

    Here's even an example:
    import javax.swing.*;
    public class HideAndShow extends JFrame
         public HideAndShow()
              super("Hello");
              setSize(200, 200);
              setVisible(true);
              try
                   Thread.sleep(2000);
              } catch(InterruptedException e) {}
              setVisible(false);
              try
                   Thread.sleep(2000);
              } catch(InterruptedException e) {}
              setVisible(true);
         public static void main(String[] args)
              new HideAndShow();
    The JFrame will show, then hide, then show again. This is at runtime.

Maybe you are looking for

  • Runtime error in webdynpro for abap

    hi every one,     The ASSERT condition was violated. in webdynpro abap can any one help . im getting this error when im inserting customer master in KNA1 and also when i m giving name in customer name field its give error as Unable to interpret RA as

  • Flex 3 downloads are dead links

    Hi, i noticed that Flex 3 sample download links are all dead links (both local and remote zip files are missing) some examples : localDownloadPath="NumericStepper/Sample-Adobe-NumericStepper.zip" downloadPath="http://www.adobe.com/devnet/flex/tourdef

  • Sales order - customer numbers

    hi all, in sales order creation, who is involved in certain calculations whether sold-to or ship-to party if both are specified. if atleast one is not specified who will be the other party whether implicitly it will consider the same party(which ever

  • Adjust front panel to screen size and re-position objects on different systems automatically

    Hello, i have designed a vi that contains 5 led's placed at the 4 corners and center of the front panel which occupies the entire screen. However, this vi is to be used on different systems having different screen sizes. But on every screen, i'll nee

  • Error While Importing DTD to XI

    Hi all, I have a DTD from cxml.org. While importing that DTD into the XI as external definitions, the message types couldn't be shown. Can anybody please suggest the reason? Any help will be appriciated. Kind regards, Kulwant