Main component in a JFrame?

Hi all,
Just wondering, how do you set the main component in a JFrame (or JDialog). The main component being the component that gets activated when you hit the enter key.
thanks,
J

Well, you can set the default button:
getRootPane().setDefaultButton(...);

Similar Messages

  • Save a "component of a JFrame to a file.  serialization

    hi there
    i read something about serialization and using the transient the example on there just using one non-serializable object . but in my case the object is going to be saved which contains : contains: String, double, Graphic, some DataSet.... etc.
    actually , i am trying to save a 'component' of a JFrame to a file, the component is a graph........... then i could load the file to do something configration (etc change the name of the graph "String", change the color....).
    but when i use the wirteObject method :
    out.writeObject(component);
    I got the NotSerializableException. I know all the objects have to be serializable in order to use the writeObject method also i know some of the component's objects aren't serialzable but it might contains a 100 of different objects??????...
    as i understand, i have to override the readObject and writeObject methods to make alll the object to serialization????? so how could i do that??? there is not just one or two objects..
    pls help
    thanks in advance

    Take a look at this stuff and see if it helps to solve your problem:
    http://java.sun.com/products/jfc/tsc/articles/persistence4/index.html
    It provides some classes, etc. on how to persist your object graph as an XML file, and then read it back in, etc.

  • Validation of reused component in Main component and Control the Navigation

    Dear Friends
       Good morning,
       I have one question as I mention in the subject.
             How to validate the data from re-used component in the main component and based on error or not the error fire the navigation plug ? 
    What I am doing is, I have two components
    1. Main_comp --> V_CREATE (view).
    2. Ora_comp-->V_CREATE_ACCOUNT (view).
    In Ora_comp I have some fields that are mandatory. plus I have 2 password fields that have to be matched with each other like ( Password and Re-Enter password).
    now in the MAIN_COMP
    I have the view called  v_create  in this view I am using method "WDDOBEFOREACTION" to validate the things.  but now I am stuck here dont know how to call the wd_api of v_create_account view of Ora_comp.
    if lo_action is bound.
         case lo_action->name.
             when 'TO_REV'. <--this is the next button action who will fire the navigation plug.
             I need to write something like this.
                 data l_view_controller type ref to if_wd_view_controller.
                 data lo_api_interfacecontroller TYPE REF TO if_wd_controller.
                 *lo_api_interfacecontroller = lo_interfacecontroller->wd_get_api( ).*
                 *l_view_controller = lo_api_interfacecontroller.*
                 *cl_wd_dynamic_tool=>check_mandatory_attr_on_view( view_controller = l_view_controller ).*      
         "some other loginc to report the non-matching passwords error using report attribute blah blah, but its okey its not a problem.
        " The proble is this
            _l_view_controller ="  ? "_  <-- what should | write here to check my view's mandatory attribute of re-used components.
            _cl_wd_dynamic_tool=>check_mandatory_attr_on_view( view_controller = l_view_controller )._
    Endcase.
    Endif.
    please help me. How I can solve this. your any help will be appreciated.
    Thank you
    Regards
    Naeem

    Hi!
       Thank you so much for your reply, well  you are right theres no navigation is taking place.. actually  my view (V_CREATE) of a main component is navigating to either to review form for for review the inputs or to go back to action view to select the action like create ,,
    why I wanted to use that dynamic_tool into main view and play with the reused view's attributes because when user presses the back button and try to go to the action view.. v_create view will not allow him to go unless he fills all the required fields..
    I wanted to over -come that.. by flush out the message area in to_action navigation part.. so I thought may be if I can do this in main view. i can remove the messages and message areas as well but I was wrong.
    well will it be possible for me to know. How can We suppress the messages and go back to action view without filling the required fields.
    look the design
    1  Serview view ( Oracle-Unix-Active Directory) --> user have selected the Oracle 
    2  Action view ( all the oracle related link2action (create, delete, rename password) --user have selected the create account
    3  v_create view ( Oracle_comp , unix_comp , active_dir_comp) since user have selected the oracle I will use oracle components'view... here I have the form to create the account in oracle server. this has the mandatory fields I can use the dynamic_tool to put check on mandatory attributes. 
    4 review view- ( Oracle_comp , unix_comp , active_dir_comp) since user have selected the oracle I will use oracle components'view..in read only.
    5 submit message view.
    so problem is at 3rd view... I can check the attributes from componets ... fill it and correct and go to review.
    but I cant go back to action-view without filling the correct informaiton.  that I wanted to solve. Suggest me is there anyway to suppress the messages and message area on to_action or anyother place to trigger the back view navigation.
    I hope this reply will you to understand what I am doing
    Thank you so much and Regards
    Edited by: Naim Khan S Babi on Mar 13, 2011 8:47 PM

  • Problem adding a component into a JFrame

    public DVD_VIDEO_CLUB() {
    mainFrame = new JFrame("DVD-VIDEO CLUB");
    mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
    aDesktopPane = new JDesktopPane();
    aDesktopPane.setBackground(Color.LIGHT_GRAY);
    aDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    mainFrame.setContentPane(aDesktopPane);
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    atoolkit = Toolkit.getDefaultToolkit();
    mainFrame.addKeyListener(new MainFrameKeyListener());
    mainFrame.addWindowListener(new FrameListener());
    mainFrame.setIconImage(createFeatures.getImage());
    mainFrame.setSize(atoolkit.getScreenSize());
    mainFrame.setJMenuBar(aMenubar.MakeMenuBar(new ItemActListener()));
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(3);
    }//end constructor
    The argument internalPanels.MainInternalPanel() is a class (internalPanels) which have various jpanels
    that i want to display under certain events.
    But i don't know why the command
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    doesn't work? I look into the java tutorial and i have read that in order to add a component you have to
    call the command
    jframe.getContentPane().add(component);
    any help is appreciated!

    my problem isn't how to add internalframes but how to add a jpanel.Did you set the size of the JPanel?
    import java.awt.*;
    import javax.swing.*;
    public class Example {
        public static void main(String[] args) {
            JFrame mainFrame = new JFrame("DVD-VIDEO CLUB");
            mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
            JDesktopPane aDesktopPane = new JDesktopPane();
            mainFrame.setContentPane(aDesktopPane);
            JPanel p = new JPanel();
            p.add(new JLabel("here is your panel"));
            p.setLocation(100, 200); //as you like
            p.setSize(p.getPreferredSize()); //this may be what you are missing
            p.setVisible(true);
            mainFrame.getContentPane().add(p);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setVisible(true);
    also i have tried not write 3 but JFrame.EXIT_ON_CLOSE but i was getting an error exception continiously.Do you mean a syntax error? That constant was introduced in 1.3 -- what version are you using?

  • Problems painting a JPanel component on a JFrame

    Hi.
    I've built a subclass of JPanel that has some controls on it, such as JPanels, JCheckBoxes, images, etc. I need to repaint this JPanel periodically because its contents are constantly changing.
    I have it added to a main JFrame (this JFrame has also other JPanels in other locations of its content pane), and when I try to repaint this JPanel, it does not seem to be double buffered, because it momentaneously repaints other parts of the window into the JPanel region, and after that it repaints what it should.
    I have tested a Panel instead of a JPanel to do the same task, and the Panel works fine.
    Basically, the code is:
    public class MyFrame extends JFrame
    JPanel myPanel = new JPanel();
    JPanel myPanel2 = new JPanel();
    JPanel myPanel3 = new JPanel();
    public MyFrame()
    getContentPane().setLayout(null);
    getContentPane().setSize(600, 400);
    myPanel.setBounds(0, 0, 200, 200);
    myPanel2.setBounds(0, 200, 200, 200);
    myPanel3.setBounds(0, 400, 200, 100);
    getContentPane().add(myPanel);
    getContentPane().add(myPanel2);
    getContentPane().add(myPanel3);
    // javax.swing.Timer to update myPanel
    Timer t = new Timer( 2000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    myPanel.repaint();
    t.start();
    I actually use othe class names and field names, but the structure is basically the same.
    Any idea of what am I doing wrong? Why Panels work fine in the same situation, into the same JFrame?
    Thank you.

    Try constructing your JPanels as doublebuffered then. (new JPanel(A layoutmanager, true)). The latter parameter is a boolean for creating a doublebuffered JPanel or not. Try with calling myPanel.revalidate() after repainting.

  • Mapping between one main component and two sub component

    Hi Experts,
    I am facing one problem.
    The situation is:-
    I have one main WD Component which has a TABSTRIP in a view.
    In that view ,TABSTRIP has 2 tabs.
    Each tab is having a view container.
    So there are two view container and each view container corresponds to one sub WD.
    So finally we have 2 seperate WD (Let say WD1 and WD2 ) and one main WD.
    In main WD i have  a Node , which is for TAB_SELECTED.It is bind witn the WD1 Node TAB_SELECTED.
    Because of this whenever we change the value of TAB_SELECTED in WD1,It automatically reflect in Main WD.
    But my problem is that i want to do it for WD2 as well.
    I am unable to bind Node of Main WD to two diff Sub WD I.e WD1 and WD2.
    How i can do this.
    Please suggest.
    Thanks
    Mahesh

    Hello Mahesh,
    I think you need to create two more nodes in the main WD compoennt .
    map the nodes of WD1 and WD2 to two seperate nodes in main WD.
    then in the method wddomodify check for the tab_selected value.
    if it is tab_1. set the value of attribute in the main WD from node mapped to WD1.
    if it is tab_2, set the value form node mapped to WD2.
    thanks
    sarbjeet singh

  • Getting the absolute location of a component within a JFrame

    I am trying to get the location of the mouse on a Canvas object inside a JFrame.
    At present I'm using the MouseInfo.getPointerInfo().getLocation() method to get the absolute mouse position, and taking away the absolute position of the JFrame using myFrame.getLocation(). But this value is slightly off, due to the window decoration.
    Is there any way to get the absolute position of the Container(JFrame.getContentPane()) housing my Canvas object? Since this has no decoration it wouldn't throw off the position.
    Thanks in advance,
    Eugene

    The size information of the decorations is available through
    Insets insets = frame.getInsets();
    insets.left and insets.top may be helpful for location info.
    Also, SwingUtilities has handy convertPoint and convertTo/FromScreen methods which you can use.
    Or you can look up the implementation of these in the source code and make up your own method(s).

  • JPopupMenu won't go away when application is moved

    Sorry, I have to reask this question. I am pretty much stuck with this.
    I have JPopupMenu that contains a JScrollPane that has a JPanel inside it.
    My application's main component is a JFrame, the above JPopupMenu is part of a search panel (JPanel). Every time when I make JPopupMenu visible, then left-click on application's title bar, and move the whole application away, JPopupMenu stays in the original position! If I click on any other place, such as tool bar, or any other component, JPopupMenu will disappear.
    This is really strange stuff. My guess is that titile bar cannot detect mouse events? Is that true? Is there any way I can make it disappear once user holds title bar and move the whole application away?
    thanks in advance!
    Message was edited by:
    jack_wns

    Finally created some sample code I can use to explain the possible solution I try to figure out. If I run the same application and then right-click on the
    application, a popup menu will show up. If I move mouse outside the frame (I try to make JComponent visible so that I can move mouse outside JComponent, but I cannot make it happen), popup menu is still visible. I try to add the following to mouseExited method:
    popupMenu.setVisible(false);
    But this seemingly will disable pupup menu.
    What I try to do is: make popup disappear once user move her mouse outside frame (better yet JComponent). How can I do this?
    Here is the sample code I just created:
    import java.awt.AWTEvent;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    class PopupTest extends JComponent implements ActionListener, MouseListener {
         private JPanel topPanel;
         private JPopupMenu popupMenu;
         public PopupTest() {
              //setTitle("Popup Menu Application");
              setSize(310, 130);
              setBackground(Color.GREEN);
              topPanel = new JPanel();
              topPanel.setLayout(null);
              add(topPanel);
              JMenuItem menuFileNew = new JMenuItem("New");
              JMenuItem menuFileOpen = new JMenuItem("Open...");
              JMenuItem menuFileSave = new JMenuItem("Save");
              JMenuItem menuFileSaveAs = new JMenuItem("Save As...");
              JMenuItem menuFileExit = new JMenuItem("Exit");
              // Create a popup menu
              popupMenu = new JPopupMenu("Menu");
              popupMenu.add(menuFileNew);
              popupMenu.add(menuFileOpen);
              popupMenu.add(menuFileSave);
              popupMenu.add(menuFileSaveAs);
              popupMenu.add(menuFileExit);
              topPanel.add(popupMenu);
              enableEvents(AWTEvent.MOUSE_EVENT_MASK);
              menuFileNew.addActionListener(this);
              menuFileOpen.addActionListener(this);
              menuFileSave.addActionListener(this);
              menuFileSaveAs.addActionListener(this);
              menuFileExit.addActionListener(this);
              addMouseListener(this);
         public void processMouseEvent(MouseEvent event) {
              if (event.isPopupTrigger()) {
                   popupMenu.show(event.getComponent(), event.getX(), event.getY());
              super.processMouseEvent(event);
         public void actionPerformed(ActionEvent event) {
              System.out.println(event);
         public void mouseExited(final MouseEvent e) {
              System.out.println("Mouse Exited...");
              //popupMenu.setVisible(false);  //line added
         public void mouseEntered(final MouseEvent e) {
              System.out.println("Mouse Entered...");
         public void mousePressed(final MouseEvent e) {
              System.out.println("Mouse pressed...");
         public void mouseReleased(final MouseEvent e) {
         public void mouseClicked(final MouseEvent e) {
              System.out.println("Mouse Clicked...");
         public static void main(String args[]) {
              PopupTest mainFrame = new PopupTest();
              mainFrame.setVisible(true);
              JFrame frame = new JFrame();
              frame.setTitle("Popup Menu Application");
              frame.setSize(500, 430);
              frame.getContentPane().add(mainFrame);
              frame.setVisible(true);
    }thx

  • In Unix, main JFrame focus not regained after modal dialog exit.

    Hi all,
    I'm new to this forum so hopefully this is the right place to put this question.
    I have a relatively simple GUI application written in Java 6u20 that involves a main gui window (extends JFrame). Most of the file menu operations result in a modal dialog (either JFileChooser or JOptionPane) being presented to the user.
    The problem is that when running on Unix (HPUX), the process of changing focus to one of these modal dialogs occasionally results in a quick flash of the background terminal window (not necessarily that used to launch the Java), and the process of closing the modal dialogs (by any means, i.e. any dialog button or hitting esc) doesn't always return focus to the main extended JFrame object, sometimes it goes to the terminal window and sometimes just flashes the terminal window before returning to the main JFrame window.
    I think the problem is with the Unix window manager deciding that the main focus should be a terminal window, not my Java application, since the problem occurs in both directions (i.e. focus from main JFrame to modal dialog or vice versa).
    In most cases of JOptionPane, I DO specify that the main extended JFrame object is the parent.
    I've tried multiple things since the problem first occured, including multiple calls to a method which calls the following:
    .toFront();
    .requestFocus();
    .setAlwaysOnTop(true);
    .setVisible(true);
    ..on the main JFrame window (referred to as a public static object)...
    just before and after dialog display, and following selection of any button from the dialogs. This reduced the frequency of the problem, but it always tends to flash the terminal window if not return focus to it completely, and when it occurs (or starts to occur then gets worse) is apparently random! (which makes me think it's an OS issue)
    Any help appreciated thanks,
    Simon
    Self-contained compilable example below which has the same behaviour, but note that the problem DOESN'T occur running on Windows (XP) and that my actual program doesn't use auto-generated code generated by a guibuilder:
    * To change this template, choose Tools | Templates 
    * and open the template in the editor. 
    package example;  
    import javax.swing.JOptionPane;  
    * @author swg 
    public class Main {  
         * @param args the command line arguments 
        public static void main(String[] args) {  
            java.awt.EventQueue.invokeLater(new Runnable() {  
                public void run() {  
                    new NewJFrame().setVisible(true);  
    class NewJFrame extends javax.swing.JFrame {  
        /** Creates new form NewJFrame */ 
        public NewJFrame() {  
            initComponents();  
        /** This method is called from within the constructor to 
         * initialize the form. 
         * WARNING: Do NOT modify this code. The content of this method is 
         * always regenerated by the Form Editor. 
        @SuppressWarnings("unchecked")  
        // <editor-fold defaultstate="collapsed" desc="Generated Code">  
        private void initComponents() {  
            jMenuBar1 = new javax.swing.JMenuBar();  
            jMenu1 = new javax.swing.JMenu();  
            jMenuItem1 = new javax.swing.JMenuItem();  
            jMenu2 = new javax.swing.JMenu();  
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
            jMenu1.setText("File");  
            jMenuItem1.setText("jMenuItem1");  
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jMenuItem1ActionPerformed(evt);  
            jMenu1.add(jMenuItem1);  
            jMenuBar1.add(jMenu1);  
            jMenu2.setText("Edit");  
            jMenuBar1.add(jMenu2);  
            setJMenuBar(jMenuBar1);  
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
            getContentPane().setLayout(layout);  
            layout.setHorizontalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGap(0, 400, Short.MAX_VALUE)  
            layout.setVerticalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGap(0, 279, Short.MAX_VALUE)  
            pack();  
        }// </editor-fold>  
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {  
            int result = JOptionPane.showConfirmDialog(this, "hello");  
        // Variables declaration - do not modify  
        private javax.swing.JMenu jMenu1;  
        private javax.swing.JMenu jMenu2;  
        private javax.swing.JMenuBar jMenuBar1;  
        private javax.swing.JMenuItem jMenuItem1;  
        // End of variables declaration  
    }

    It won't comfort you much, but I had similar problems on Solaris 10, and at the time we traked them down to a known bug [6262392|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6262392]. The status of this latter is "Closed, will not fix", although it is not explained why...
    It's probably because the entry is itself related to another, more general, bug [6888200|http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=b6eea0fca217effffffffe82413c8a9fce16?bug_id=6888200], which is still open.
    So it is unclear whether this problem will be worked upon (I suspect that yes) and when (I suspect that... not too soon, as it's been dormant for several years!).
    None of our attempts (+toFront(...)+ etc...) solved the issue either, and they only moderately lowered the frequency of occurrence.
    I left the project since then, but I was said that the workaround mentioned in the first bug entry (see comments) doesn't work, whereas switching to Java Desktop instead of CDE reduced the frequency of the issues (without fixing them completely either) - I don't know whether it's an option on HPUX.
    Edited by: jduprez on Jul 9, 2010 11:29 AM

  • Calling main controller method from component view

    Hi,
    Because i want to re-use certain views, i've created components of em so i can re-use them in several places within the same view. The problem is that i have 1 main component which has several methods calling webservices. I want the other components to be able to call the methods of the maincomponent. I tried adding the main component to the Used Web Dynpro Components of another component. Then i added the main component in the properties of the view but then it says: Cycle in component usage definitions.
    I can understand this because the main view creates instances of all other components, so the sub components cannot create the maincomponent again...but how do i then give a reference of the maincomponents controller to the sub components?
    Much thanks,
    Hugo Hendriks

    Hi Siarhei,
    The problem of creating a Java class is that there i dont have access to certain classes for example when there is something with a webservice, i want to send a message back like
    IWDMessageManager msgMgr = wdComponentAPI.getMessageManager();
         msgMgr.reportSuccess(message);
    In a seperate java class, i dont have access to the wdComponentAPI! The only thing i want is kinda like a ServiceLocator to call different webservices. I do check roles of the user logged in the portal and stuff like that....How do you normally implement something like this? I have several views which have to make use of the locator....
    I hope i dont need to create a seperate DC when i want to re-use a screen and want to call a service method of another class or so.........Sounds like much overkill for a screen with 2 inputfields and a button!
    Anoop, i tried adding the mainController to the searchComponent by adding it to Used WebDynpro Components and then I added the mainController in the properties of the searchView so i can make use of it. In the searchcode i now can use the maincontroller but i still get the compiling message: Cycle in component usage definition!
    best regards,
    Hugo

  • How to remove and add the component to JFrame at runtime.

    Hi
    How to delete the JTabbedPane component from the Jframe at runtime and how to add the same component with different data at runtime.
    But the remaining components should not distrub.
    When i try to delete and add the component at runtime the remaing components are distrubed.
    when i minimize and maximize the screen, the components are adjusted. but i need a help on this without minimize and maximize the screen.

    Hi
    I am sending my code snippet, please look into this......i am doing the same even though i am not able to..................can u suggest anything seeing this code snippet.
    here one function called createtabpane (It creates the JTabbedpanes with the table information at runtime).
    private void getTimeSheetObj(String weekDate){
    //Object[][] rowObj=null;
    try {
    System.out.println("Inside the gettimesheet method try block");
    if(projTables!=null){
    for(int i=projTables.length-1; i>=0; i--){
    JTable jt = projTables;
    jTabbedPane_Main.remove(jt);
    System.out.println("Removing Table:"+i);
    jPanel_Tabbedpane.remove(jTabbedPane_Main);
    jTabbedPane_Main = new JTabbedPane();
    jTabbedPane_Main.revalidate();
    jPanel_Tabbedpane.revalidate();
    getContentPane().validate();
    getContentPane().repaint();
    jTabbedPane_Main.addChangeListener(new ChangeListener(){
    public void stateChanged(ChangeEvent ce){
    getTabbedPaneListenerValues();
    // this.setState(JFrame.ICONIFIED);
    // this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    res = GetTimesheetResponseDocument.Factory.parse(new File("C:\\Narayana.xml"));
    response = res.getGetTimesheetResponse();
    proDets=response.getProjectDetailsArray();
    numOfPro = proDets.length;
    String taskDayValues[] = new String[8];
    System.out.println(numOfPro);
    proArr=new Object[numOfPro];
    Object[][] taskValues=null;
    for(int p = 0;p<numOfPro;p++){
    System.out.println("Inside1");
    taskDet = proDets[p].getTaskDetailsArray();
    taskValues = new Object[taskDet.length][8];
    for(int t=0;t<taskDet.length;t++){
    System.out.println("Inside2");
    taskValues[t][0] = (taskDet[t].getTaskName());
    taskValues[t][1] = (taskDet[t].getDay1HH()+":"+taskDet[t].getDay1MM()).toString();
    taskValues[t][2] = (taskDet[t].getDay2HH()+":"+taskDet[t].getDay2MM()).toString();
    taskValues[t][3] = (taskDet[t].getDay3HH()+":"+taskDet[t].getDay3MM()).toString();
    taskValues[t][4] = (taskDet[t].getDay4HH()+":"+taskDet[t].getDay4MM()).toString();
    taskValues[t][5] = (taskDet[t].getDay5HH()+":"+taskDet[t].getDay5MM()).toString();
    taskValues[t][6] = (taskDet[t].getDay6HH()+":"+taskDet[t].getDay6MM()).toString();
    taskValues[t][7] = (taskDet[t].getDay7HH()+":"+taskDet[t].getDay7MM()).toString();
    System.out.println("After taskvalues");
    proArr[p]=taskValues;
    createTabPanes(jTabbedPane_Main, proArr);
    System.out.println("outside");
    jPanel_Tabbedpane.add(jTabbedPane_Main);
    jTabbedPane_Main.getAccessibleContext().setAccessibleName("Proj");
    getContentPane().add(jPanel_Tabbedpane);
    pack();
    }catch(XmlException xe) {
    System.out.println("Inside the XmlException block");
    System.out.println(""+xe.getMessage());
    } catch(IOException ioe) {
    System.out.println("Inside the IOException block");
    System.out.println(""+ioe.getMessage());
    /* JOptionPane.showMessageDialog(null,
    "Values Displayed in the below tables",
    "Alert!",JOptionPane.ERROR_MESSAGE); */
    System.out.println("Initial JFrame Bounds:"+this.getBounds());

  • How to print the whole JFrame

    Hi,
    I got this code somewhere from the net.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    *  an arbitrary component. Just pass the component to the
    *  PrintUtilities.printComponent. The component you want to
    *  print doesn't need a print method and doesn't have to
    *  implement any interface or do anything special at all.
    *  <P>
    *  If you are going to be printing many times, it is marginally more
    *  efficient to first do the following:
    *  <PRE>
    *    PrintUtilities printHelper = new PrintUtilities(theComponent);
    *  </PRE>
    *  then later do printHelper.print(). But this is a very tiny
    *  difference, so in most cases just do the simpler
    *  PrintUtilities.printComponent(componentToBePrinted).
    *  7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    *  May be freely used or adapted.
    public class PrintUtilities implements Printable {
      private JFrame componentToBePrinted;
      public static void printComponent(JFrame c) {
        new PrintUtilities(c).print();
      public PrintUtilities(JFrame componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;
      public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog())
          try {
            printJob.print();
          } catch(PrinterException pe) {
            System.out.println("Error printing: " + pe);
      public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        } else {
          Graphics2D g2d = (Graphics2D)g;
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
          disableDoubleBuffering(componentToBePrinted);
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }From my main class (where the JFrame resides), the print() method is invoked to print the JFrame. However, when it is printed, it only prints the top left part of the JFrame, not the whole JFrame. Can anyone help please? Thank you very much.

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        else {
          Graphics2D g2d = (Graphics2D)g;     
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
           double xScale = 0.63;
           double yScale = 0.56;
          g2d.scale(xScale, yScale);
          disableDoubleBuffering(componentToBePrinted);     
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      }Hi all,
    Alright I managed to scale it to print the whole JFrame. But another problem surfaces. When I select draft quality printing, it doesn't print the whole JFrame. Other printing qualities (standard, high) do print the whole JFrame. I am really puzzled. Anyone has any clue?
    And I have an unrelated question to this topic. How do I set a JTextField so that when I click on it the first time, it highlights its content? Have to work around with the mouselistener?
    Thank you.

  • Set font size based on component size

    Hi everybody,
    This is kind of a duplicate, kind of new, because my original post is buried and I figured out a more helpful and general way to ask this question. Does anyone know if there is a way to set the size of a string as large as possible on a component, but still be able to have the whole string visible, if you're using a font other than default?
    For example:
    public static void main( String args[] ){
    try {
              JFrame frame = new JFrame( "Title" );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              int guiWidth = width / 2;
              int guiHeight = height / 2;
              frame.setSize( guiWidth, guiHeight );
              Container pane = frame.getContentPane();
              // Create main label
              String labelString = "Test";
              JLabel label = new JLabel( labelString );
              label.setBackground( new Color( 179, 0, 0 ) );
              label.setForeground( new Color( 235, 191, 16 ) );
              label.setHorizontalAlignment( CENTER );
              label.setOpaque( true );
              label.setFont( new Font( �Old English Text MT�, 0, 48 ) );
              pane.add( label, BorderLayout.NORTH );
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    } catch( Exception e) {
    e.printStackTrace();
         }As you can see, right now the font needs to be hard coded. I'd like it to be dynamic, based on the size of the screen the user has.
    Sorry if the partial double post annoys anybody; I figured it would be less annoying than resurrecting my old post.
    Any help on this would be great, and thank you!
    Jezzica85
    Message was edited by:
    jezzica85
    Message was edited by:
    jezzica85

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.AffineTransform;
    import javax.swing.*;
    public class DynamicFont {
        private JLabel getNorth() {
            // Create main label
            String labelString = "Test";
            final JLabel label = new JLabel( labelString ) {
                public void paint(Graphics g) {
                    ((Graphics2D)g).setRenderingHint(
                            RenderingHints.KEY_TEXT_ANTIALIASING,
                            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                    super.paint(g);
            label.setBackground( new Color( 179, 0, 0 ) );
            label.setForeground( new Color( 235, 191, 16 ) );
            label.setHorizontalAlignment( JLabel.CENTER );
            label.setOpaque( true );
            label.setFont( new Font( "Old English Text MT", 0, 48 ) );
            label.addComponentListener(new ComponentAdapter() {
                Font font = label.getFont();
                public void componentResized(ComponentEvent e) {
                    int w = label.getWidth();
                    int sw = label.getFontMetrics(font).stringWidth(label.getText());
                    double scale = (double)w/sw;
                    AffineTransform at = AffineTransform.getScaleInstance(scale, 1.0);
                    label.setFont(font.deriveFont(at));
                    label.repaint();
            return label;
        public static void main( String[] args ) {
            JFrame frame = new JFrame( "Title" );
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            Container pane = frame.getContentPane();
            pane.add( new DynamicFont().getNorth(), BorderLayout.NORTH );
            frame.setSize( 400, 100);
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
    }

  • JFrame - MouseEvent handling, 2nd

    Hi,
    the following code has a JFrame, which opens via the JButton a second JFrame, which holds a JTable:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class FrameTester {
         private void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("This is a Frame.");
              // Show the frame
              int width = 300;
              int height = 300;
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width, height);
              frame.getContentPane().setLayout(new GridLayout(3, 3));
              frame.addMouseListener(new MouseListener() {
                   public void mouseClicked(MouseEvent e) {
                        System.out.println("Frame clicked.");
                   public void mousePressed(MouseEvent e) {
                   public void mouseReleased(MouseEvent e) {
                   public void mouseEntered(MouseEvent e) {
                   public void mouseExited(MouseEvent e) {
              JButton b1 = new JButton("OK");
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        new FrameTable();
              JLabel jL1 = new JLabel();
              JLabel jL2 = new JLabel();
              JLabel jL3 = new JLabel();
              JLabel jL4 = new JLabel();
              JLabel jL5 = new JLabel();
              JLabel jL6 = new JLabel();
              JLabel jL7 = new JLabel();
              JLabel jL8 = new JLabel();
              frame.getContentPane().add(jL1);
              frame.getContentPane().add(jL2);
              frame.getContentPane().add(jL3);
              frame.getContentPane().add(jL4);
              frame.getContentPane().add(b1);
              frame.getContentPane().add(jL5);
              frame.getContentPane().add(jL6);
              frame.getContentPane().add(jL7);
              frame.getContentPane().add(jL8);
              // Display the window.
              frame.setVisible(true);
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              FrameTester ft = new FrameTester();
              ft.createAndShowGUI();
    } import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    public class FrameTable {
         FrameTable() {
              // Create and set up the window.
              JFrame frame = new JFrame("This frame has a JTable.");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setLayout(new GridLayout(2, 1));
              String[] columnNames = { "First Name", "Last Name", "Id" };
              Object[][] data = { { "Mary", "Campione", new Integer(5) },
                        { "Alison", "Huml", new Integer(3) } };
              JTable table = new JTable(data, columnNames);
              JLabel jL1 = new JLabel();
              frame.getContentPane().add(jL1);
              frame.getContentPane().add(table);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
    }First of all, I'm wondering why the first frame closes as well, if the second one is closed by the support button for closing?
    But now my main questions:
    The second JFrame has a JTable. When I edit a cell, for example the ID cell (3rd column) of the first row, and hit the enter key or click inside another cell of the JTable, the current value of the edited cell is stored automatically by the JTable. But if I edit a cell and click somewhere outside the cell, for example
    1. Above the cell (where in this example a JLable is placed)
    2. Close the second JFrame by clicking the support button for closing
    3. Click inside the first JFrame
    I would like that the current edited cell stores the current value as well. How to achieve this?
    Thx!

    but I thought, that each instance of a JFrame is closed independently...It is if you choose the appropriate close operation. So again I ask why did you choose "exit" instead of one of the other options? Did you read the API to understand what all the options mean?
    but no change in behavior. I found some posts that this worked for other code samples, but why not here? Then no focus lost event was generated. If you click on a label it doesn't gain focus so focus is still on the editor. If you click on a panel of the frame a panel doesn't gain focus either. So I'm not sure what you expect to happen but I guess you need to use the second approach of manually stopping cell editing when you click on another component.
    If you click on the close button, the same problem is that the table doesn't lose focus. So I guess you need to add a WindowListener to the frame and manually stop editing in the windowClosing() method. You can check out my "Closing an Application" entry from the above blog.

  • Referencing main class from created instances

    The quick setup:
    My Main class creates a JFrame and adds a few custom JPanels. One of the JPanels has a mouse listener and responses to the mouse clicks, and it works great.
    I'd like to know if there's a way to have that JPanel invoke public, non-static methods from the Main class (the class which created it) without passing a reference for the instance of the Main class to the JPanel when it's (the JPanel) is created. Or is that the way you're supposed to do it?
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?
    Thanks so much,
    Matt

    Hi Rhesus21,
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?Yes, simply this way :
    public class MainFrame extends JFrame {
        private MyPanel panel;
        panel = new MyPanel(this);
    public class MyPanel extends JPanel {
        private MainFrame frame;
        public MyPanel(MainFrame frame) {
            this.frame = frame;
    }

Maybe you are looking for