JFrame.getContentPane()

JFrame.getContentPane() returns the container that is the JFrame's content pane. Is there a way to identify the class of the object returned? I'm trying to figure out the default container (class) that is assigned as the content pane of a JFrame.

Object defines a getClass() method that returns an instance of java.lang.Class that represents the runtime type of the object.
Why do you need this information anyway? If you need to rely on the type of the content pane, then you should just create a Container of the type you desire and use JFrame.setContentPane() to make that Container the content pane for the JFrame.

Similar Messages

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

  • Open an applet inside a JFrame?

    Hi all!
    I know this subject is kind of covered in previous topics, but my situation here is a little different.
    I have a TRENDnet TV-IP100 Internet Camera that uses a Java-Applet to show in a browser window the video it captures, using an xview.class file.
    I built a swing application that extends JFrame and I want to open in a JPanel, inside the JFrame, the applet-class that my camera uses.
    My problem is that I can't take and decompile that class file from the camera, in order to compile from the scratch the Applet; some could say illegal.
    So, I wonder if there is a way to open the class file inside my JFrame application. Also, I want to know if I can pass argumets in the JFrame file, like PARAM, NAME, VALUE, as there are important to start the applet.
    Thank you all, in advance.
    John_Astralidis.

    I have not tried this but if the Applet or JApplet class is to be used only as far as a component in a Container (JFrame.getContentPane() returns a Container) I see no problem with explicitly casting into a Panel or even a Container
    Panel p=(Panel)theAppletInstance;
    this.getContentPane().add(p);//this being the JFrame;There be problem of which I have not considered as the applet class is 'different' to many classes.
    Bamkin
    Message was edited by:
    bamkin-ov-lesta
    Container and Panel examples were used as Applet is derived from Panel, which is derived from Containter

  • 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).

  • Intercepting JFrame closing

    Ok, so in my GUI adventure, I now need to present a dialog asking if the user wants to save his or her work on closing via the window decoration.
    So, when the user clicks the close decoration on the JFrame, I need to query the use if he or she really wants to leave, if yes, the continue to close the app, if no cancel closing the app. How can I do this?

    set the default close operation like
    jFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    // now handle close operation by urself, by adding WindowListener to jFrame
    For u'r reference I'm adding one sample code use this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class CloseFrame extends JFrame
         static boolean canClose = false;
         static CloseFrame jFrame;
         public static void main(String a[])
              jFrame = new CloseFrame("Close Frame");
              jFrame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent we)
                        if ( !canClose)
                             return;
                        System.exit(0);
              JButton jBut = new JButton("Allow Close");
              jBut.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        canClose = true;
              jFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
              jFrame.getContentPane().setLayout(new FlowLayout());
              jFrame.getContentPane().add(jBut);
              jFrame.setSize(500,500);
              jFrame.setVisible(true);
         CloseFrame(String s)
              super(s);
    }

  • Help Refreshing JFrame, Validate not working...

    Hi,
    I've read many post suggesting that calling the JFrame.getContentPane().Validate() should refresh my JFrame and display the modifications made to the components on it, but it doesn't work for me. OK, so i'm creating a login screen where i want to hide 2 combos/2 labels, move the buttons and resize the frame when i click on a button (similar to the Windows Login screen where you can click "Options" to view the Domain Combo). When I hide my comtrols, works perfect, when i want to re-display them, the section of the frame that was hidden does not refresh what was behind it. The Option Button calls the ButtonOptionHandler() function, that's where the Validate() is executed.
    Here is the complete code for easier understanding, you can run it and see the effects:
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JPasswordField;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    import javax.swing.ImageIcon;
    import java.awt.event.*;
    public class screenLogin extends JFrame implements ActionListener {
    private static String OK = "OK";
    private static String CANCEL = "Cancel";
    private static String OPTION = "Option";
    private boolean showODBC = false;
         private JLabel lblUser;
         private JLabel lblPass;
         private JLabel lblOraODBC;
         private JLabel lblSqlODBC;
         private JTextField txtUser;
         private JPasswordField txtPass;
         private JComboBox cboOraODBC;
         private JComboBox cboSqlODBC;
         private JButton btnOK;
         private JButton btnCancel;
         private JButton btnOption;
         private JLabel lblImage;
         public screenLogin() {
              InitUI();
         private void InitUI() {
              this.setSize(400,230);
              this.getContentPane().setLayout(null);
              /* Labels */
              lblUser = new JLabel("NorLims User", SwingConstants.RIGHT);
              lblPass = new JLabel("Password", SwingConstants.RIGHT);
              lblOraODBC = new JLabel("Oracle ODBC", SwingConstants.RIGHT);
              lblSqlODBC = new JLabel("SQL Anywhere ODBC", SwingConstants.RIGHT);
              lblUser.setBounds(10, 65, 120, 23);
              lblPass.setBounds(10, 90, 120, 23);
              lblOraODBC.setBounds(10, 115, 120, 23);
              lblSqlODBC.setBounds(10, 140, 120, 23);
              txtUser = new JTextField();
              txtUser.setBounds(140, 65, 100, 20);
              txtPass = new JPasswordField();
              txtPass.setBounds(140, 90, 100, 20);
              txtPass.setEchoChar('*');
              cboOraODBC = new JComboBox();
              cboOraODBC.setBounds(140, 115, 200, 20);
              cboSqlODBC = new JComboBox();
              cboSqlODBC.setBounds(140, 140, 200, 20);
              btnOK = new JButton("OK");
              btnOK.setSize(80, 25);
              btnOK.setActionCommand(OK);
              btnOK.addActionListener(this);
              btnCancel = new JButton("Cancel");
              btnCancel.setSize(80, 25);
              btnCancel.setActionCommand(CANCEL);
              btnCancel.addActionListener(this);
              btnOption = new JButton("Options");
              btnOption.setSize(80, 25);
              btnOption.setActionCommand(OPTION);
              btnOption.addActionListener(this);
              // position Buttons and display labels/combos
              ButtonOptionHandler();
              // I commented this part since you dont have the login.jpg
              //lblImage = new JLabel(new ImageIcon("login.jpg"));
              //lblImage.setBounds(0, 0, 400, 60);
              this.getContentPane().add(lblUser, null);
              this.getContentPane().add(lblPass, null);
              this.getContentPane().add(lblOraODBC, null);
              this.getContentPane().add(lblSqlODBC, null);
              this.getContentPane().add(txtUser, null);
              this.getContentPane().add(txtPass, null);
              this.getContentPane().add(cboOraODBC, null);
              this.getContentPane().add(cboSqlODBC, null);
              this.getContentPane().add(btnOK, null);
              this.getContentPane().add(btnCancel, null);
              this.getContentPane().add(btnOption, null);
              //this.getContentPane().add(lblImage, null);
         public void actionPerformed(ActionEvent e) {
              String cmd = e.getActionCommand();
              if (OK.equals(cmd)) { //Process the OK Button
                   ButtonOkHandler();
              } else if (CANCEL.equals(cmd)) {
                   ButtonCancelHandler();
              } else if (OPTION.equals(cmd)) {
                   ButtonOptionHandler();
         private void ButtonOkHandler() {
              System.out.println("OK Button");
         private void ButtonCancelHandler() {
              System.out.println("Cancel Button");
              System.exit(0);
         private void ButtonOptionHandler() {
              showODBC = !showODBC;     // Toggle the value
              int top = (showODBC ? 165 : 115);          // determine the top for the buttons
              this.setSize(400, (showODBC ? 230 : 180));
              lblOraODBC.setVisible(showODBC);
              lblSqlODBC.setVisible(showODBC);
              cboOraODBC.setVisible(showODBC);
              cboSqlODBC.setVisible(showODBC);     
              btnOK.setLocation(100, top);
              btnCancel.setLocation(180, top);
              btnOption.setLocation(260, top);
              this.getContentPane().validate(); // This dont refresh ?!?
    I hope someone can help me with this!
    Thanks,
    XiNull

    First suggestion would be to use a layout manager. Then changing the visibility of components within the layout mgr will cause all the proper resizing, refreshing, etc. to happen for you. You should never have to call validate on your own like that (unless you are doing something really bizarre, which you aren't). Generally null or XY layout managers are more hassle than they are worth (and a maintenance nightmare). Do yourself a favor and learn to use gridbaglayout, etc. While a bit wacky to get used to, you will be glad you spent the time on it.

  • Focus problem when JPopupMenu is shown

    I have compiled and ran the following 'JPopupTest.java' in JDK 1.4.1 on Windows. Kindly conduct the two tests as given below
    First Test :
    ============
    The class shows an editable JComboBox and a JButton when visible. Now click the down-arrow button of the JComboBox and make the drop-down popup visible. Then click on the "OK" button while the popup is visible. The popup gets hidden and a dialog is displayed as it should be.
    Second Test :
    =============
    Run the appilcation again. This time type something in the editable textfield of the JComboBox. A custom JPopupMenu with the text "Hello World" would be visible. Then click on the "OK" button while the popup is visible. The expected dialog is not shown. The custom JPopupMenu gets hidden. Now click on "OK" button again. The dialog is visible now.
    My Desire :
    ===========
    When I click on the "OK" button in the "Second Test" the JPopupMenu should get hidden and the dialog gets displayed (as it happens for the "First Test") in one click.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    import java.util.*;
    public class JPopupTest extends JPanel implements DocumentListener, ActionListener
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         JPopupMenu jpopupmenu;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         public JPopupTest()
            vec = new Vector();
               vec.addElement("One");
            vec.addElement("Two");
            vec.addElement("Three");
            vec.addElement("Four");
            vec.addElement("Five");
            vec.addElement("Six");
            vec.addElement("Seven");
            vec.addElement("Eight");
            vec.addElement("Nine");
            vec.addElement("Ten");
            jcombobox = new JComboBox(vec);
            jcombobox.setEditable(true);
            _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
            jtextfield = ((JTextField) _bcbe.getEditorComponent());
            jtextfield.getDocument().addDocumentListener(this);
            add(jcombobox);
            button = new JButton("OK");
            button.addActionListener(this);
            add(button);
            jpopupmenu = new JPopupMenu();
            jpopupmenu.add("Hello World");
         public void insertUpdate(DocumentEvent e)  {changedUpdate(e);}
         public void removeUpdate(DocumentEvent e)  {changedUpdate(e);}
            public void changedUpdate(DocumentEvent e)
            if(!jpopupmenu.isVisible())
            jpopupmenu.show(jcombobox, 0, jcombobox.getHeight());
            jtextfield.requestFocus();
         public void actionPerformed(ActionEvent e)
            JOptionPane.showMessageDialog(this, "OK button was pressed");
         public static void main(String[] args)
            JPopupTest test = new JPopupTest();
            JFrame jframe = new JFrame();
            jframe.getContentPane().add(test);
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jframe.setSize(200,100);
            jframe.setVisible(true);

    See the code below with auto complete of text. When button is pressed, still TF gets focus after JOptionPane dialog is closed.
    -Pratap
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    public class JPopupTest extends JPanel implements ActionListener {
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         MyComboUI comboUi = new MyComboUI();
         public JPopupTest() {
              vec = new Vector();
              vec.addElement("One");
              vec.addElement("Two");
              vec.addElement("Three");
              vec.addElement("Four");
              vec.addElement("Five");
              vec.addElement("Six");
              vec.addElement("Seven");
              vec.addElement("Eight");
              vec.addElement("Nine");
              vec.addElement("Ten");
              jcombobox = new JComboBox(vec);
              jcombobox.setEditable(true);
              jcombobox.setUI(comboUi);
              add(jcombobox);
              button = new JButton("OK");
              button.addActionListener(this);
              add(button);
              _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
              jtextfield = ((JTextField) _bcbe.getEditorComponent());
              jtextfield.addCaretListener(new CaretListener() {
                        public void caretUpdate(CaretEvent e) {
                             if (!jcombobox.isPopupVisible() && jtextfield.isShowing() &&
                                       jtextfield.hasFocus()) {
                                  jcombobox.showPopup();
                             String text = jtextfield.getText().toLowerCase();
                             int index = -1;
                             for (int i = 0; i < jcombobox.getItemCount(); i++) {
                                  String item = ((String) jcombobox.getItemAt(i)).toLowerCase();
                                  if (item.startsWith(text)) {
                                       index = i;
                                       break;
                             if (index != -1) {
                                  comboUi.getList().setSelectedIndex(index);
                             } else {
                                  comboUi.getList().clearSelection();
                   jtextfield.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent e) {
                             if (e.getKeyCode() == e.VK_ENTER) {
                                  Object value = comboUi.getList().getSelectedValue();
                                  jcombobox.setSelectedItem(value);
                                  jcombobox.hidePopup();
         public void actionPerformed(ActionEvent e) {
              JOptionPane.showMessageDialog(this,"OK button was pressed");
              jtextfield.requestFocus();
         public static void main(String[] args) {
              JPopupTest test = new JPopupTest();
              JFrame jframe = new JFrame();
              jframe.getContentPane().add(test);
              jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jframe.setSize(200,100);
              jframe.setVisible(true);
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList() {
                   return listBox;

  • Opening a HTML page on clicking of button .

    i created a button under menuItem help , i want to open a HTML page in other window (that is save inside my project folder ) when i click that button.
    for this i created jeditorpane and passing the URL in to its constructor but i m getting exception when i m using URL like "D:/x/y.html" exception is protocol not find and in the case of "http://localhost/d:/x/y.html" exception is java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method
    my code is
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import java.awt.Color;
    import java.awt.Container;
    import java.io.IOException;
    public class HelpDialog {
    * height of frame in pixels
    private static final int height = 1000;
    * width of frame in pixels
    private static final int width = 1000;
    private static final String TITLE_STRING = "Help";
    * URL of page we want to display
    private static final String URL = "http://localhost/D:/SVGcode/javaApplet/src/com/Documentation.html";
    // --------------------------- main() method ---------
         public HelpDialog()
         SwingUtilities.invokeLater( new Runnable()
         public void run()
         System.out.println( "Starting" );
         final JFrame jframe =
         new JFrame( TITLE_STRING );
         Container contentPane = jframe.getContentPane();
         jframe.setSize( width, height );
         contentPane.setBackground( Color.WHITE );
         contentPane.setForeground( Color.BLUE );
         jframe.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE);
         try
         System.out.println( "acquiring URL" );
         JEditorPane jep = new JEditorPane(URL);
         System.out.println( "URL acquired" );
         JScrollPane jsp =
         new JScrollPane( jep,
         JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
         JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
         contentPane.add( jsp );
         catch ( IOException e )
         System.err.println( "can't find URL" );
         e.printStackTrace();
         contentPane.add( new JLabel( "can't find URL" ) );
         jframe.validate();
         jframe.setVisible( true );
    plz help me

    Hi Sandy,
    Instead of giving url in the constructor. Paste the code below the JEditorPane. Remove the url from the JEditorPane constructor.
    try{
                        /** Files from system */
                        java.net.URL helpURL = new URL ("file:///" + "C:\\thread.jspa.htm");     
                        /** Files from inter net */
                         helpURL = new URL ("http://forums.sun.com/thread.jspa?threadID=5421146&tstart=0");
              if(helpURL!=null)     
               jHelp.setPage(helpURL);
              else
                   System.out.println("Couldnt find file");
               }catch(MalformedURLException exp){
                    System.out.println("Exception in page loading---"+exp);
               }catch(IOException ioexp){
                    System.out.println("Exception in page loading"+ioexp);
               }

  • Imitate modal dialog by non-modal

    Hi
    I'm trying to achieve modal dialog functionality by non-modal (i have reasons to do that), but I have encountered a real problem:
    calling wait() from EDT is freezing everything. Below is source code, in most cases dialog is created inside action listener (in the EDT), so it is the source of problem:
    public class TestMyDialog {
         public TestMyDialog() {
              final JFrame jFrame = new JFrame();
              JPanel panel = new JPanel();
              JButton button1 = new JButton("open dialog");
              JButton button2 = new JButton("close");
              button1.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        System.out.println(SwingUtilities.isEventDispatchThread());
                        Object syncObject = new Object();
                        new MyDialog(jFrame, "title", syncObject);
                        try {
                             synchronized (syncObject) {
                                  syncObject.wait();
                        } catch (InterruptedException ex) {
                             ex.printStackTrace();
                        System.out.println("dialog closed");
              button2.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        System.exit(0);
              panel.add(button1);
              panel.add(button2);
              jFrame.getContentPane().add(panel);
              jFrame.setUndecorated(true);
              jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jFrame.pack();
              jFrame.setVisible(true);
         public static void main(String[] args) {
              new TestMyDialog();
    }And main class:
    * Dialog that imitates modal dialog.
    * @author ggg
    @SuppressWarnings("serial")
    public class MyDialog extends JDialog {
         private Frame ownerFrame;
         public MyDialog(Frame owner, String title, final Object syncObject) {
              super(owner, title, false); // modal = false
              this.ownerFrame = owner;
              JButton button1 = new JButton("close dialog");
              button1.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        ownerFrame.setFocusable(true);
                        ownerFrame.setEnabled(true);
                        setVisible(false);
                        dispose();
                        synchronized (syncObject) {
                             syncObject.notifyAll();
              add(button1);
              ownerFrame.setFocusable(false);
              ownerFrame.setEnabled(false);
              setSize(300, 200);
              setVisible(true);
         } // end of constructor
    }Any ideas would be highly appreciated.

    gimbal2 wrote:
    calling wait() from EDT is freezing everything.
    Any ideas would be highly appreciated. What about... don't ever block the EDT?Why do you mean by don't block the EDT? I'm using wait() because I need the calling thread to stop for a while (close dialog) but unfortunately this thread is EDT in case of ActionListeners....
    AndrewThompson64 wrote:
    gregory_33 wrote:
    ..I'm trying to achieve modal dialog functionality by non-modal (i have reasons to do that), ..What are those reasons?It was requirements from my boss, and please don't ask me why.... I just have to try to solve this.
    And thanks for interest for all of you.

  • How painting behind a JComponent ?

    Hi all,
    I'm trying to paint stuff like shadows, frames (not borders), etc. behind JComponents.
    So every shape only intersects with the relative JComponent's one.
    Cannot paint these stuff in the container's paintComponent() method since more widgets can have one or more of them, so I guess It should be better do the job in every child's paintComponent() method.
    What follows was the code I tested but doesn't work.
    Any hints ? Thanks in advance.
    Lucio
    import java.awt.*;
    import javax.swing.*;
    public class UpButton extends JButton {
        Dimension dimension = new Dimension(100, 100);
        Point point = new Point(100, 100);
        public UpButton(String text) {
         setSize(dimension);
         setLocation(point);
         setBackground(new Color(255,186,26));
         setText(text);
        public void paintComponent(Graphics g) {
         Component c = (Component) getParent();
         Graphics2D g2 = (Graphics2D)
                                      c.getGraphics().create(0,0,dimension.width,dimension.height);
         g2.translate(-(point.x + 10), -(point.y + 5));
         g2.setPaint(Color.gray);
         g2.fill(new Rectangle(dimension));
         g2.dispose();
         super.paintComponent(g);
        public static void main(String[] args) {
         JFrame jFrame = new JFrame();
         jFrame.getContentPane().setLayout(null);
         jFrame.add(new UpButton("Test"));
         jFrame.setSize(300,300);
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jFrame.setVisible(true);
    }

    I'm very grateful to you, weebib
    I was missing the setClip method, now perfectly works.
    It doesn't seems to me too difficult (now ;-)
    Here my modified version :
    import java.awt.*;
    import javax.swing.*;
    public class UpButton extends JButton {
        Dimension dimension = new Dimension(100, 100);
        Point point = new Point(100, 100);
        public UpButton(String text) {
         setSize(dimension);
         setLocation(point);
         setBackground(new Color(255,186,26));
         setText(text);
        public void paintComponent(Graphics g) {
         Graphics2D g2 = (Graphics2D) g.create();
         g2.translate(10, 5);
         g2.setClip(0, 0, 100, 100);
         g2.setPaint(Color.gray);
         g2.fill(new Rectangle(dimension));
         g2.dispose();
         super.paintComponent(g);
        public static void main(String[] args) {
         JFrame jFrame = new JFrame();
         jFrame.getContentPane().setLayout(null);
         jFrame.add(new UpButton("Test"));
         jFrame.setSize(300,300);
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jFrame.setVisible(true);
    }

  • Simple Question: JList and JDesktopPane in the same Swing app?

    Hi,
    I'm really inexperienced with Swing and so have hit what I think is quite a simple problem that I hope someone here can help me with.
    I have a class Frame which extends JFrame, I would like to have it contain a JTree running down the left hand side, with the rest of the JFrame taken up by a JDesktopPane. I have sorted out the code for both the JDesktopPane and the JTree independently, and can get them displaying on their own, but how can I display them side by side?
    I have a feeling that I have to use some layout manager of some sort and add the JTree and JDesktopPane to it, then add the layout to the JFrame or something but as you can tell I'm a little lost.
    I hope that this is a simple problem, it certainly seems quite fundamental and so I hope that someone can help!
    Thanks in advance
    Richard

    JFrame by default has a BorderLayout Manager
    so to add these two componets for the center one add it as usual, but for the other u have to add it
    JFrame.getContentPane().add(instance, BorderLayout.WEST);
    or any one of three other values.
    hope this is what u ask about

  • JWS 1.6.0_12 possible regression - can anyone verify?

    My company's application uses Java 1.4.2, and has some issues with later Java versions (event handling appears to have been done in an interesting way in our libraries that doesn't seem to upgrade properly). This is something I don't have the ability to change, much as I would like to.
    To ensure we can always use the correct version of Java, we therefore deploy the application using JWS, specifying J2SE Version 1.4 in the JNLP file.
    I've recently been investigating JWS 1.6.0, and have run into certain technical difficulties.
    * With JWS 1.6.0 and later (I've tried all the publicly available releases), I get 100% CPU usage whenever the application tries to load a class out of anything but the first JAR file. This may be an issue with the JAR files themselves, as I can't replicate with our other application. If anyone can offer any pointers on this, it'd be great (but I'm going to assume "broken JARs" and ignore it for now). Note that the exact same JNLP file and JAR files work fine in JWS 1.4 and 1.5 - it's just upgrading to JWS 1.6.0 or later that causes this issue.
    * With JWS 1.6.0_12, if the "homepage" is set to a non-responsive server, JWS fails to launch the application. This worked fine in JWS 1.6.0_11 - and seems odd; why would JWS try and contact the homepage for the application (note that this is nothing like the CodeBase or DocumentBase). The error received is as below:
    #### Java Web Start Error:
    #### No route to host: connect* With JWS 1.6.0_12, the application fails to start even once the homepage is set to a valid URL, when using the JRE 1.4.2. The error message below is shown. Note that this code works fine on JWS 1.6.0_11, and also works fine if the J2SE Version is set to 1.6 - so it appears to be a problem with the way JWS is launching JRE 1.4.2...
    Java Plug-in 1.6.0_12
    Using JRE version 1.4.2_19 Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\Aldata
    java.lang.Error: Do not use javax.swing.JFrame.setLayout() use javax.swing.JFrame.getContentPane().setLayout() instead
         at javax.swing.JFrame.createRootPaneException(Unknown Source)
         at javax.swing.JFrame.setLayout(Unknown Source)
         at sun.plugin2.applet.viewer.JNLP2Viewer$1.run(JNLP2Viewer.java:355)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)I think the "homepage" bug should be easy for anyone to verify, but I'd appreciate any tips anyone can give me on where best to follow on the Swing error with JRE 1.4.2, or if anyone has ever encountered a similar 100% CPU issue using JWS - I just don't know where to start on that one (Google wasn't helpful!)

    Hi there,
    Our team supports a 1.4.2 application running at our company, and we have experienced a similar CPU usage issue now that the users have JWS 1.6 installed on their PCs for other reasons.
    The app now takes about 30 seconds to even appear to the user where it used to take 3 seconds or so in JWS 1.4.2. This is against JWS 1.6.0_12. The app appears to be taking forever to load classes from a large jar file (WebLogic's weblogic.jar file, 35 MB in size). And the app runs through memory at an incredible rate, consuming 3 MB or so to load a single class. I haven't found any solutions online. I figured I would try to look at the JNLPClassLoader source at some point and see if I could understand why it's doing so much work.

  • Controlling events between classes

    hello
    i know i'm asking a lot, but i couldn't find anything. the problem is i've got a jframe and some panels with buttons.
    eg:
    class A extends JFrame
    getContentPane().add( B ) ;
    getContentPane().add( C ) ;
    class B extends JPanel
    add( button1 ) ;
    add( button2 ) ;
    class C extends JPanel
    add( button3 ) ;
    add( button4 ) ;
    where do i add ActionListeners? how do i pass information between classes? if button1 is clicked -> class A should know it.
    i tried to do this in class A: objectOfB.button1 (access button1 directly) - didn't work - why?
    if a button1 is clicked i want to remove the jpanel and replace it with another one. how should i do this?
    Thank You All

    Check out the java tutorials. There are great examples that show you how to do what you want to do

  • Writing a Java Web Browser

    I'm trying to write a simple Java based browser. Can anyone please help me with this code. I can't get it to load the URL
    please help
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.lang.*;
    import javax.swing.text.*;
    public class Browser extends JPanel implements ActionListener {
         Browser() {
              JPanel p = new JPanel();
              p.setLayout(new BorderLayout(5,5));
              final JEditorPane jt = new JEditorPane();
              final JTextField input = new JTextField("http://java.sun.com");
              //make read only
              jt.setEditable(false);
              //follow links
              jt.addHyperlinkListener(new HyperlinkListener () {
                   public void hyperlinkUpdate(
                        final HyperlinkEvent e) {
                             if (e.getEventType() ==
                                  HyperlinkEvent.EventType.ACTIVATED) {
                                       SwingUtilities.invokeLater(new Runnable() {
                                            public void run() {
                                                 //Save original
                                                 Document doc = jt.getDocument();
                                                 try {
                                                      URL url = e.getURL();
                                                      jt.setPage(url);
                                                      input.setText(url.toString());
                                                 } catch (IOException io) {
                                                      JOptionPane.showMessageDialog(
                                                           Browser.this, "Can't follow link",
                                                           "Invalid Input",JOptionPane.ERROR_MESSAGE);
                                                      jt.setDocument(doc);
                             JScrollPane pane = new JScrollPane();
                             pane.setBorder(
                                  BorderFactory.createLoweredBevelBorder());
                             pane.getViewport().add(jt);
                             p.add(pane, BorderLayout.CENTER);
                             input.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent e) {
                                       try {
                                            jt.setPage(input.getText());
                                       } catch (IOException ex) {
                                            JOptionPane.showMessageDialog(
                                                 Browser.this,"Invalid URL","Invalid Input",JOptionPane.ERROR_MESSAGE);
                                  p.add(input, BorderLayout.SOUTH);
                                  JFrame f = new JFrame();
                                  f.getContentPane().add(p);
                                  //f.getContentPane().setSize(400,400);
                                  f.setVisible(true);
                             public void actionPerformed(ActionEvent e) {}
                             public static void main(String[] args) {
                                  Browser b = new Browser();
                                  b.setSize(500,500);
                        }

    i made a few changes and it works.
    i have marked the changes.
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.lang.*;
    import javax.swing.text.*;
    public class Browser extends JFrame implements ActionListener {     Browser() {
              JPanel p = new JPanel();
              p.setLayout(new BorderLayout(5,5));
              final JEditorPane jt = new JEditorPane();
              final JTextField input = new JTextField("http://java.sun.com");
              //make read only
              jt.setEditable(false);
              //follow links
              jt.addHyperlinkListener(new HyperlinkListener () {
                        public void hyperlinkUpdate(final HyperlinkEvent e) {
                             if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                  SwingUtilities.invokeLater(new Runnable() {
                                            public void run() {
                                                 //Save original
                                                 Document doc = jt.getDocument();
                                                 try {
                                                      URL url = e.getURL();
                                                      jt.setPage(url);
                                                      input.setText(url.toString());
                                                 catch (IOException io) {
                                                      JOptionPane.showMessageDialog
                                                           ( Browser.this, "Can't follow link",
                                                             "Invalid Input",JOptionPane.ERROR_MESSAGE);
                                                      jt.setDocument(doc);
              JScrollPane pane = new JScrollPane();
              pane.setBorder(BorderFactory.createLoweredBevelBorder());
              pane.getViewport().add(jt);
              p.add(pane, BorderLayout.CENTER);
              input.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             try {
                                  jt.setPage(input.getText());
                             } catch (IOException ex) {
                                  JOptionPane.showMessageDialog
                                       ( Browser.this,"Invalid URL","Invalid Input",JOptionPane.ERROR_MESSAGE);
              p.add(input, BorderLayout.SOUTH);
              //JFrame f = new JFrame();          getContentPane().add(p);
              //f.getContentPane().setSize(400,400);
              setVisible(true);
              this.addWindowListener(new java.awt.event.WindowAdapter() {                    public void windowClosing(java.awt.event.WindowEvent e) {
                             System.exit(0);
         public void actionPerformed(ActionEvent e) {}
         public static void main(String[] args) {
              Browser b = new Browser();
              b.setSize(500,500);
    }

  • HTML in a JAVA application

    Hello all
    I have a JAVA program and i have to display an HTML document (with tags and e.t.c.) in the way Internet explorer displays it (with the colors and all that stuff) Can i convert the plain text:
    <HTML>sdfsdf
    <h1>sdfsdf
    to a colored one?
    Thanks in advance!!

    You can try something like this...import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    public class Test extends JFrame
      private JEditorPane htmlPane = new JEditorPane();
      Test(URL url)
        super();
        try
          htmlPane.setPage(url);
        catch (IOException _ex)
          _ex.printStackTrace();
        init();
      private void init()
        JScrollPane s = new JScrollPane(htmlPane);
        JPanel p = new JPanel();
        JFrame frame = new JFrame();
        getContentPane().add(s);
        validate();
        setSize(700, 700);
        centerComponent(this);
        setVisible(true);
      public static void main(String[] args)
        if ( args.length != 1 )
          System.out.println("usage: java Test2 <fileName>");
          return;
        File file = new File(args[0]);
        if ( !file.exists())
          System.out.println("File not found: "+file.getAbsolutePath());
          return;
        try
          URL url = file.toURL();
          JFrame frame = new Test(url);
          frame.setVisible(true);
        catch (MalformedURLException _ex)
          _ex.printStackTrace();
      public static void centerComponent(Component target)
        target.validate();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = target.getSize();
        frameSize.width  = Math.min(frameSize.width, screenSize.width);
        frameSize.height = Math.min(frameSize.height, screenSize.height);
        target.setLocation(
          (screenSize.width - frameSize.width) / 2,
            (screenSize.height - frameSize.height) / 2);
    }Cheers, HJK

Maybe you are looking for

  • How can I exit my UNIX script when my PLSQL script in it calls an error?

    hello. I hope someone can help with my error handling and exiting-in-the-right-place problem. I have several PLSQL scripts that are called from a UNIX script to insert/update employee records in ORACLE Financials. At the end of the UNIX script, depen

  • Service component:  java.lang.NoSuchMethodException: java.util.Vector.isX()

    Hi everybody: I created a Mobile service component and a Data Structure with 3 attributes. I created and instantiated the collection and showed all objects in a table but I´m getting the following error:java.lang.NoSuchMethodException: java.util.Vect

  • Finder folder deletion bug

    OK, I've had it with this problem. It has bitten me several times over the years. Imagine that you have a folder of documents and folders. You use a keyboard command (cmd-delete) to delete one folder after having looked in the folder in column view.

  • Problem creating Service POs with BAPI_PO_CREATE1

    Hi. I'm trying to create service POs with data that i read from an excel file, to do this I'm using the bapi: <b>BAPI_PO_CREATE1</b> I'm passing the following parameters: IMPORT: - poheader - poheaderx TABLES: - return - poitem - poitemx - poaccount

  • I have little to no signal in an area that says I should have great signal.

    My verizon I- phone 5S has poor to no Verison signal at my house. I can get 3 bars extended, but it will intermittently grab a verizon tower, give me one bar, then i can't make any calls (No cellular Functionality). What can verizon do to fix the poo