JFrame.DISPOSE_ON_CLOSE

Hey,
I was wondering what JFrame.DISPOSE_ON_CLOSE actually does?
I have a JFrame (called by a launcher JFrame) that I have set this to as I don't want to close the whole application.
I seem to be able to setVisible(true); on the JFrame after I have "DISPOSE_ON_CLOSE" it.
Does it just hide the JFrame? or does it clear it from memory and close completely, and what I'm setVisible(true); on is the properties of the closed JFrame?
Sorry if I'm speaking gibberish, and thanks in advance :)

this is taken from the API Docs for java.awt.Window on the dispose method where JFrame inherited from.
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.
The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Similar Messages

  • 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);
    }

  • Problem while encoding JPEG image from JFrame paintComponent in a servlet

    Hello!
    I m developing webapplication in which I made one servlet that calls JFrame developed by me, and then encoding into JPEG image to send response on client browser. I m working on NetBeans 5.5 and the same code runs well. But my hosting server is Linux and I m getting the following error:
    java.awt.HeadlessException:
    No X11 DISPLAY variable was set, but this program performed an operation which requires it.
         java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159)
         java.awt.Window.<init>(Window.java:406)
         java.awt.Frame.<init>(Frame.java:402)
         java.awt.Frame.<init>(Frame.java:367)
         javax.swing.JFrame.<init>(JFrame.java:163)
         pinkConfigBeans.pinkInfo.pinkModel.pinkChartsLib.PinkChartFrame.<init>(PinkChartFrame.java:36)
         pinkConfigBeans.pinkController.showLastDayRevenueChart.processRequest(showLastDayRevenueChart.java:77)
         pinkConfigBeans.pinkController.showLastDayRevenueChart.doGet(showLastDayRevenueChart.java:107)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.25 logs.
    I m building the application in NetBeans and when runs then it runs well, even while browsing from LAN. But when I place the web folder creted under buil directory of NetBeans in the Tomcat on Linux, then it gives above error.
    Under given is the servlet code raising exception
    response.setContentType("image/jpeg"); // Assign correct content-type
    ServletOutputStream out = response.getOutputStream();
    /* TODO GUI output on JFrame */
    PinkChartFrame pinkChartFrame;
    pinkChartFrame = new PinkChartFrame(ssnGUIAttrInfo.getXjFrame(), ssnGUIAttrInfo.getYjFrame(), headingText, xCordText, yCordText, totalRevenueDataList);
    pinkChartFrame.setTitle("[::]AMS MIS[::] Monthly Revenue Chart");
    pinkChartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //pinkChartFrame.setVisible(true);
    //pinkChartFrame.plotDataGUI();
    int width = 760;
    int height = 460;
    try {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    pinkChartFrame.pinkChartJPanel.paintComponent(g2);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(image);
    } catch (ImageFormatException ex) {
    ex.printStackTrace();
    response.sendRedirect("index.jsp");
    } catch (IOException ex) {
    ex.printStackTrace();
    response.sendRedirect("index.jsp");
    out.flush();
    Do resolve anybody!
    Edited by: pinkVag on Oct 15, 2007 10:19 PM

    >
    I m developing webapplication in which I made one servlet that calls JFrame developed by me, and then encoding into JPEG image to send response on client browser. I m working on NetBeans 5.5 and the same code runs well. But my hosting server is Linux and I m getting the following error:
    java.awt.HeadlessException: >That makes sense. It is saying that you cannot open a JFrame in an environment (the server) that does not support GUIs!
    To make this so it will work on the server, it will need to be recoded so that it uses the command line only - no GUI.
    What is it exactly that PinkChartFrame is generated an image of? What does it do? (OK probably 'generate a chart') But what APIs does it use (JFreeChart or such)?

  • Cant dispose a JFrame

    hi
    i'm having a problem with jFrame disposion. i have a login JDialog, that launches JFrame. After logoff - the same JDialog appears. And when i call JFrame again - i get 2 flashing frames, that are disabling/enabling one another, and swithing from one to another. after some accurate clicks in taskbar - forms stop flicker, but i still have 2 of them.
    then you may try to logoff and login again from one of them - and guess what - i get 4 flikering frames. dammit.
    how to completely dispose Frame?
    tryed everything in forums with keyword "dispose". no luck.
    many many many thanx.

    I presume your are calling frame.dispose() from your Dialog window, and not trying to be clever by calling it in your finalizer? Additionally, you could setframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  • JMenu/JFrame issue

    Ok, I can't figure out how to make an option in a menu popup a new JFrame instead of displaying some stupid text in a text box.
    menuItem2 = new JMenuItem("Inventory");
              menuItem2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
              menuItem2.getAccessibleContext().setAccessibleDescription("This does nothing for now");
              menu.add(menuItem2);That's just a tiny part...I need it to open the JFrame Inven if anybody knows how to do that.

    (post #2 - another disappeared into the ether)
    is this what you're trying to do?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(400,200);
        setSize(300,200);
        JMenu menu = new JMenu("Window");
        JMenuItem menuItem1 = new JMenuItem("Employees");
        JMenuItem menuItem2 = new JMenuItem("Inventory");
        menu.add(menuItem1);
        menu.add(menuItem2);
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);
        setJMenuBar(menuBar);
        getContentPane().add(new JTextArea(5,20));
        menuItem1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JFrame frame = new JFrame("Employee Frame");
            frame.setSize(200,100);
            frame.setLocation(100,500);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);}});
        menuItem2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JFrame frame = new JFrame("Inventory Frame");
            frame.setSize(200,100);
            frame.setLocation(500,500);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);}});
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Getting a JFrame to display  from a JSP, remaining JSP code waits for frame

    Hello,
    I'm new to Java and just started using JSPs. My objective is to call a display window (from a JSP) that shows the user a list of project selections. Once the user has made their selections and clicked a Submit button, the display class captures the selected projects to the request object as an attribute and then closes the window. The next command in the jsp then forwards the request attribute to a controller. I'm having trouble getting the display window to show-the JSP seems to hang and then timeout. Is there code I'm missing to get the JSP to stop processing while it waits for the choices to be made in the JFrame?
    Below is the JSP code and the class I'm calling. I'm seeing all my debug System.out statements but no JFrame pops up. In the JFrame class, the line f.addWindowListener(... does the capture of user selections to the request attribute.
    Any help will be greatly appreciated!!
    JSP:
    <%@ page language="java" contentType="text/html;charset=UTF-8" import="com.plumtree.remote.portlet.*,edu.app.projects.*" %>
    <%
        request.setAttribute("action", "prefDisplay");
        request.setAttribute("orderby", "title");
        ServletContext jc = getServletContext();
        DualListBox dual = new DualListBox(request,(String)jc.getAttribute("db.driver"), (String)jc.getAttribute("db.connectionstring"),"title");
         JFrame f = dual.getFrame();
         f.setVisible(true);//expect code to stop here and display frame, waiting for the user to finish.
            //Debug code that tests if frame is visible at this point -came true though did not see Jframe displayed
         if(f.isShowing()){
         System.out.println("Jframe visible");}
           //Send to ProjectsController
          request.getRequestDispatcher("pc").forward(request, response);%>               ---------------------------------------------------------------------------------------------
    JFrame Class (below)
    -Sets up Frame and corresponding Dialog box
    -Populates Dialog box with options from a database call (for user selection)
    -Should wait for user input - Window close or Submit! to capture selection and dispose of Jframe
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.Frame;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.lang.reflect.InvocationTargetException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.SortedSet;
    import java.util.TreeSet;
    import javax.servlet.http.HttpServletRequest;
    import javax.swing.AbstractListModel;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    public class DualListBox extends JPanel {
      private static final long serialVersionUID = 1L;
      private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0);
      private static final String ADD_BUTTON_LABEL = "Add >>";
      private static final String REMOVE_BUTTON_LABEL = "<< Remove";
      private static final String DONE_BUTTON_LABEL = "Submit!";
      private static final String DEFAULT_SOURCE_CHOICE_LABEL = "Available Projects";
      private static final String DEFAULT_DEST_CHOICE_LABEL = "Your Selections";
      private String orderby, mydriver, connectionString;
      private JLabel sourceLabel;
      private JList sourceList;
      private SortedListModel sourceListModel;
      private JList destList;
      private String chosenprojects;
      private SortedListModel destListModel;
      private JLabel destLabel;
      private JButton addButton;
      private JButton removeButton;
      private JButton doneButton;
      private DatabaseHelper dh;
      protected HttpServletRequest request;
      protected JFrame f;
      protected JDialog jd;
      public DualListBox(HttpServletRequest req, String driver, String connection, String ordering) {
         System.out.println("In DualList Setup");
        request =req;
         orderby =ordering;
         connectionString = connection;
         mydriver = driver;
         f = new JFrame("Projects List Selector");     
         jd =new JDialog(f,true);
         jd.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         System.out.println("B4 initscreen");
        initScreen();
        System.out.println("After initscreen");
        String[] DBprojects = this.dbCall();
        System.out.println("After DB Call");
        this.addSourceElements( DBprojects );   
        System.out.println("Filled screen");
        jd.getContentPane().add(this, BorderLayout.CENTER);
        //f.getContentPane().add(jd, BorderLayout.CENTER);
        jd.setSize(800, 600);
        System.out.println("OK2");
        jd.setVisible(true);
        System.out.println("OK3");
        Runnable runner = new FrameShower(jd);
        EventQueue.invokeLater(runner);
      public String getSourceChoicesTitle() {
        return sourceLabel.getText();
      public String chosenprojects() {
             return chosenprojects;
      public JFrame getFrame() {
             return f;
      public void setSourceChoicesTitle(String newValue) {
        sourceLabel.setText(newValue);
      public String getDestinationChoicesTitle() {
        return destLabel.getText();
      public void setDestinationChoicesTitle(String newValue) {
        destLabel.setText(newValue);
      public void clearSourceListModel() {
        sourceListModel.clear();
      public void clearDestinationListModel() {
        destListModel.clear();
      public void addSourceElements(ListModel newValue) {
        fillListModel(sourceListModel, newValue);
      public void setSourceElements(ListModel newValue) {
        clearSourceListModel();
        addSourceElements(newValue);
      public void addDestinationElements(ListModel newValue) {
        fillListModel(destListModel, newValue);
      private String[] dbCall(){
             if(dh==null)
                  dh = new DatabaseHelper(mydriver, connectionString);
              PreparedStatement ps = null;
              ResultSet rs = null;
              ArrayList<String>children = new ArrayList<String>();
              ArrayList<String[]>tree =new ArrayList<String[]>();
              if(orderby==null || orderby.equals("")){
                   orderby ="region";
              String query = "select title,id from projects";// order by " + orderby;
              System.out.println(query);
              try {
                   Connection conn =dh.getConnection();
                   ps = conn.prepareStatement(query);
                   rs = ps.executeQuery();
                   while (rs.next()) {
                        children.add(new String(rs.getString(1)));
                        System.out.println(rs.getString(1));
                        tree.add(new String[]{rs.getString(1),rs.getString(2)});
                   request.setAttribute("ResultTree",tree);
                   return (String[])children.toArray(new String[children.size()]);
              } catch (SQLException e) {
                   throw new RuntimeException(e);
              } finally {
                   try {
                        if (null != rs) rs.close();
                   } catch (SQLException e) {
                   try {
                        if (null != ps) ps.close();
                   } catch (SQLException e) {
      private void fillListModel(SortedListModel model, ListModel newValues) {
        int size = newValues.getSize();
        for (int i = 0; i < size; i++) {
          model.add(newValues.getElementAt(i));
      public void addSourceElements(Object newValue[]) {
        fillListModel(sourceListModel, newValue);
      public void setSourceElements(Object newValue[]) {
        clearSourceListModel();
        addSourceElements(newValue);
      public void addDestinationElements(Object newValue[]) {
        fillListModel(destListModel, newValue);
      private void fillListModel(SortedListModel model, Object newValues[]) {
        model.addAll(newValues);
      public Iterator sourceIterator() {
        return sourceListModel.iterator();
      public Iterator destinationIterator() {
        return destListModel.iterator();
      public void setSourceCellRenderer(ListCellRenderer newValue) {
        sourceList.setCellRenderer(newValue);
      public ListCellRenderer getSourceCellRenderer() {
        return sourceList.getCellRenderer();
      public void setDestinationCellRenderer(ListCellRenderer newValue) {
        destList.setCellRenderer(newValue);
      public ListCellRenderer getDestinationCellRenderer() {
        return destList.getCellRenderer();
      public void setVisibleRowCount(int newValue) {
        sourceList.setVisibleRowCount(newValue);
        destList.setVisibleRowCount(newValue);
      public int getVisibleRowCount() {
        return sourceList.getVisibleRowCount();
      public void setSelectionBackground(Color newValue) {
        sourceList.setSelectionBackground(newValue);
        destList.setSelectionBackground(newValue);
      public Color getSelectionBackground() {
        return sourceList.getSelectionBackground();
      public void setSelectionForeground(Color newValue) {
        sourceList.setSelectionForeground(newValue);
        destList.setSelectionForeground(newValue);
      public Color getSelectionForeground() {
        return sourceList.getSelectionForeground();
      public String getProjects(){
           return chosenprojects;
      private void clearSourceSelected() {
        Object selected[] = sourceList.getSelectedValues();
        for (int i = selected.length - 1; i >= 0; --i) {
          sourceListModel.removeElement(selected);
    sourceList.getSelectionModel().clearSelection();
    private void clearDestinationSelected() {
    Object selected[] = destList.getSelectedValues();
    for (int i = selected.length - 1; i >= 0; --i) {
    destListModel.removeElement(selected[i]);
    destList.getSelectionModel().clearSelection();
    private void initScreen() {
    setBorder(BorderFactory.createEtchedBorder());
    setLayout(new GridBagLayout());
    sourceLabel = new JLabel(DEFAULT_SOURCE_CHOICE_LABEL);
    sourceListModel = new SortedListModel();
    sourceList = new JList(sourceListModel);
    add(sourceLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0,
    GridBagConstraints.CENTER, GridBagConstraints.NONE,
    EMPTY_INSETS, 0, 0));
    add(new JScrollPane(sourceList), new GridBagConstraints(0, 1, 1, 5, .5,
    1, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
    EMPTY_INSETS, 0, 0));
    addButton = new JButton(ADD_BUTTON_LABEL);
    add(addButton, new GridBagConstraints(1, 2, 1, 2, 0, .25,
    GridBagConstraints.CENTER, GridBagConstraints.NONE,
    EMPTY_INSETS, 0, 0));
    addButton.addActionListener(new AddListener());
    removeButton = new JButton(REMOVE_BUTTON_LABEL);
    add(removeButton, new GridBagConstraints(1, 4, 1, 2, 0, .25,
    GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
    0, 5, 0, 5), 0, 0));
    removeButton.addActionListener(new RemoveListener());
    doneButton = new JButton(DONE_BUTTON_LABEL);
    add(doneButton, new GridBagConstraints(1, 6, 1, 2, 0, .25,
    GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
    0, 10, 0, 10), 0, 0));
    doneButton.addActionListener(new DoneListener());
    f.addWindowListener(new java.awt.event.WindowAdapter() {
         public void windowClosing(WindowEvent winEvt) {
              //could set to null here to force use of Done button only
         chosenprojects = destList.getSelectedValues().toString();
              request.setAttribute("ProjectIDs", destList.getSelectedValues().toString());
              System.exit(0);
    destLabel = new JLabel(DEFAULT_DEST_CHOICE_LABEL);
    destListModel = new SortedListModel();
    destList = new JList(destListModel);
    add(destLabel, new GridBagConstraints(2, 0, 1, 1, 0, 0,
    GridBagConstraints.CENTER, GridBagConstraints.NONE,
    EMPTY_INSETS, 0, 0));
    add(new JScrollPane(destList), new GridBagConstraints(2, 1, 1, 5, .5,
    1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
    EMPTY_INSETS, 0, 0));
    private class AddListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    Object selected[] = sourceList.getSelectedValues();
    addDestinationElements(selected);
    clearSourceSelected();
    private class RemoveListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    Object selected[] = destList.getSelectedValues();
    addSourceElements(selected);
    clearDestinationSelected();
    private class DoneListener implements ActionListener {
         public void actionPerformed(ActionEvent e) {
         chosenprojects = destList.getSelectedValues().toString();
         request.setAttribute("ProjectIDs", destList.getSelectedValues().toString());
         System.exit(0);      
    class FrameShower implements Runnable {
         final JDialog frame;
         public FrameShower(JDialog frame) {
              this.frame = frame;
         public void run() {
              System.out.println("B4 make visible");
              frame.setVisible(true);          
         System.out.println("Made screen visible");
    class SortedListModel extends AbstractListModel {
    private static final long serialVersionUID = 8777627817685130496L;
    SortedSet model;
    public SortedListModel() {
    model = new TreeSet();
    public int getSize() {
    return model.size();
    public Object getElementAt(int index) {
    return model.toArray()[index];
    public void add(Object element) {
    if (model.add(element)) {
    fireContentsChanged(this, 0, getSize());
    public void addAll(Object elements[]) {
    Collection c = Arrays.asList(elements);
    model.addAll(c);
    fireContentsChanged(this, 0, getSize());
    public void clear() {
    model.clear();
    fireContentsChanged(this, 0, getSize());
    public boolean contains(Object element) {
    return model.contains(element);
    public Object firstElement() {
    return model.first();
    public Iterator iterator() {
    return model.iterator();
    public Object lastElement() {
    return model.last();
    public boolean removeElement(Object element) {
    boolean removed = model.remove(element);
    if (removed) {
    fireContentsChanged(this, 0, getSize());
    return removed;
    }{code}
    Edited by: redm14A on Oct 10, 2007 11:34 AM
    Edited by: redm14A on Oct 10, 2007 11:37 AM
    Edited by: redm14A on Oct 10, 2007 11:40 AM
    Edited by: redm14A on Oct 10, 2007 11:45 AM
    Edited by: redm14A on Oct 10, 2007 11:47 AM

    redm14A wrote:
    Hmm, I was trying to avoid writing an applet. Seems my only other option then is to write a JSP that returns a javascript menu populated by options from a database call. Then I'd have the user click submit to send the options to another JSP that simply sets the request attribute and forwards to the controller. Will this be a sound alternative?
    Edited by: redm14A on Oct 10, 2007 12:29 PMSounds good to me.

  • 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();
    }

  • Custom JPanel moves inside JFrame when Jpanel.paintComponent(...) is called

    I have a custom JPanel (CompassCalculatorPanel) that is created, setup and placed within a custom JFrame (CompassCalcFrame). Calling the JFrame constructor sets this all up and makes the Frame show up. All is good with placement and drawing initially. Then when a user changes the spinner value (change the compass heading) it is supposed to redraw the arrow within the panel. It does this just fine, but on the repaint, and subsequent paints, the Panel ends up being placed in the upper left corner of the frame, rather than at the place I positioned it. I've tried saving the upper left corner placement coordinates and calling setBounds(...) before and after the paintComponent(...) method is called. This has no effect, the panel still resides at 0, 0.
    boldAny help that keeps the panel in place would be appreciated!*bold*
    I am opening a new CompassCalcFrame with the following code from another GUI application like this (but this works from an example program perspective):
    import com.vikingvirtual.flightsim.CompassCalcFrame;
    * @author madViking
    public class Main
        public static void main(String[] args)
            CompassCalcFrame CCF = new CompassCalcFrame();
    }The CompassCalcFrame.java code:
    package com.vikingvirtual.flightsim;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Insets;
    import java.awt.Point;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    * @author madViking
    public class CompassCalcFrame extends JFrame
        private CompassCalculatorPanel ccPanel;
        private JButton closeButton;
        private JLabel frameTitle;
        private JSeparator frameSeparator1;
        private JSpinner hdgSpinner;
        private JTextField neField;
        private JTextField eField;
        private JTextField seField;
        private JTextField sField;
        private JTextField swField;
        private JTextField wField;
        private JTextField nwField;
        private Point ccPanelPoint;
        public CompassCalcFrame()
            super ("Compass Heading Calculator");
            initComponents();
            this.setVisible(true);
            calculateAndDraw();
        private void initComponents()
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            this.setLayout(null);
            this.setBackground(Color.BLACK);
            this.setForeground(Color.BLACK);
            Container ccPane = this.getContentPane();
            Dimension panelDim = ccPane.getSize();
            Font buttonFont = new Font("Tahoma", 0, 12);
            Font compassFont = new Font("Digital-7", 0, 24);
            Font titleFont = new Font("Lucida Sans", 1, 14);
            frameTitle = new JLabel();
            frameTitle.setText("Compass Heading Calculator");
            frameTitle.setFont(titleFont);
            frameTitle.setForeground(Color.WHITE);
            closeButton = new JButton();
            closeButton.setText("Close");
            closeButton.setToolTipText("Click to close view");
            closeButton.setFont(buttonFont);
            closeButton.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt)
                                                                              {closeButtonActionPerformed(evt);}});
            hdgSpinner = new JSpinner();
            hdgSpinner.setFont(compassFont);
            hdgSpinner.setModel(new javax.swing.SpinnerNumberModel(0, 0, 359, 1));
            hdgSpinner.setToolTipText("Enter heading to see angles change");
            hdgSpinner.addChangeListener(new javax.swing.event.ChangeListener() {public void stateChanged(javax.swing.event.ChangeEvent evt)
                                                                                {hdgSpinnerStateChanged(evt);}});
            neField = new JTextField();
            neField.setBackground(Color.BLACK);
            neField.setEditable(false);
            neField.setFont(compassFont);
            neField.setForeground(Color.WHITE);
            neField.setHorizontalAlignment(JTextField.CENTER);
            neField.setBorder(null);
            eField = new JTextField();
            eField.setBackground(Color.BLACK);
            eField.setEditable(false);
            eField.setFont(compassFont);
            eField.setForeground(Color.WHITE);
            eField.setHorizontalAlignment(JTextField.CENTER);
            eField.setBorder(null);
            seField = new JTextField();
            seField.setBackground(Color.BLACK);
            seField.setEditable(false);
            seField.setFont(compassFont);
            seField.setForeground(Color.WHITE);
            seField.setHorizontalAlignment(JTextField.CENTER);
            seField.setBorder(null);
            sField = new JTextField();
            sField.setBackground(Color.BLACK);
            sField.setEditable(false);
            sField.setFont(compassFont);
            sField.setForeground(Color.WHITE);
            sField.setHorizontalAlignment(JTextField.CENTER);
            sField.setBorder(null);
            swField = new JTextField();
            swField.setBackground(Color.BLACK);
            swField.setEditable(false);
            swField.setFont(compassFont);
            swField.setForeground(Color.WHITE);
            swField.setHorizontalAlignment(JTextField.CENTER);
            swField.setBorder(null);
            wField = new JTextField();
            wField.setBackground(Color.BLACK);
            wField.setEditable(false);
            wField.setFont(compassFont);
            wField.setForeground(Color.WHITE);
            wField.setHorizontalAlignment(JTextField.CENTER);
            wField.setBorder(null);
            nwField = new JTextField();
            nwField.setBackground(Color.BLACK);
            nwField.setEditable(false);
            nwField.setFont(compassFont);
            nwField.setForeground(Color.WHITE);
            nwField.setHorizontalAlignment(JTextField.CENTER);
            nwField.setBorder(null);
            frameSeparator1 = new JSeparator();
            frameSeparator1.setForeground(Color.WHITE);
            frameSeparator1.setBackground(Color.BLACK);
            ccPanel = new CompassCalculatorPanel();
            // Add components to pane
            ccPane.add(frameTitle);
            ccPane.add(closeButton);
            ccPane.add(frameSeparator1);
            ccPane.add(nwField);
            ccPane.add(hdgSpinner);
            ccPane.add(neField);
            ccPane.add(wField);
            ccPane.add(ccPanel);
            ccPane.add(eField);
            ccPane.add(swField);
            ccPane.add(sField);
            ccPane.add(seField);
            // Begin Component Layout
            Insets paneInsets = ccPane.getInsets();
            Point P1 = new Point(0, 0);
            Point P2 = new Point(0, 0);
            Point P3 = new Point(0, 0);
            Dimension size = frameTitle.getPreferredSize();
            frameTitle.setBounds((5 + paneInsets.left), (5 + paneInsets.top), size.width, size.height);
            P1.setLocation((5 + paneInsets.left), (5 + paneInsets.top + size.height + 5));
            P2.setLocation((P1.x + size.width + 5), (paneInsets.top + 5));
            size = closeButton.getPreferredSize();
            closeButton.setBounds(P2.x, P2.y, size.width, size.height);
            frameSeparator1.setBounds(P1.x, P1.y, (panelDim.width - paneInsets.left - paneInsets.right), 10);
            P1.setLocation(P1.x, (P1.y + 10 + 5));
            P2.setLocation((P1.x + 50 + 75), P1.y);
            P3.setLocation((P1.x + 50 + 75 + 60 + 75), P1.y);
            nwField.setBounds(P1.x, P1.y, 50, 26);
            hdgSpinner.setBounds(P2.x, P2.y, 60, 26);
            neField.setBounds(P3.x, P3.y, 50, 26);
            P2.setLocation((P1.x + 50 + 5), (P1.y + 26 + 5));
            P1.setLocation(P1.x, (P1.y + 26 + 5 + 87));
            P3.setLocation((P1.x + 50 + 5 + 200 + 5), P1.y);
            wField.setBounds(P1.x, P1.y, 50, 26);
            ccPanel.setBounds(P2.x, P2.y, 200, 200);
            ccPanelPoint = new Point(P2.x, P2.y);
            eField.setBounds(P3.x, P3.y, 50, 26);
            P1.setLocation(P1.x, (P1.y + 26 + 87 + 5));
            P2.setLocation((P1.x + 50 + 80), P1.y);
            P3.setLocation((P1.x + 50 + 80 + 50 + 80), P1.y);
            swField.setBounds(P1.x, P1.y, 50, 26);
            sField.setBounds(P2.x, P2.y, 50, 26);
            seField.setBounds(P3.x, P3.y, 50, 26);
            // End with Frame sizing
            Dimension frameDim = new Dimension((paneInsets.left + 5 + 50 + 5 + 200 + 5 + 50 + 5 + paneInsets.right + 10), (P1.y + 26 + 5 + paneInsets.bottom + 40));
            this.setPreferredSize(frameDim);
            this.setSize(frameDim);
            //this.setSize((paneInsets.left + 5 + 50 + 5 + 200 + 5 + 50 + 5 + paneInsets.right), (P1.y + 26 + 5 + paneInsets.bottom));
        private void closeButtonActionPerformed(java.awt.event.ActionEvent evt)
            this.dispose();
        private void hdgSpinnerStateChanged(javax.swing.event.ChangeEvent evt)
            calculateAndDraw();
        private void calculateAndDraw()
            int angle = (Integer)hdgSpinner.getValue();
            int[] headings = new int[7];
            int addAngle = 45;
            for (int i = 0; i < 7; i++)
                headings[i] = angle + addAngle;
                if (headings[i] >= 360)
                    headings[i] -= 360;
                addAngle += 45;
            neField.setText(String.valueOf(headings[0]));
            eField.setText(String.valueOf(headings[1]));
            seField.setText(String.valueOf(headings[2]));
            sField.setText(String.valueOf(headings[3]));
            swField.setText(String.valueOf(headings[4]));
            wField.setText(String.valueOf(headings[5]));
            nwField.setText(String.valueOf(headings[6]));
            ccPanel.paintComponent(this.getGraphics(), angle);
            ccPanel.setBounds(ccPanelPoint.x, ccPanelPoint.y, 200, 200);
            //ccPanel.repaint(this.getGraphics(), angle);
    }The CompassCalculatorPanel.java code:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package com.vikingvirtual.flightsim;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Stroke;
    * @author madViking
    public class CompassCalculatorPanel extends javax.swing.JPanel
        private int xCent;
        private int yCent;
        public CompassCalculatorPanel()
            super();
        @Override
        public void paintComponent(Graphics g)
            paintComponent(g, 0);
        public void repaint(Graphics g, int angle)
            paintComponent(g, angle);
        public void paintComponent(Graphics g, int angle)
            super.paintComponent(g);
            Dimension panelDim = this.getSize();
            xCent = (panelDim.width / 2);
            yCent = (panelDim.height / 2);
            float[] dashArray = {8.0f};
            Graphics2D g2D = (Graphics2D)g;
            g2D.setColor(new Color(53, 153, 0));
            g2D.fillRect(0, 0, panelDim.width, panelDim.height);
            BasicStroke hdgLine = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
            BasicStroke northLine = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10.0f, dashArray, 0.0f);
            Stroke stdStroke = g2D.getStroke();
            // Setup Heading Arrow Points
            Point hdgBottom = new Point(xCent, panelDim.height - 15);
            Point hdgTop = new Point(xCent, 15);
            Point ltHdgArr = new Point(xCent - 10, 20);
            Point rtHdgArr = new Point(xCent + 10, 20);
            // Setup North Arrow Points
            Point nthBottom = new Point(xCent, panelDim.height - 15);
            Point nthTop = new Point(xCent, 15);
            Point ltNthArr = new Point(xCent - 8, 20);
            Point rtNthArr = new Point(xCent + 8, 20);
            // Rotate North Arrow Points
            nthBottom = rotatePoint(nthBottom, (0 - angle), true);
            nthTop = rotatePoint(nthTop, (0 - angle), true);
            ltNthArr = rotatePoint(ltNthArr, (0 - angle), true);
            rtNthArr = rotatePoint(rtNthArr, (0 - angle), true);
            // Draw Heading Line
            g2D.setColor(Color.RED);
            g2D.setStroke(hdgLine);
            g2D.drawLine(hdgBottom.x, hdgBottom.y, hdgTop.x, hdgTop.y);
            g2D.drawLine(ltHdgArr.x, ltHdgArr.y, hdgTop.x, hdgTop.y);
            g2D.drawLine(rtHdgArr.x, rtHdgArr.y, hdgTop.x, hdgTop.y);
            g2D.setStroke(stdStroke);
            // Draw North Line
            g2D.setColor(Color.WHITE);
            g2D.setStroke(northLine);
            g2D.drawLine(nthBottom.x, nthBottom.y, nthTop.x, nthTop.y);
            g2D.drawLine(ltNthArr.x, ltNthArr.y, nthTop.x, nthTop.y);
            g2D.drawLine(rtNthArr.x, rtNthArr.y, nthTop.x, nthTop.y);
            g2D.setStroke(stdStroke);
            // Draw circles
            g2D.setColor(Color.BLUE);
            g2D.setStroke(hdgLine);
            g2D.drawOval(5, 5, (panelDim.width - 10), (panelDim.height - 10));
            g2D.setStroke(stdStroke);
            g2D.fillOval((xCent - 2), (yCent - 2), 5, 5);
            g2D.setStroke(stdStroke);
        private Point rotatePoint(Point p, int angle, boolean centerRelative)
            double ix, iy;
            double hyp = 0.0;
            double degrees = 0.0;
            if (centerRelative == true)
                ix = (double)(p.x - xCent);
                iy = (double)((p.y - yCent)*-1);
            else
                ix = (double)p.x;
                iy = (double)p.y;
            if (ix == 0)
                ix = 1;
            hyp = Math.sqrt((Math.pow(ix, 2)) + (Math.pow(iy, 2)));
            if ((ix >= 0) && (iy >= 0))
                degrees = Math.toDegrees(Math.atan(ix/iy));
            else if((ix >= 0) && (iy < 0))
                degrees = Math.abs(Math.toDegrees(Math.atan(iy/ix)));
                degrees = degrees + 90.0;
            else if ((ix < 0) && (iy < 0))
                degrees = Math.toDegrees(Math.atan(ix/iy));
                degrees = degrees + 180.0;
            else if ((ix < 0) && (iy >= 0))
                degrees = Math.abs(Math.toDegrees(Math.atan(iy/ix)));
                degrees = degrees + 270.0;
            degrees = degrees + angle;
            if (degrees >= 360)
                degrees = degrees - 360;
            if (degrees < 0)
                degrees = degrees + 360;
            double interX = Math.sin(Math.toRadians(degrees));
            double interY = Math.cos(Math.toRadians(degrees));
            interX = interX * hyp;
            interY = ((interY * hyp) * -1);
            if (centerRelative == true)
                p.x = xCent + (int)Math.floor(interX);
                p.y = yCent + (int)Math.floor(interY);
            else
                p.x = (int)Math.floor(interX);
                p.y = (int)Math.floor(interY);
            return p;
    }

    In response to the first couple of comments made about using Absolute positioning (layout null), I took a look at the page on doing layouts, which happens to be the link you sent. I read about each, and decided that a GridBag layout would be best. So I created a new class called CompassCalcGridBagFrame and set it all up using the same components, but with a Grid Bag layout. I encounter the exact same problem.
    Just FYI: I originally created this frame using the NetBeans (6.9.1) Frame form builder. By default that uses the Free Design setting, which creates group layouts for both vertical and horizontal spacing. This is where the problem first came to be. I next used the builder to create an absolute positioning frame, which had the same issue. That is when I started building my frames using code only - no NetBeans GUIs. This is where the absolute layout from scratch code started. Same effect. And now, I've created a Grid Bag layout from code, and same effect. There has to be something I'm missing overall, as this effects all of my different layout designs.
    The one thing from gimbal2's previous comment is, should I be using this custom panel within another panel? I am currently adding all of the components (and in Grid Bag, the GridBag layout) to the frame pane itself. Is that OK, or should I use a generic JPanel, and have the components all within that?
    Here is the code for the newest frame class (CompassCalcGridBagFrame):
    package com.vikingvirtual.flightsim;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Point;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    * @author madViking
    public class CompassCalcGridBagFrame extends JFrame
        private CompassCalculatorPanel ccPanel;
        private JButton closeButton;
        private JLabel frameTitle;
        private JSeparator frameSeparator1;
        private JSpinner hdgSpinner;
        private JTextField neField;
        private JTextField eField;
        private JTextField seField;
        private JTextField sField;
        private JTextField swField;
        private JTextField wField;
        private JTextField nwField;
        private Point ccPanelPoint;
        public CompassCalcGridBagFrame()
            super ("Compass Heading Calculator");
            initComponents();
            this.pack();
            this.setVisible(true);
            calculateAndDraw();
        private void initComponents()
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            Container ccPane = this.getContentPane();
            ccPane.setLayout(new GridBagLayout());
            ccPane.setBackground(Color.BLACK);
            ccPane.setForeground(Color.BLACK);
            Font buttonFont = new Font("Tahoma", 1, 12);
            Font compassFont = new Font("Digital-7", 0, 24);
            Font titleFont = new Font("Lucida Sans", 1, 14);
            frameTitle = new JLabel();
            frameTitle.setText("Compass Heading Calculator");
            frameTitle.setFont(titleFont);
            frameTitle.setHorizontalAlignment(JLabel.CENTER);
            frameTitle.setPreferredSize(new Dimension(220, 25));
            frameTitle.setForeground(Color.BLACK);
            closeButton = new JButton();
            closeButton.setText("Close");
            closeButton.setToolTipText("Click to close view");
            closeButton.setFont(buttonFont);
            closeButton.setPreferredSize(new Dimension(75, 25));
            closeButton.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt)
                                                                              {closeButtonActionPerformed(evt);}});
            hdgSpinner = new JSpinner();
            hdgSpinner.setFont(compassFont);
            hdgSpinner.setModel(new javax.swing.SpinnerNumberModel(0, -1, 360, 1));
            hdgSpinner.setToolTipText("Enter heading to see angles change");
            hdgSpinner.setPreferredSize(new Dimension(50, 26));
            hdgSpinner.addChangeListener(new javax.swing.event.ChangeListener() {public void stateChanged(javax.swing.event.ChangeEvent evt)
                                                                                {hdgSpinnerStateChanged(evt);}});
            neField = new JTextField();
            neField.setBackground(Color.BLACK);
            neField.setEditable(false);
            neField.setFont(compassFont);
            neField.setForeground(Color.WHITE);
            neField.setHorizontalAlignment(JTextField.CENTER);
            neField.setPreferredSize(new Dimension(50, 26));
            neField.setBorder(null);
            eField = new JTextField();
            eField.setBackground(Color.BLACK);
            eField.setEditable(false);
            eField.setFont(compassFont);
            eField.setForeground(Color.WHITE);
            eField.setHorizontalAlignment(JTextField.CENTER);
            eField.setPreferredSize(new Dimension(50, 26));
            eField.setBorder(null);
            seField = new JTextField();
            seField.setBackground(Color.BLACK);
            seField.setEditable(false);
            seField.setFont(compassFont);
            seField.setForeground(Color.WHITE);
            seField.setHorizontalAlignment(JTextField.CENTER);
            seField.setPreferredSize(new Dimension(50, 26));
            seField.setBorder(null);
            sField = new JTextField();
            sField.setBackground(Color.BLACK);
            sField.setEditable(false);
            sField.setFont(compassFont);
            sField.setForeground(Color.WHITE);
            sField.setHorizontalAlignment(JTextField.CENTER);
            sField.setPreferredSize(new Dimension(50, 26));
            sField.setBorder(null);
            swField = new JTextField();
            swField.setBackground(Color.BLACK);
            swField.setEditable(false);
            swField.setFont(compassFont);
            swField.setForeground(Color.WHITE);
            swField.setHorizontalAlignment(JTextField.CENTER);
            swField.setPreferredSize(new Dimension(50, 26));
            swField.setBorder(null);
            wField = new JTextField();
            wField.setBackground(Color.BLACK);
            wField.setEditable(false);
            wField.setFont(compassFont);
            wField.setForeground(Color.WHITE);
            wField.setHorizontalAlignment(JTextField.CENTER);
            wField.setPreferredSize(new Dimension(50, 26));
            wField.setBorder(null);
            nwField = new JTextField();
            nwField.setBackground(Color.BLACK);
            nwField.setEditable(false);
            nwField.setFont(compassFont);
            nwField.setForeground(Color.WHITE);
            nwField.setHorizontalAlignment(JTextField.CENTER);
            nwField.setPreferredSize(new Dimension(50, 26));
            nwField.setBorder(null);
            frameSeparator1 = new JSeparator();
            frameSeparator1.setForeground(Color.WHITE);
            frameSeparator1.setBackground(Color.BLACK);
            frameSeparator1.setPreferredSize(new Dimension(320, 10));
            ccPanel = new CompassCalculatorPanel();
            ccPanel.setPreferredSize(new Dimension(250, 250));
            GridBagConstraints gbc = new GridBagConstraints();
            // Begin Component Layout
            gbc.insets = new Insets(0, 0, 0, 0);
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.FIRST_LINE_START;
            ccPane.add(nwField, gbc);
            gbc.gridx = 1;
            gbc.gridy = 0;
            gbc.gridwidth = 2;
            gbc.gridheight = 1;
            gbc.weightx = 0.4;
            gbc.weighty = 0.4;
            gbc.anchor = GridBagConstraints.PAGE_START;
            ccPane.add(hdgSpinner, gbc);
            gbc.gridx = 3;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.FIRST_LINE_END;
            ccPane.add(neField, gbc);
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.LINE_START;
            ccPane.add(wField, gbc);
            gbc.gridx = 1;
            gbc.gridy = 1;
            gbc.gridwidth = 2;
            gbc.gridheight = 1;
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.anchor = GridBagConstraints.CENTER;
            ccPane.add(ccPanel, gbc);
            gbc.gridx = 3;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.LINE_END;
            ccPane.add(eField, gbc);
            gbc.gridx = 0;
            gbc.gridy = 2;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.LAST_LINE_START;
            ccPane.add(swField, gbc);
            gbc.gridx = 1;
            gbc.gridy = 2;
            gbc.gridwidth = 2;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.PAGE_END;
            ccPane.add(sField, gbc);
            gbc.gridx = 3;
            gbc.gridy = 2;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 0.5;
            gbc.weighty = 0.5;
            gbc.anchor = GridBagConstraints.LAST_LINE_END;
            ccPane.add(seField, gbc);
            gbc.gridx = 0;
            gbc.gridy = 3;
            gbc.gridwidth = 4;
            gbc.gridheight = 1;
            gbc.insets = new Insets(10, 5, 10, 5);
            gbc.weightx = 0.6;
            gbc.weighty = 0.6;
            gbc.anchor = GridBagConstraints.CENTER;
            ccPane.add(frameSeparator1, gbc);
            gbc.gridx = 1;
            gbc.gridy = 4;
            gbc.gridwidth = 2;
            gbc.gridheight = 1;
            gbc.anchor = GridBagConstraints.PAGE_START;
            ccPane.add(closeButton, gbc);
        private void closeButtonActionPerformed(java.awt.event.ActionEvent evt)
            this.dispose();
        private void hdgSpinnerStateChanged(javax.swing.event.ChangeEvent evt)
            calculateAndDraw();
        private void calculateAndDraw()
            int angle = (Integer)hdgSpinner.getValue();
            if (angle == -1)
                angle = 359;
            if (angle == 360)
                angle = 0;
            int[] headings = new int[7];
            int addAngle = 45;
            for (int i = 0; i < 7; i++)
                headings[i] = angle + addAngle;
                if (headings[i] >= 360)
                    headings[i] -= 360;
                addAngle += 45;
            hdgSpinner.setValue(Integer.valueOf(angle));
            neField.setText(String.valueOf(headings[0]));
            eField.setText(String.valueOf(headings[1]));
            seField.setText(String.valueOf(headings[2]));
            sField.setText(String.valueOf(headings[3]));
            swField.setText(String.valueOf(headings[4]));
            wField.setText(String.valueOf(headings[5]));
            nwField.setText(String.valueOf(headings[6]));
            ccPanel.paintComponent(this.getGraphics(), angle);
    }

  • Good practice to quit a JFrame

    I'm working on a Lab assignment. The instructions ask that I call System.exit() to close my JFrame from a "Quit" JButton's ActionListener. From what I've read it seems System.exit() simply kills the JVM. Is this really the proper way to close a JFrame?

    >
    I'm working on a Lab assignment. The instructions ask that I call System.exit() to close my JFrame from a "Quit" JButton's ActionListener. From what I've read it seems System.exit() simply kills the JVM. Is this really the proper way to close a JFrame?>I would say, no. If you call frame.setDefualtCloseOperation(JFrame.DISPOSE_ON_CLOSE), the app. will also end once the 'x' button is clicked, so long as ..
    1) There are no other GUI elements still visible (if they are, they will have a root component with its own thread).
    2) The code of the JFrame in question does not start any threads that are still running when it is closed.
    In fact, setting DISPOSE_ON_CLOSE helps us to check that there are no 'stray threads' still running when the frame is closed.

  • To close JFrame over a JDialog

    Hi,
    I am facing a slight problem. Say I have a code like under
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class abc extends JDialog implements ActionListener
         JPanel jp1 = new JPanel();
         JButton ok1 = new JButton("OK");
         public abc()
              this.getContentPane().setLayout(new BorderLayout());
              this.getContentPane().add(jp1,BorderLayout.CENTER);
              jp1.add(ok1);
              ok1.addActionListener(this);
              ok1.setActionCommand("ok1");
         public void actionPerformed(ActionEvent e)
              if (e.getActionCommand().equals("ok"))
                   System.out.println("Inside action performed method");
              else if (e.getActionCommand().equals("ok1"))
              JFrame j1 = new JFrame();
              JPanel jp2 = new JPanel();
              JButton btn1 = new JButton("OK");
              j1.getContentPane().add(jp2);
              jp2.add(btn1);     
              btn1.addActionListener(this);
              btn1.setActionCommand("ok");
              j1.show();
              j1.pack();
              j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String args[])
              abc ABC = new abc();
              ABC.show();
              ABC.pack();
    Now here in this code the line
    j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    closes the application itself. What I want is only the JFrame closes while the main Dialog stills stays in context.
    Can someone help with me how I can achieve the same.
    Regards.
    Anand

    There is a dialog it has a OK button. When I click the OK button a frame opens with another OK1 button in it.
    Now if I click the "x" sign of the frame it should be disposed without doing anything. frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)But if I click the OK1 button then also the frame should be disposed but
    after doing something other processing corresponding to the OK1 button.
    OK1.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent e) {
              // do processing
             frame.setVisible(false);
             // add this if you want to remove the frame from memory and recreate it when it needs to be opened
             frame.dispose();
    })>
    And within all this the parent(JDialog) and the child(JFrame) should be modal.A JFrame unfortunately cannot be modal, so you shd use a JDialog instead.
    ICE

  • JFrame remains blank until manually resized

    I have two jframes here, one works correctly, however the second one refuses to draw until I manually resize it.
    JFrame test = new JFrame("test");
         public BilliardGame (String title) {
              super(title);
              setSize(400,700);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setLocation(100,100);
              table = new ShuffleboardPanel(this);                             
              setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));                             
              add(table); //add the whole table view    
              JViewport view = new JViewport();
              view.setViewSize(new Dimension(199, 199));
              view.setViewPosition(new Point(0, 0));
              view.setView(new ShuffleboardPanel(test));
              test.setSize(200, 200);
              test.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              test.setVisible(true);
              test.setLayout(new BorderLayout());
              test.add(view, BorderLayout.CENTER);
              update();
         }ShuffleboardPanel is just a JPanel, no static variables between them. I just cant understand why this is happening.

    you could also try this
    //test.setVisible(true);//<---------move to after the component is added
    test.setLayout(new BorderLayout());
    test.add(view, BorderLayout.CENTER);
    test.setVisible(true);//<------move to here

  • JFrame titleBar resize ???

    hi,i got 2 file :
    satu.java
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    public class satu {
    * @param args
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    JFrame.setDefaultLookAndFeelDecorated(true);
    final JFrame appp = new JFrame("TEST ");
    appp.setSize(150,180);
    appp.setResizable(false);
    dua m = new dua(appp);
            m.init();
    appp.add(m,BorderLayout.CENTER);   
        appp.setVisible(true);
        //appp.setLocationRelativeTo(null);
    appp.addWindowListener(new WindowAdapter() {
       public void windowClosing(WindowEvent evt) {
                appp.setVisible(false);
                appp.dispose();
    }dua.java
    import java.applet.Applet;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class dua extends Applet implements ActionListener {
    * @param args
    JFrame myframe;
    public dua(JFrame sat){
    myframe = sat;
    public void init(){
    JButton x = new JButton("Big");
    x.addActionListener(this);
    add(x);
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    int newx = myframe.getWidth()+10;
    int newy = myframe.getHeight()+10;
    myframe.setTitle("X = "+newx+" Y = "+newy);
    myframe.setSize(newx,newy);
    the problem is when i clicked the button,the titlebar doesnt resize...what should i add to resize the title bar too ?
    thanks.

    BACK !!! You have to validate parent frame. This works fine:
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.applet.Applet;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class satu {
        public static void main(String[] args) {
            JFrame.setDefaultLookAndFeelDecorated(true);
            final JFrame appp = new JFrame("TEST ");
            appp.setSize(150,180);
            appp.setResizable(false);
            dua m = new dua(appp);
            m.init();
            appp.add(m,BorderLayout.CENTER);
            appp.setVisible(true);
            appp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    class dua extends Applet implements ActionListener {
        JFrame myframe;
        public dua(JFrame sat){
            myframe = sat;
        public void init(){
            JButton x = new JButton("Big");
            x.addActionListener(this);
            add(x);
        public void actionPerformed(ActionEvent arg0) {
            int newx = myframe.getWidth()+10;
            int newy = myframe.getHeight()+10;
            myframe.setTitle("X = "+newx+" Y = "+newy);
            myframe.setSize(newx,newy);
            myframe.validate();
    }

  • Mac vs. Windows -- JFrame repaint

    Say I have two windows: windowA (which is my JFrame) and windowB. My question concerns when windowB is in front of windowA and in particular when it is dragged across the screen moving over windowA.
    I've noticed that within the Mac OS, the repaint() method of windowA is never called as a result of dragging another window across it. Whereas in Windows, repaint() is called repeatedly in this situation.
    Is this to be expected? And if so, why? Are there any ways around it?
    Since windowA is not changing while windowB is being dragged across it, it seems silly for the system to keep calling repaint() instead of just saving some stored rendering of the window contents (which is what I assume the Mac OS is doing).
    The following code will demonstrate the difference:
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame {
         public Test() {
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setSize(100, 100);
              setVisible(true);
         public void paint(Graphics g) {
              super.paint(g);
              System.out.println("painting...");
         public static void main(String args[]) {
              new Test();
    }

    I think this is just how the two operating systems work. I've done some programming with Win32 API and when one window is placed on top of the other, it invalidates the section of the window that is beeing covered. So when the invalidated section is visible again, it needs to be repainted. I've not programmed for the Mac OS so I don't know why it would be doing that.

  • Show new Jframe in BorderLayout.CENTER

    I write one JFrame with BorderLayout and Jmenu when I click Menu > Test I wana show me one new Jframe IN BorderLayout.CENTER.
    new Frame2(); with BorderLayout.CENTER. Plz Can sobody show me how can I do this.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
        class JFrameIconScrollPane extends JFrame {
             private JLabel label1, label2, label3, label4, label5;
             private JMenu menu;
             private JMenuItem menuItemTest;
            JFrameIconScrollPane()
                 super("JFrame Icon ScrollPane");
                 setLayout(new BorderLayout(5, 5));
                 label1 = new JLabel("---CENTER---");
                add(label1, BorderLayout.CENTER);
                label1.setOpaque(true);
                 label1.setBackground(Color.RED);
                label2 = new JLabel("---NORTH---"); 
                add(label2, BorderLayout.NORTH);
                label3 = new JLabel("--- WEST ---");
                add(label3, BorderLayout.WEST);
                label4 = new JLabel("--- EAST ---");
                add(label4, BorderLayout.EAST);
                label5 = new JLabel("--- SOUTH ---");
                add(label5, BorderLayout.SOUTH);
          JMenuBar menuBar = new JMenuBar();
          menu = new JMenu( "Menu" );
          menuBar.add(menu);
          menuItemTest = new JMenuItem( "TEST" );
          menu.add(menuItemTest);     
    // (creates a listener)
          TestListener theTestListener = new TestListener();
          menuItemTest.addActionListener(theTestListener);
           setJMenuBar(menuBar); // set menu bar for this application               
            class TestListener implements ActionListener
                 public void actionPerformed(ActionEvent event)
                      new Frame2();
           public static void main(String args[])
                  JFrameIconScrollPane j = new JFrameIconScrollPane();
                  j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 j.setSize(900, 600);
                 j.setVisible(true);
                 j.setLocationRelativeTo(null);
    and new JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
        class Frame2 extends JFrame{ 
             private JLabel label1, label2, label3, label4, label5;
            Frame2() {
               setLayout(new BorderLayout(5, 5));
                 label1 = new JLabel("Frame 2---CENTER---");
                add(label1, BorderLayout.CENTER);
                label1.setOpaque(true);
                 label1.setBackground(Color.RED);
                label2 = new JLabel("Frame 2---NORTH---"); 
                add(label2, BorderLayout.NORTH);
                label3 = new JLabel("Frame 2--- WEST ---");
                add(label3, BorderLayout.WEST);
                label4 = new JLabel("Frame 2--- EAST ---");
                add(label4, BorderLayout.EAST);
                label5 = new JLabel("Frame 2--- SOUTH ---");
                add(label5, BorderLayout.SOUTH);
                    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    setSize(360, 350);
                    setVisible(true);
                    setLocationRelativeTo(null);
        }

    this may be close to what you're trying to do, using a CardLayout.
    clicking the menuItem changes the entire display.
    if you just want the center part to change, a slight modification is required.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class JFrameIconScrollPane
      private JLabel label1, label2, label3, label4, label5;
      private JMenu menu;
      private JMenuItem menuItemTest;
      CardLayout cl = new CardLayout();
      JFrame f;
      JFrameIconScrollPane()
        f = new JFrame("JFrame Icon ScrollPane");
        f.getContentPane().setLayout(cl);
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout(5, 5));
        label1 = new JLabel("---CENTER---");
        p.add(label1, BorderLayout.CENTER);
        label1.setOpaque(true);
        label1.setBackground(Color.RED);
        label2 = new JLabel("---NORTH---");
        p.add(label2, BorderLayout.NORTH);
        label3 = new JLabel("--- WEST ---");
        p.add(label3, BorderLayout.WEST);
        label4 = new JLabel("--- EAST ---");
        p.add(label4, BorderLayout.EAST);
        label5 = new JLabel("--- SOUTH ---");
        p.add(label5, BorderLayout.SOUTH);
        f.getContentPane().add("0",p);
        f.getContentPane().add("1",new Frame2().getFrame2Panel());
        JMenuBar menuBar = new JMenuBar();
        menu = new JMenu( "Menu" );
        menuBar.add(menu);
        menuItemTest = new JMenuItem( "Other Panel" );
        menu.add(menuItemTest);
        TestListener theTestListener = new TestListener();
        menuItemTest.addActionListener(theTestListener);
        f.setJMenuBar(menuBar);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(900, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      class TestListener implements ActionListener
        public void actionPerformed(ActionEvent event)
          cl.next(f.getContentPane());
      public static void main(String args[]){JFrameIconScrollPane j = new JFrameIconScrollPane();}
    class Frame2
      private JLabel label1, label2, label3, label4, label5;
      public JPanel getFrame2Panel()
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout(5, 5));
        label1 = new JLabel("Frame 2---CENTER---");
        p.add(label1, BorderLayout.CENTER);
        label1.setOpaque(true);
        label1.setBackground(Color.RED);
        label2 = new JLabel("Frame 2---NORTH---");
        p.add(label2, BorderLayout.NORTH);
        label3 = new JLabel("Frame 2--- WEST ---");
        p.add(label3, BorderLayout.WEST);
        label4 = new JLabel("Frame 2--- EAST ---");
        p.add(label4, BorderLayout.EAST);
        label5 = new JLabel("Frame 2--- SOUTH ---");
        p.add(label5, BorderLayout.SOUTH);
        p.setPreferredSize(new Dimension(360, 350));
        return p;
    }

  • Jframe inheritance question

    hi why is it when i set the variable inside secondframe class
    it just doesn't stick. i have a example that describes my problem better.
    i can see that when void show is called that it makes a new instance of
    second frame class so how would i fix this.
    i know i could scope int x through the show method and use it that way
    but im wanting to change varibles inside second class dynamicly
    any ideas thanks
    firstclass with frame1
    public class Main {
        public static void main(String[] args) {
              firstframe frame = new firstframe();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(270, 500);
              frame.setVisible(true);
            frame.setAlwaysOnTop(true);
    class firstframe extends JFrame
        private int x = 10;
        firstframe(){
        super.setTitle("first frame");
        System.out.println("first result :" + x);
        secondframe frame2 = new secondframe();
        secondclass.show();
    }second class
    public class secondclass {
        public static void show()
              secondframe frame = new secondframe();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(270, 500)thanks;
              frame.setVisible(true);
            frame.setAlwaysOnTop(true);
    class secondframe extends JFrame
        private int x;
        public secondframe(){
            super.setTitle("second frame");
            System.out.println("end result :" + x);
        public void setvaribles(int x){
            this.x = x;
    }

    Use proper Java naming conventions.
    Class names should be upper cased: ie FirstFrame, not firstframe.
    Method names are also upper cased except the first word: ie. setVariables, not setvariables.
    Why is show a static method? The only static method should be the main(...) method.
    You don't even need a show() method, the code to create the frame should be in the constructor.
    Also, applications should only have a single JFrame. Other windows should be JDialogs.

Maybe you are looking for