Set size JPanel inside a JFrame

I�m trying to set the size of a custom JPanel inside of a custom JFrame
my code looks like this
public class myFrame extends JFrame
    public myFrame()
     //This set the size of JFrame but i dont want this
        //setSize(300,600);
        //add panel to frame
        MyPanel panel = new myPanel();
        Container contentPane = getContentPane();
        contentPane.add(panel);
class MyPanel extends JPanel
     public MyPanel()
          setSize(300, 600); //This don�t work, why??
          validate();
}Why wont setSize(300, 600) work inside class myPanel ???

@Op
You need to read a tutorial on layout managers. It looks like you don't know how they work.
The panel should call setPreferredSize, and the frame should call pack just before you are displaying the frame.
Kaj

Similar Messages

  • Setting size JScrollPane inside a JSplitPane

    Hi,
    In my program I want to have two panels, one above the other. The first panel will contain a row of objects that will be dynamically generated. These objects will have an unchangeable height, which I only know after construction. The second panel, below the first panel, will contain a column of objects, which will also be dynamically generated. These objects will take up almost the screen width.
    The following code explains what I am trying to accomplish here.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JSplitPaneProblem extends JPanel
    implements ActionListener {
         static Color background;
         static String [] csdEngineers = { "jdoe1", "jdoe2", "jdoe3", "jdoe4", "jdoe5",
              "jdoet", "amacadam" };
         static String [] engineers = { "Choose one", "jdoe1", "jdoe2", "jdoe3", "jdoe4", "jdoe5",
              "jdoet", "amacadam" };
         static int width;
         static int height;
         static int remainingWidth;
         static int insets;
         static int labelWidth;
         static JScrollPane problemPane;
         static JPanel problemPanel;
         static int BIGNUMBER = 1;
         public JSplitPaneProblem () {
              setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
              //Get the image to use.
              ImageIcon trafficLight = createImageIcon("trafficlight.gif");
              JLabel trafficLightLabel = new JLabel (trafficLight);
              if (trafficLight != null) {
                   width = trafficLight.getIconWidth();
                   height = trafficLight.getIconHeight();
              else {
                   width = 100;
                   height = 300;
              trafficLightLabel.setPreferredSize(new Dimension (width, height + 50));
              //Set up the scroll pane.
              JScrollPane trafficLightPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              JPanel trafficLightPanel = new JPanel();
              trafficLightPanel.setLayout(new BoxLayout(trafficLightPanel, BoxLayout.LINE_AXIS));
              for (int i=0; i < BIGNUMBER; i++) {
                   trafficLight = createImageIcon("trafficlight.gif");
                   trafficLightLabel = new JLabel (trafficLight);
                   trafficLightPanel.add(trafficLightLabel);
              trafficLightPane.setViewportView(trafficLightPanel);
              trafficLightPane.setPreferredSize(new Dimension(width, height));
              trafficLightPane.setMinimumSize(new Dimension(width, height));
              Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
              width = dimension.width;
              height = 36;
              insets = 4; // Number of pixels to left and/or right of a component
              labelWidth = 40;
              setBounds (0, 0, dimension.width, dimension.height);
              // Set up the problem panel.
              JScrollPane problemPane = new JScrollPane (ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              problemPanel = new JPanel();
              // And a new problem pane, to which the problem panel is added
              problemPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              problemPane.setViewportView(problemPanel);
              // Set up the JSlitPane
              JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,trafficLightPane,problemPane);
              splitPane.setOneTouchExpandable(true);
              add(splitPane);
          * The screen is divided in two equal sized halves, a left and a right side. Each
          * half is divided into 3 parts. remainingWidth is used to calculate the remaining
          * width inside a half.
         public static JPanel addProblem (String organisation, String problem) {
              JPanel panel = new JPanel (); // JPanel has FlowLayout as default layout
              panel.setPreferredSize(new Dimension (width, height));
              // First half, containing serverId, customer name, and problem title
              // serverId
              JTextArea serverId = new JTextArea ("99999");
              Font usedFont = new Font ("SanSerif", Font.PLAIN, 12);
              serverId.setFont(usedFont);
              serverId.setPreferredSize(new Dimension(labelWidth, height));
              serverId.setBackground(background);
              panel.add(serverId);
              // Organisation name. Gets 1/3 of remaining width
              remainingWidth = (width/2 - (int)serverId.getPreferredSize().getWidth())/3 - insets;
              JTextArea organisationArea = new JTextArea (organisation);
              organisationArea.setPreferredSize(new Dimension (remainingWidth, height));
              organisationArea.setAlignmentX(SwingConstants.LEFT);
              organisationArea.setBackground(background);
              organisationArea.setLineWrap(true);
              organisationArea.setWrapStyleWord(true);
              organisationArea.setEditable(false);
              panel.add(organisationArea);
              // Problem title
              JTextArea problemArea = new JTextArea (problem);
              problemArea.setPreferredSize(new Dimension (remainingWidth*2, height));
              problemArea.setBackground(background);
              problemArea.setLineWrap(true);
              problemArea.setWrapStyleWord(true);
              problemArea.setEditable(false);
              panel.add(problemArea);
              // Second half, containing severity, CSD and Engineer
              // Severity
              JTextArea severity = new JTextArea ("WARN");
              severity.setFont(usedFont);
              severity.setBackground(background);
              severity.setPreferredSize(new Dimension(labelWidth, height));
              panel.add(severity);
              // CSD
              JLabel csdField = new JLabel("CSD:");
              csdField.setFont(usedFont);
              JComboBox csdList = new JComboBox(csdEngineers);
              csdList.setFont(usedFont);
              csdList.setSelectedIndex(6);
              // csdList.addActionListener(this);
              panel.add(csdField);
              panel.add(csdList);
              // Solver, another ComboBox
              JLabel engineerField = new JLabel("Solver:");
              engineerField.setFont(usedFont);
              JComboBox engineerList = new JComboBox(engineers);
              engineerList.setFont(usedFont);
              engineerList.setSelectedIndex(0);
              // engineerList.addActionListener(this);
              panel.add(engineerField);
              panel.add(engineerList);
              // Empty panel to be added after this panel
              JPanel emptyPanel = new JPanel();
              emptyPanel.setPreferredSize(new Dimension (width, 15));
              return panel;
          * ActionListener
          * @param args
         public void actionPerformed(ActionEvent event) {
              System.out.println ("Burp");
         private static ImageIcon createImageIcon(String path) {
              java.net.URL imgURL = JSplitPaneProblem.class.getResource(path);
              if (imgURL != null) {
                   return new ImageIcon(imgURL);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         private static void createAndShowGUI() {
              //Create and set up the window.
              JFrame frame = new JFrame("JSlitPaneProblem");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Set the size of the window so in covers the whole screen
              Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setBounds (0, 0, dimension.width, dimension.height);
              //Create and set up the content pane.
              JComponent newContentPane = new JSplitPaneProblem();
              newContentPane.setOpaque(true); //content panes must be opaque
              frame.setContentPane(newContentPane);
              //Display the window.
              //frame.pack();
              frame.setVisible(true);
              // Add panels
              problemPanel.setPreferredSize(new Dimension(dimension.width, dimension.height - height));
              for (int j=0; j < BIGNUMBER; j++) {
                   problemPanel.add(addProblem("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch Computer Shop",
                   "expected string or buffer, but that is not everyting, as this problem description is extremely long. And as I am chatty, I add some more length"));
                   JPanel emptyPanel = new JPanel();
                   emptyPanel.setPreferredSize(new Dimension (width, 15));
                   problemPanel.add(addProblem("My Company", "I have no problem"));
         public static void main(String[] args) {
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }If you want to try it out with the trafficlight.gif mentioned in the code, get it from
    http://www.hermod.nl/images/trafficlight.gif
    The problem I have with the current code is that in the following line
    trafficLightLabel.setPreferredSize(new Dimension (width, height + 15));I try to set the size of the top panel, but the program disregards what I instruct it to do.
    When BIGNUMBER = 1, you will see that part of the bottom of the image is not shown.
    Can you help me?
    Abel
    Edited by: Abel on Feb 27, 2008 2:20 PM
    Added
    static int BIGNUMBER = 1; and where it is used. If you want to play with the program, change BIGNUMBER to for instance 10

    Found it. Add
    splitPane.resetToPreferredSizes();as last instruction in createAndShowGUI().

  • Maximizing JPanel inside a JFrame

    Hi guys. I have a jpanel inside a part of a jframe (1/4 of it) and I want to do two things
    1) Suppose I have a 'maximize' button inside this jpanel. I want when I press this button to make the jpanel take up the whole jframe's space instead of just 1/4 of it.
    2) When I maximize the jframe ( completely different than before) the jpanel's size remains the same. What I want is to make it take as much space as it "deserves" - 1/4 of the jframe.
    Could anyone help with these things? Thanks in advance

    I am only interested at (1) now. So what I have is a jpanel with flowlayout and two components inside. Another jpanel with flowlayout with a textpane inside and a jpanel with boxlayout that contains the two panels (placed vertically). Finally a jframe that contains this jpanel

  • JPanel inside a JFrame

    How do you make a JPanel resize automatically with its parent JFrame?
    Thanks,
    -Zom.

    Use BorderLayout for the JFrame and set the JPanel at centre like this:myJFrame.getContentPane().setLayout(new BorderLayout());
    myJFrame.getContentPane().add(myPanel,  JFrame.CENTER);

  • Several Jpanels in a JFrame

    Hi,
    I have three buttons in Jtoolbar and a JPanel inside a JFrame. Now my program is supposed to work in the follwoing way-
    when I click a button a new JPanel containing general information comes in that fixed Jpanel place in that JFrame.
    When I press another button "a form" should come.
    When I press the third button then the a Jtable will come.
    Now all these should come in the same place inside that JFrame. So, when I press the JToggleButtons then how to call and set up so that the Jpanels replace each other?
    Please post some example if possible along with your advice.
    Thanks a lot in advance.

    I figured what the heck, here's a trivial example of card layout:
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    * main jpanel that is added to a jframe's contentPane
    * this main panel uses a borderlayout and places a label
    * in the north position, a swap button in the south
    * position, and a jpanel in the center position that uses
    * the cardlayout. 
    * @author Pete
    public class CardPracticeMainPanel extends JPanel
        private static final long serialVersionUID = 1L;
        private JButton swapButton = new JButton("Swap Panels");
        private CardLayout cardlayout = new CardLayout();
        private JPanel cardLayoutPanel = null;
        public CardPracticeMainPanel()
            int ebGap = 20;
            setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
            setLayout(new BorderLayout());
            cardLayoutPanel = createCardLayoutPanel();
            add(createNorthPanel(), BorderLayout.NORTH);
            add(cardLayoutPanel, BorderLayout.CENTER);
            add(createSouthPanel(), BorderLayout.SOUTH);
        public void addCard(JPanel panel, String string)
            cardLayoutPanel.add(panel, string);
        private JPanel createNorthPanel()
            JPanel p = new JPanel();
            JLabel titleLabel = new JLabel("CardLayout Practice Program");
            titleLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 24));
            p.add(titleLabel);
            return p;
        private JPanel createCardLayoutPanel()
            JPanel p = new JPanel();
            p.setLayout(cardlayout);
            return p;
        private JPanel createSouthPanel()
            JPanel p = new JPanel();
            p.add(swapButton);
            swapButton.addActionListener(new SwapButtonListener());
            return p;
        private class SwapButtonListener implements ActionListener
            public void actionPerformed(ActionEvent arg0)
                cardlayout.next(cardLayoutPanel);
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    * the "driver" program that creates a JFrame and places a
    * CardPracticeMainPanel into the contentpane of this jframe.
    * It also adds JPanel "cards" to the CardPracticeMainPanel object.
    * @author Pete
    public class CardPracticeTest
        private static Random rand = new Random();
        private static void createAndShowGUI()
            // create the main panel and add JPanel "cards" to it
            CardPracticeMainPanel mainPanel = new CardPracticeMainPanel();
            for (int i = 0; i < 4; i++)
                JPanel card = new JPanel();
                card.setPreferredSize(new Dimension(600, 400));
                card.setBorder(BorderFactory.createLineBorder(Color.blue));
                String panelString = "panel " + String.valueOf(i + 1);
                card.add(new JLabel(panelString));
                mainPanel.addCard(card, panelString);
                card.setBackground(new Color(
                        127 * rand.nextInt(3),
                        127 * rand.nextInt(3),
                        127 * rand.nextInt(3)));
            JFrame frame = new JFrame("CardLayout Practice Application");
            frame.getContentPane().add(mainPanel); // add main to jframe
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // let's show the jframe in a thread-safe manner
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • 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

  • Set size of jPanel

    Hi i've create a jForm in netbeans. To this I have added a scrollpane containing a jPanel called PrintPreview. (I have to do this rather than use the automated preview of printUtilities because of some items I need removed from the original jPanel before printing).
    I need to set the size of the PrintPreview jPanel as it's instantiated. I have the dimensions created from another class called "Gbl".
    In the constructor is the following:
    /** Creates new form PrintPreview */
    public PrintPreview() {
    PreviewPanel.setPreferredSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
    PreviewPanel.setMaximumSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
    PreviewPanel.setMinimumSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
    Window.pack();
    initComponents();
    this.setLocationRelativeTo(null);
    // ADD CODE - COLLECT DRAWING FROM ARRAY
    PreviewPanel.repaint();
    I would like the jPanel set to these dimensions however I would also like the scrollPane to remain at it's standard size so I can scroll the diagram as necessary.
    Could you please tell me where I am going wrong? The three setSize lines are flagged as erroneous. The dimensions are int and have tried double.
    Any advice is good...
    Thanks

    Ok I'm going to add onto this thread because it still relates to the original problem. setting size of jPanel.
    Some details first:
    OS - Ubuntu Gutsy 7.10
    Kernel - 2.6.22-14-generic
    NB - v5.5.1
    Java version - java version "1.5.0" / gij (GNU libgcj) version 4.2.1 (Ubuntu 4.2.1-5ubuntu5)
    Research:
    I have been trawling the net for days trying to resolve this but I am struggling to find anything specific to my problem. I keep finding general methods using given NB facilities. I've also scoured a couple of my Java books but of course they're not totally relevant to NetBeans. I've practiced using the forum this afternoon to find things but with my lack of knowledge using both forums and java has left me a little bamboozled. I've been working on this problem for a couple of days now and achieved very little.
    My specific problem is this:
    I have a JFrame GUI. Inside that I have a jTabbedPane containing a jScrollPane containing a jPanel. I would like to have the jPanel display at A4 size relevant to the screen it is displayed on. e.g. I have a separate global class "Gbl" that calculates the dimensions based on current dpi and then creates the necessary measurements to feed to my preferred size function.
    I have tried implementing the preferred size method to the constructor and have also tried adding it to all four ways to enter bespoke code to NetBeans' autogenerated code. (Pre-init, Post-init, Pre-creation and Post-creation code) To no avail. Nothing changes on screen.
    The code I am trying to enter is as follows:
    // Set preferred size of user-drawing-area (jPanel1)
    jPanel1.setPreferredSize(new java.awt.Dimension(600,500));
    jPanel1.setMaximumSize(new java.awt.Dimension(600,500));
    jPanel1.setMinimumSize(new java.awt.Dimension(600,500));
    // Set preferred size of jPanel1 container (jScrollPane1)
    jScrollPane1.setPreferredSize(new java.awt.Dimension(600,500));
    jScrollPane1.setMaximumSize(new java.awt.Dimension(600,500));
    jScrollPane1.setMinimumSize(new java.awt.Dimension(600,500));
    // Set preferred size of the jScrollPane1 container (mainTabView(Tabbed pane))
    mainTabView.setPreferredSize(new java.awt.Dimension(600,500));
    mainTabView.setMaximumSize(new java.awt.Dimension(600,500));
    mainTabView.setMinimumSize(new java.awt.Dimension(600,500));
    I am using absolute values here to omit any error getting the variables from my Global class. If it works I will add them and test again.
    Ideally, I would like the jPanel to be set to an A4 size yet have the containers at a smaller more "screen-manageable" size (With scroll bars). Then if the GUI is maximized, then it only expands to the full size of the A4 sized jPanel if possible.
    Of course, this may not be possible or there may be a far better method for doing this, however I am really stumped. I've had some good advice this afternoon of whihc has opened may eyes some. Although, I have made no headway so far. I hope the above follows site-rules and gives enough information to resolve this issue. I'm losing hair rapidly!
    I'm grateful for any advice given. Thank You

  • Placing JPanels in a JFrame

    Hi,
    In my program I plan to put JPanels, containing Traffic Lights (data calculated somewhere else in my program) inside a JFrame. At the moment I have a problem with getting the panels where I want them.
    When I construct the JFrame, I set its size to be screen wide, and a bit less higher than screen height:
    public class TlsFrame extends JFrame implements WindowListener,
                                                    Observer {
         private JComponent component;
         public TlsFrame (String title, TlsModel theModel, TlsView theView) {
              super(title);
              model = theModel;
              model.addObserver(this);
              view = theView;
              // Default close operation
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              addWindowListener (new CloseListener() );
              setup();   
         private void setup () {
              setBackground (Color.WHITE);
              setLayout(new GridBagLayout());
              // Set the size of the window so in covers the whole screen
              dimension = Toolkit.getDefaultToolkit().getScreenSize();
              setBounds (0, 0, dimension.width, dimension.height - 200);
              // Create the Menu bar
              tlsMenu = new TlsMenu(model);
              tlsMenu.createMenuBar();         
              // Create the Panel used to log in (replaced later with the traffic lights)
              logInPanel = new LogInPanel(model);
              add(logInPanel);
              logInPanel.requestFocusInWindow();
              setVisible (true);
         }After logging in, I am ready to display the traffic lights:
         private void setUpTrafficLights() {
              // Remove all previous traffic lights from the panel
              if (component != null) {
                   removeAll();
              component = createComponent();
              add(component);
              setVisible (true);
         private JComponent createComponent () {
              JPanel panel = new JPanel ();
              panel.setBounds (0, 0, dimension.width, 300);
              // X coordinate for the different traffic lights
              int xCoordinate = 0;
              // Add the Customers as TrafficLights to the panel
              for (int i = 0; i < view.getTrafficLights().size(); i++) {
                   TrafficLight light = (TrafficLight) view.getTrafficLights().get(i);
                   light.setBounds(INSETS + xCoordinate, INSETS, light.getWidth(), light.getHeight());
                   System.out.printoln ("info", "TlsFrame.createComponent: light.getBounds()=" + light.getBounds());
                   xCoordinate += light.getWidth();
                   panel.add(light);
              return panel;
         }The logging I get about this part is:
    TlsFrame.createComponent: light.getBounds()=java.awt.Rectangle[x=2,y=2,width=144,height=266]
    TlsFrame.createComponent: light.getBounds()=java.awt.Rectangle[x=146,y=2,width=100,height=266]
    TlsFrame.createComponent: light.getBounds()=java.awt.Rectangle[x=246,y=2,width=108,height=266]But although I place my TrafficLight's to be placed on the top row, they are placed in the middle of my screen. And that is not what I expected. Is there a LayoutManager I need to set, or set to null (tried it, but that did not help)?
    Abel
    Edited by: Abel on Feb 12, 2008 9:31 AM
    I just found out I use the BorderLayout

    Found it.
         private void setUpTrafficLights() {
              // Remove all previous traffic lights from the panel
              if (component != null) {
                   removeAll();
              component = createComponent();
              add(component);
              this.setLayout(null);
              addItem ("info", "TrlsFrame.setUpTrafficLights: current layoutManager is " +
                        this.getLayout());
              setVisible (true);
         }Logging is your friend:
    while (problemNotFound) {
        addLogging();
    }

  • How to set size of buttons

    hi,
    I am working on the GUI. There are four buttons. I wanted the button's width to be just enough to show the text inside the button and not "...." or bigger than required. How should I edit my code, which is shown below?
    Thanks in advance
    regards
    * GridBagLayoutDemo.java is a 1.4 application that requires no other files.
    import java.awt.*;
    import javax.swing.*;
    public class GridBagLayoutDemo {
        final static boolean shouldFill = true;
        final static boolean shouldWeightX = true;
        final static boolean RIGHT_TO_LEFT = false;
        public static void addComponentsToPane(Container pane) {
            if (RIGHT_TO_LEFT) {
                pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
              GridBagLayout gbl = new GridBagLayout();
             container.setLayout(gbl);
             gbl.layoutContainer(container);
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.HORIZONTAL; //natural height, maximum width
              recv = new JEditorPane();
              recv.setEditorKit(new HTMLEditorKit());
              recv.setEditable(false);
              JScrollPane pane
                   = new JScrollPane(recv,
                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                             JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              c.ipady = 200;      //make this component tall
            c.weightx = 1.0;
            c.weighty = 1.0;   //request any extra vertical space
            c.gridwidth = 8;
            c.gridx = 0;
            c.gridy = 0;
            container.add(pane, c);
              to_reply = new JCheckBox("Reply to latest message", true);
                c.gridx = 0;
            c.gridy = 1;
            c.gridwidth = 4;
            container.add(to_reply, c);
              type = new JTextArea();
              type.setFont(new Font("Arial",Font.PLAIN,11));
              type.setLineWrap(true);
              JScrollPane typepane
                   = new JScrollPane(type,
                             JScrollPane.VERTICAL_SCROLLBAR_NEVER,
                             JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              c.ipady = 50;
              c.weightx = 1.0;
              c.gridx = 0;
            c.gridy = 2;
            c.gridwidth = 6;
            container.add(typepane, c);
              send = new JButton("Send");
              c.fill = GridBagConstraints.NONE;
              c.gridx = 5;
            c.gridy = 2;
            c.ipady = 10;
            c.anchor = GridBagConstraints.LINE_END;
            container.add(send, c);
            String num_msg_just_inserted = "Newly inserted messages : 0";
              num_msg_inserted = new JLabel(num_msg_just_inserted);
              c.gridx = 0;
              c.weightx = 1.0;
            c.gridy = 3;
            //c.gridwidth = 2;
            container.add(num_msg_inserted, c);
              see = new JButton("See");
              see.setBounds(235,220,65,20);
              see.setEnabled(false);
              c.fill = GridBagConstraints.NONE;
              c.anchor = GridBagConstraints.LINE_START;
              c.ipadx = 2;
                 c.ipady = 2;
              c.gridx = 1;
            c.gridy = 3;
            container.add(see, c);
              previous_msgs = new previous_messages(thisframe);  
            previous_msgs.setBounds(10,200,220,20);
            msgPosiArray = new msgPositionArray();
            c.weightx = 1.0;
            c.gridx = 0;
            c.gridy = 4;
            c.gridwidth = 4;
            container.add(previous_msgs, c);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("GridBagLayoutDemo");
            this.setSize(550,500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set up the content pane.
            addComponentsToPane(frame.getContentPane());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    90% of people's layout woes on this forum seem tostem from the fact that they use GridBagLayout.
    I'll second that.
    And I will third that!
    If you read this article from Sun it practically ignores GridBagLayout and mentions that GridBagLayout should only be used by GUI builders. It is a dated article (it preedates BoxLayout) but is very informative in its own right. I have a suspicion that Sun meant GridBagLayout to be used by GUI builders rather than hand coded.
    http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/shortcourse.html
    As far as using setPreferredSize, setMinimumSize, and setMaximumSize it is up to each layout manager whether they honer those setting. Among the layout managers included in the JDK I don't believe any of them honor setMaximumSize. Only GridBagLayout honors setMinimumSize, and then they all honor at least one component (i.e. height or width) of setPreferredSize.
    Don't take that as gospel but I believe that to be correct.
    As has already been pointed out it isn't good to set the size to a hard value. It won't play nice with all look and feels.

  • Refreshing a set of JPanels

    Hello there,
    I have an issue with refreshing and replacing my JPanel colors. As you can see, the format is GridLayout with the size of the grid changing based on what file they open. My issue is that when a second file is opened, it merely adds those JPanels to the end of the previously loaded set of JPanels. I've tried refresh() and repaint() but to no avail. Maybe I placed them in the wrong place, not sure. Thanks in advance.
              if (actionCommand.equals("Open..."))
                   JFileChooser fileChooser = new JFileChooser();
                   fileChooser.setDialogTitle("Choose a file");
                   this.getContentPane().add(fileChooser);
                   fileChooser.setVisible(true);
                   int result = fileChooser.showOpenDialog(this);
                   File file = fileChooser.getSelectedFile();
                   GridMap gm = new GridMap();
                   gm.read(file);
                   int row = gm.getRow();
                   int col = gm.getColumn();
                   setLayout(new GridLayout(row,col));
                   for (int i = 0; i < row; i++)
                        for (int j = 0; j < col; j++)
                             JLabel color = new JLabel();
                             color.setOpaque(true);
                             if (gm.getGrid(i,j) == 'O')
                                  color.setBackground(Color.GREEN);
                             else if (gm.getGrid(i,j) == 'F')
                                  color.setBackground(Color.RED);
                             else if (gm.getGrid(i,j) == 'H')
                                  color.setBackground(Color.BLACK);
                             add(color);
              }

    something along these lines
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    public class MainFrame2
      private static final String EXIT = "Exit";
      private static final String OPEN = "Open...";
      private static final String START = "Start";
      private JPanel mainPanel = new JPanel();
      private JPanel gridPanel = new JPanel();
      public MainFrame2()
        mainPanel.setPreferredSize(new Dimension(300, 300));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(gridPanel, BorderLayout.CENTER);
      public JComponent getPanel()
        return mainPanel;
      public JMenuBar createMenu()
        JMenu sim = new JMenu("Simulator");
        MenuListener menuListener = new MenuListener();
        JMenuItem m = new JMenuItem(OPEN);
        m.addActionListener(menuListener);
        sim.add(m);
        m = new JMenuItem(START);
        m.addActionListener(menuListener);
        sim.add(m);
        sim.addSeparator();
        m = new JMenuItem(EXIT);
        m.addActionListener(menuListener);
        sim.add(m);
        JMenuBar mBar = new JMenuBar();
        mBar.add(sim);
        return mBar;
      private class MenuListener implements ActionListener
        public void actionPerformed(ActionEvent e)
          String actionCommand = e.getActionCommand();
          if (actionCommand.equals(OPEN))
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Choose a file");
            //mainPanel.add(fileChooser);
            fileChooser.setVisible(true);
            int result = fileChooser.showOpenDialog(mainPanel);
            if (result == JFileChooser.APPROVE_OPTION)
              File file = fileChooser.getSelectedFile();
              GridMap gm = new GridMap();
              gm.read(file);
              int row = gm.getRow();
              int col = gm.getColumn();
              gridPanel.setLayout(new GridLayout(row, col));
              gridPanel.removeAll();
              for (int i = 0; i < row; i++)
                for (int j = 0; j < col; j++)
                  JLabel color = new JLabel();
                  color.setOpaque(true);
                  if (gm.getGrid(i, j) == 'O')
                    color.setBackground(Color.GREEN);
                  else if (gm.getGrid(i, j) == 'F')
                    color.setBackground(Color.RED);
                  else if (gm.getGrid(i, j) == 'H')
                    color.setBackground(Color.BLACK);
                  gridPanel.add(color);
          else if (actionCommand.equals(START))
            // setVisible(true);
          else if (actionCommand.equals(EXIT))
            Window window = SwingUtilities.getWindowAncestor(mainPanel);
            window.dispose();
      private static void createAndShowGUI()
        MainFrame2 frame2 = new MainFrame2();
        JFrame frame = new JFrame("Fire Saving Simulator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(frame2.getPanel());
        frame.setJMenuBar(frame2.createMenu());
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        javax.swing.SwingUtilities.invokeLater(new Runnable()
          public void run()
            createAndShowGUI();
    }

  • Unable to paint (using paint() in JPanel) inside mouse listeners

    This is hard to explain but I'll do my best :)
    I've created a little game and at some point I needed to make images "move" on the JPanel (through paint()), on a checkers-based game board.
    The game works like so:
    it has a mouse listener for clicks and movement, and the main game process is THINK(), REPAINT(), which is repeated until the user wins (the above is inside a while).
    The mouse actions were added to the constructor so they are always active, THINK changes the enemy's locations, and REPAINT simply calls "paint()" again.
    The picture is either an enemy or the player, and it can only "rest" on squares.
    (e.g. point's x and y must be divided in 50).
    While doing that, I wanted to make the movement more sleek and clean,
    instead of them simply jumping from one square to the other with a blink of the eye.
    So, I've created MOVEACTOR, that "moves" an enemy or a player from its current point (actor.getPoint()) to the requested future square (futurePoint).
    //actor = enemy or player, has getPoint() that returnes the current point on the board where he rests on.
    //futurePoint = the new point where the enemy or player should be after the animation.
    //please ignore obvious stuff that has nothing to do with what I asked -- those will be deleted in the future, for they are only temporary checking extra lines and stuff.
    //also feel free to ignore the "jumpX" things. Those are just to change images, to imitate physical "jumping" animation.
    protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");
         }I use the above on several occasions:
    [1] When an enemy moves. Summary:
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             moveActor(actors[currentVillain], futurePoint);[2] When the player moves. Summary (this is inside the mouseClicked listener):
    //mouseLocation = MouseWEvent.getPoint();
    //stl, str, etc = rectangles that represents future location of the player on the board.
              if (waitingForPlayer) {
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
    SO ... WHAT IS THE QUESTION?!?
    What I see when I run the game:
    the animation of the enemy (first code) works, but the animation of the player (second code, inside the mouse listeners) -- doesn't!
    The purpose of the moveActor is to move the enemy or player pixel by pixel, until its in the future point,
    instead of skipping the pixels between the squares and going straight for the future location.
    So what comes out is, that the enemy is moving pixel by pixel, and the player simply jumps there!
    I doublechecked and if I use moveActor with the player OUTSIDE the mouse listener, it works (i think).
    Any ideas what is the source of this problem?
    Hope I made myself clear enough :D
    Thanks,
    Eshed.

    I don't know if thats what happens, nor how to fix the thread problems. The mosue actions are "threaded" by default, no? And the moving thing happens after the mouse was clicked, and if the enemy's moving the user can still move his mouse and get responses, like "enemy didn't move yet" and stuff.
    Here's the complete GamePanel.java:
    //drawings
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    //events
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    //tools
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.MediaTracker;
    import java.awt.Dimension;
    //panels, buttons, etc
    import javax.swing.JPanel;
    /** The Game Panel.
    *The panel's size is 500x500, and each square is squaresized 50.
    *This is where the game actually "exists". Here its being updated, drawn, etc.*/
    public class GamePanel extends JPanel implements Runnable
         private static final int PWIDTH = 500;                              //Width of the panel.
         private static final int PHEIGHT = 500;                              //Height of the panel.
         private static final int SQUARESIZE = 50;                         //Size of each square in the panel.
         private boolean working = false;                                   //Game keeps going until this is FALSE.
         private volatile Thread animator;                                   //The animation thread.
         private ImageIcon stand,fall;                                        //Images for the background - ground and water.
         private static ImageHandler ih;                                        //An image handler for image loading.
         private int numOfImages = 0;                                        //Number of total images (max image qunatity).
         private Actor[] actors;                                                  //The actors: [0] is the player, rest are enemies.
         private Point mouseLocation;                                        //Saves the current mouse location for checking where the mouse is
         protected Rectangle stl, str, sbl, sbr;                              //squares around the player, for mouse stuff.
         protected Rectangle v1, v2, v3, v4, v5;                              //squares around each villain, for mouse stuff.
         protected Rectangle wholeBoard = new Rectangle(0,0,PWIDTH,PHEIGHT);
         protected boolean waitingForPlayer = true;
         private int currentVillain = 1;
         private boolean inSight = false;
         // in methods other than the listeners.
         /** Waits for the Window (or whatever this panel loads in) to settle in before doing anything.*/
         public void addNotify()
              super.addNotify();                                                                           //When the super finishes...
              go();                                                                                                         //..go, go, go!
         /** Starts the game.*/
         private void go()
              if (animator==null || !working)     {                                        //if the game isn't in process,
                   animator = new Thread(this);                                        //make the animator as the main process,
                   animator.start();                                                                      //and start it (because of the runnable it launches "run()".
         /**Constructor of the Game Panel.*/
         public GamePanel()
              numOfImages = 14;                                                                      //Total image num.
              ih = new ImageHandler(this,numOfImages);               //Setting a new image handler for the images.
              ih.addImage("player_idle", "images/p_idle.png");          //Adding images.
              ih.addImage("villain_idle", "images/v_idle.png");
              ih.addImage("stand", "images/stand.gif");
              ih.addImage("fallpng", "images/fall.png");
              ih.addImage("fall", "images/fall.gif");
              ih.addImage("ghost", "images/ghost.gif");
              ih.addImage("villain_angry", "images/v_angry.png");
              ih.addImage("player_angry", "images/p_angry.png");
              ih.addImage("player_jump1", "images/p_j1.gif");
              ih.addImage("player_jump2", "images/p_j2.gif");
              ih.addImage("player_jump3", "images/p_j3.gif");
              ih.addImage("villain_jump1", "images/v_j1.gif");
              ih.addImage("villain_jump2", "images/v_j2.gif");
              ih.addImage("villain_jump3", "images/v_j3.gif");
              setPreferredSize(new Dimension(PWIDTH,PHEIGHT));     //Setting size of the panel.
              setFocusable(true);                                                                                //This and the next makes the window "active" and focused.
              requestFocus();
              /** Mouse hovering settings.*/
              addMouseMotionListener( new MouseMotionAdapter()
                   /** When the mouse is moving, do these stuff.*/
                   public void mouseMoved(MouseEvent e1)
                         *  |  stl  |       | str   |          stl = squareTopLeft
                         *  |_______|_______|_______|       str = squareTopRight
                        *   |       |current|       |         current = player's location
                        *   |_______|_______|_______|       sbl = squareBottomLeft
                        *   |  sbl  |       |  sbr  |       sbr = squareBottomRight
                        *   |_______|_______|_______|
                        mouseLocation = e1.getPoint();
                        Dimension defaultSquareDimension = new Dimension(50,50);
                        //current-player-location points
                        Point topLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY());
                        Point topRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY());
                        Point bottomLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY()+50);
                        Point bottomRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY()+50);
                        //four-squares-around-the-player points
                        //T = top, B = bottom, R = right, L = left
                        Point ptl = new Point((int)topLeft.getX()-50,(int)topLeft.getY()-50);
                        Point ptr = new Point((int)topRight.getX(),(int)topRight.getY()-50);
                        Point pbl = new Point((int)bottomLeft.getX()-50,(int)bottomLeft.getY());
                        Point pbr = new Point((int)bottomRight.getX(),(int)bottomRight.getY());
                        //ghosts
                        stl = new Rectangle (ptl, defaultSquareDimension);
                        str = new Rectangle (ptr, defaultSquareDimension);
                        sbl = new Rectangle (pbl, defaultSquareDimension);
                        sbr = new Rectangle (pbr, defaultSquareDimension);
                        Rectangle player = new Rectangle(topLeft, defaultSquareDimension);     //rectangle of player
                        if (stl.contains(mouseLocation) && !hoveringVillain(stl))
                             actors[8] = new Actor("ghost", ptl);
                             else actors[8] = null;
                        if (str.contains(mouseLocation) && !hoveringVillain(str))
                             actors[9] = new Actor("ghost", ptr);
                             else actors[9] = null;
                        if (sbl.contains(mouseLocation) && !hoveringVillain(sbl))
                             actors[10] = new Actor("ghost", pbl);
                             else actors[10] = null;
                        if (sbr.contains(mouseLocation) && !hoveringVillain(sbr))
                             actors[11] = new Actor("ghost", pbr);
                             else actors[11] = null;
                   private boolean hoveringVillain(Rectangle r)
                        boolean onVillain = false;
                        for (int i=1; i<=5 && !onVillain; i++) onVillain = actors.getRect().equals(r);
                        return onVillain;
              /** Mouse-click settings.
              Note: only usable after moving the mouse. /
              addMouseListener (new MouseAdapter()
                   /** When the mouse button is clicked */
                   public void mouseClicked (MouseEvent me)
                        mouseClickedAction(me);
         private boolean hoveringVillain(Rectangle r)
              boolean onVillain = false;
              for (int i=1; i<=5 && !onVillain; i++) onVillain = actors[i].getRect().equals(r);
              return onVillain;
         public void mouseClickedAction(MouseEvent me)
              System.out.println("Point: "+me.getX()+","+me.getY());
              if (waitingForPlayer) {
                   //causes error if the mouse wasn't moved uptil now. try it.
                   mouseLocation = me.getPoint();
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
              } else MiscTools.shout("Wait for the computer to take action!");
              if (actors[0].getPoint().getY() == 0){
                   for (int i=1; i<=5; i++){
                             actors[i].setStatus("angry");
                   //repaint();
                   MiscTools.shout("Game Over! You Won!");
         /** First thing the Game Panel does.
         Initiating the variables, and then looping: updating, painting and sleeping./
         public void run() {
    Thread thisThread = Thread.currentThread();                                                  //Enables the restart action (two threads needed).
    init();                                                                                                                                            //Initialize the variables.
    while (animator == thisThread && working){                                                  //While the current thead is the game's and it's "on",
                   think();                                                                                                                             //Update the variables,
                   repaint();                                                                                                                             //Paint the stuff on the panel,
                   try {Thread.sleep(5);} catch (InterruptedException ex) {}                    //And take a wee nap.
         /** Initializing the variables.*/
         private void init()
              currentVillain = 1;
              working = true;                                                                                //Make the game ready for running.
              inSight = false;
              actors = new Actor[12];                                                                      //Six actors: player and 5*villains.
              actors[0] = new Actor("player", 200, 450);                                             //The first actor is the player.
              int yPoint = 50;                                                                           //The Y location of the villains (first row).
              /* ACTORS ON TOP, RIGHT, LEFT
              actors[1] = new Actor ("villain", 0, 350);
              actors[2] = new Actor ("villain", 0, 150);
              actors[3] = new Actor ("villain", 50, 0);
              actors[4] = new Actor ("villain", 250, 0);
              actors[5] = new Actor ("villain", 450, 0);
              actors[6] = new Actor ("villain", 450, 200);
              actors[7] = new Actor ("villain", 450, 400);
              /* ACTORS ON TOP*/
              for (int i=1; i<actors.length-4; i++){                                                  //As long as it doesnt go above the array...
                   actors[i] = new Actor ("villain", yPoint, 0);                                   //init the villains
                   actors[i].setStatus("idle");
                   yPoint+=100;                                                                           //and advance in the Y axis.
         /** Updating variables.*/
         private void think()
              if (!waitingForPlayer){
                   //initialize
                   int playerX = (int)actors[0].getPoint().getX();
                   int playerY = (int)actors[0].getPoint().getY();
                   boolean moved = false;
                   wholeBoard = new Rectangle(0,0,500,500);     //needed to check whether an actor is inside the board
                   //for (int in = 0; in<=5; in++) actors[in].setStatus("idle"); //"formatting" the actor's mood
                   if (playerY <= 1000) inSight = true;     //first eye contact between the player and villains.
                   int closestVillainLevel = 0;
                   int[] vills = closestVillain();
                   int moveCounter = 0;
                   if (inSight) {
                        while (!moved){               //while none of the villains made a move
                        moveCounter++;
                        if (moveCounter == 5) moved = true;
                        else{
                             currentVillain = vills[closestVillainLevel];
                             int villainX = (int)actors[currentVillain].getPoint().getX();
                             int villainY = (int)actors[currentVillain].getPoint().getY();
                             //clearing stuff up before calculating things
                             boolean playerIsBelowVillain = playerY > villainY;
                             boolean playerIsAboveVillain = playerY < villainY;
                             boolean playerIsOnSameRowAsVillain = playerY == villainY;
                             boolean playerIsToVillainsRight = playerX > villainX;
                             boolean playerIsToVillainsLeft = playerX < villainX;
                             boolean playerIsOnSameColumnAsVillain = playerX == villainX;
                             //System.out.println("\n-- villain number "+currentVillain+" --\n");
                             int xToAdd = 0, yToAdd = 0;
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             if (legalPoint(futurePoint)){
                                  moveActor(actors[currentVillain], futurePoint);
                                  moved = true;
                                  //System.out.println("\nVillain "+currentVillain+" is now at "+actors[currentVillain].getPoint());
                             else closestVillainLevel=circleFive(closestVillainLevel);
                        } //end of else
                        } //end of while
                        //currentVillain = circleFive(currentVillain); //obsolete
                   } //end of ifInSight
                   waitingForPlayer = true;
         private boolean legalPoint(Point fp)
              return (wholeBoard.contains(fp) && !onPeople(fp) && legalSquare(fp));
         private boolean legalSquare(Point p)
              if ( (p.getX()==0 || p.getX()%100==0) && (p.getY()/50)%2!=0 ) return true;
              if ( (p.getX()/50)%2!=0 && (p.getY()==0 || p.getY()%100==0) ) return true;
              return false;
         //return the closest villain to the player, by its level of distance.
         public int[] closestVillain()
              //System.out.println("Trying to find the closest villain...");
              double[] gaps = new double[5];     //the distances array
              //System.out.println("The villains' distances are: ");
              for (int i=0; i<5; i++){
                   gaps[i] = distanceFromPlayer(actors[i+1].getPoint());     //filling the distances array
                   //System.out.print(gaps[i]+", ");
              int[] toReturn = new int[5];
              double smallestGapFound;
              double[] arrangedGaps = smallToLarge(gaps);
              for (int level=0; level<5; level++){
                   smallestGapFound = arrangedGaps[level];
                   for (int i=1; i<=5; i++){
                        if (smallestGapFound == distanceFromPlayer(actors[i].getPoint())){
                             toReturn[level] = i;
              return toReturn;
         private double[] smallToLarge(double[] nums)
              //System.out.println("\nArranging array... \n");
              double[] newArray = new double[5];
              int neweye = 0;
              double theSmallestOfTheArray;
              for (int i=0; i<nums.length; i++){
                   theSmallestOfTheArray = smallest(nums);
                   //System.out.println("\t\t>> Checking whether location "+i+" ("+nums[i]+") is equal to "+theSmallestOfTheArray);
                   if (nums[i] == theSmallestOfTheArray && nums[i]!=0.0){
                        //System.out.println("\t\t>> Adding "+nums[i]+" to the array...");
                        newArray[neweye] = nums[i];
                        //System.out.println("\t\t>> Erasing "+nums[i]+" from old array...\n");
                        nums[i] = 0.0;
                        neweye++;
                        i=-1;
              /*System.out.print("\nDONE: ");
              for (int i=0; i<newArray.length; i++)
                   System.out.print("["+newArray[i]+"] ");
              System.out.println();*/
              return newArray;
         private double smallest (double[] nums)
                   //System.out.print("\tThe smallest double: ");
                   double small = 0.0;
                   int j=0;
                   while (j<nums.length){               //checking for a starting "small" that is not a "0.0"
                        if (nums[j]!=0.0){
                             small = nums[j];
                             j = nums.length;
                        } else j++;
                   for (int i=1; i<nums.length; i++){
                        if (small>nums[i] && nums[i]!=0.0){
                             small = nums[i];
                   //System.out.println(small+".");
                   return small;
         private double distanceFromPlayer(Point vp)
              Point pp = actors[0].getPoint(); //pp=plaer's point, vp=villain's point
              double x = Math.abs(vp.getX() - pp.getX());
              double y = Math.abs(vp.getY() - pp.getY());
              return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
         private int circleFive(int num)
                   if (num>=5) return 0;
                   else return num+1;
         private boolean onPeople(Point p)
              for (int jj=0; jj<=5; jj++)
                   if (jj!=currentVillain && p.equals(actors[jj].getPoint()))
                        return true;
              return false;
         /** Painting the game onto the Game Panel.*/
         public void paintComponent(Graphics g)
              Graphics2D graphics = (Graphics2D)g;                                                            //Reset the graphics to have more features.
              //draw bg
              graphics.setColor(Color.white);                                                                                //"format" the panel.
              graphics.fillRect(0,0,500,500);
         char squareType = 'f';                                                                                                    //First square's type (stand or fall).
         for (int height=0; height<PHEIGHT; height=height+SQUARESIZE){     //Painting the matrix bg.
                   for (int width=0; width<PWIDTH; width=width+SQUARESIZE){
                        if (squareType=='f') {                                                                                               //If a "fall" is to be drawn,
                             ih.paint(graphics, "fallpng", new Dimension(width,height));          //Draw a non-animated image to bypass white stuff.
                             ih.paint(graphics, "fall", new Dimension(width,height));               //Draw the water animation.
                             squareType = 's';                                                                                                    //Make the next square a "stand".
                        } else if (squareType=='s'){                                                                                //If a "stand" is to be drawn,
                             ih.paint(graphics, "stand", new Dimension(width,height));          //Draw the ground image,
                             squareType = 'f';                                                                                                    //and make the next square a "fall".
                   if (squareType=='f') squareType = 's';                                                                 //After finishing a row, switch again so
                   else squareType = 'f';                                                                                                    // the next line will start with the same type (checkers).
              for (int i=actors.length-1; i>=0; i--){                                                                           //Draw the actors on the board.
                   if (actors[i]!=null)
                        ih.paint(graphics, actors[i].currentImage(), actors[i].getPoint());
         /** Restart the game.
         Or, in other words, stop, initialize and start (again) the animator thread and variables./
         public void restart()
              System.out.println("\n\n\nRESTARTING GAME\n\n\n");
              animator = null;                                                                                                                   //Emptying the thread.
              init();                                                                                                                                                 //Initializing.
              animator = new Thread(this);                                                                                     //Re-filling the thread with this panel's process.
              animator.start();                                                                                                                   //launch "run()".
         protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");

  • How do I add multiple JPanels to a JFrame?

    I've been trying to do my own little side project to just make something for me and my friends. However, I can't get multiple JPanels to display in one JFrame. If I add more than one JPanel, nothing shows up in the frame. I've tried with SpringLayout, FlowLayout, GridBagLayout, and whatever the default layout for JFrames is. Here is the code that's important:
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.*;
    public class CharSheetMain {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              CharSheetFrame frame=new CharSheetFrame();
              abilityPanel aPanel=new abilityPanel();
              descripPanel dPanel=new descripPanel();
              frame.setLayout(new FlowLayout());
              abilityScore st=new abilityScore();
              abilityScore de=new abilityScore();
              abilityScore co=new abilityScore();
              abilityScore in=new abilityScore();
              abilityScore wi=new abilityScore();
              abilityScore ch=new abilityScore();
              frame.add(aPanel);
              frame.add(dPanel);
              frame.validate();
              frame.repaint();
              frame.pack();
              frame.setVisible(true);
    }aPanel and dPanel both extend JPanel. frame extends JFrame. I can get either aPanel or dPanel to show up, but not both at the same time. Can someone tell me what I'm doing wrong?

    In the future, Swing related questions should be posted in the Swing forum.
    You need to read up on [How to Use Layout Managers|http://download.oracle.com/javase/tutorial/uiswing/layout/index.html]. The tutorial has working example of how to use each layout manager.
    By default the content pane of the frame uses a BorderLayout.
    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.
    The code you posted in NOT a SSCCE, since we don't have access to any of your custom classes. To do simple tests of adding a panel to frame then just create a panel, give it a preferred size and give each panel a different background color so you can see how it works with your choosen layout manager.

  • Setting a jpanel as a background image

    i have managed to load the image into a jpanel but now need to know how to set the jpanel as a background image, to allow my jbuttons and textfields to be seen over the top

    that statement is unbeleivably true.
    right, heres my two classes, the first class is where i created the image
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.* ;
    import java.io.*;
    import javax.imageio.*;
    public class EmailBackgroundImage extends JComponent
    public void paint (Graphics g)
    File bkgdimage = new File ("background.jpg");
    Image imagebg = createImage ( 250,300 );
    try {
    imagebg = ImageIO.read(bkgdimage);
    catch (IOException e)
    g.drawImage(imagebg, 0, 0,null,null);
    this next class is where i'm trying to make the background
    youll notice remnants of my current attempt to create the background image.
    in its current state it does compile
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.* ;
    import java.sql.*;
    import java.util.*;
    import java.awt.color.*;
    public class emailFrontpage extends JFrame implements ActionListener
    JLabel FirstNameLabel = new JLabel("First Name");
    JLabel LastNameLabel = new JLabel("Last Name");
    JLabel EmailLabel = new JLabel("Email Address");
    JTextField FirstNameText = new JTextField( 10 );
    JTextField LastNameText = new JTextField( 10 );
    JTextField EmailAddressText = new JTextField( 20 );
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();
    JPanel panel4 = new JPanel();
    JPanel panel5 = new JPanel();
    JPanel image = new JPanel();
    JButton Enterbutton = new JButton("Enter Details");
    JButton Logon = new JButton("Log on");
    EmailBackgroundImage myimage;
    EmailEdit editEmp;
    emailFrontpage()
    getContentPane().setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ));
    myimage = new EmailBackgroundImage();
    image.add(myimage);
    myimage.setSize(250,300);
    image.setOpaque( false );
    FirstNameLabel.setForeground(Color.WHITE);
    LastNameLabel.setForeground(Color.WHITE);
    EmailLabel.setForeground(Color.WHITE);
    panel1.add(Logon);
    panel2.add(FirstNameLabel); panel2.add(FirstNameText);
    panel3.add(LastNameLabel); panel3.add(LastNameText);
    panel4.add(EmailLabel); panel4.add(EmailAddressText);
    panel5.add(Enterbutton);
    getContentPane().add(image);
    getContentPane().add(panel1);
    getContentPane().add(panel2);
    getContentPane().add(panel3);
    getContentPane().add(panel4);
    getContentPane().add(panel5);
    // .setBackground( Color.black )
    Enterbutton.addActionListener( this );
    Logon.addActionListener( this );
    Enterbutton.setActionCommand( "ENTERBUTTONPRESSED" );
    Logon.setActionCommand( "LOGONBUTTONPRESSED" );
    setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
    editEmp = new EmailEdit();
    public void actionPerformed( ActionEvent evt)
    if ( evt.getActionCommand().equals("LOGONBUTTONPRESSED") )
    emailLogonpage emaillogon = new emailLogonpage();
    emaillogon.setSize( 250, 300 );
    emaillogon.setVisible( true );
    emaillogon.setResizable(false);
    setVisible(false);
    else
    String newFN = FirstNameText.getText();
    String newLN = LastNameText.getText();
    String newEA = EmailAddressText.getText();
    editEmp.addNewEmail(newFN, newLN, newEA);
    setVisible(false);
    emailFrontpage emailfront = new emailFrontpage();
    emailfront.setSize( 250, 300 );
    emailfront.setVisible( true );
    emailfront.setResizable(false);
    public static void main ( String[] args )
    emailFrontpage emailfront = new emailFrontpage();
    emailfront.setSize( 250, 300 );
    emailfront.setVisible( true );
    emailfront.setResizable(false);
    }

  • Setting a JPanel alignment

    hi all,
    I'm using a BorderLayout for my simply application.
    I have created a JPanel that contains two buttons, as follows:
    JPanel pannello_pulsanti=new JPanel();
    pannello_pulsanti.setLayout(new BoxLayout(pannello_pulsanti, BoxLayout.LINE_AXIS));
    salva.setPreferredSize(new Dimension(100, 20));
    salva.setMaximumSize(new Dimension(100, 20));
    reset.setPreferredSize(new Dimension(100, 20));
    reset.setMaximumSize(new Dimension(100, 20));
    pannello_pulsanti.add(salva);
    pannello_pulsanti.add(Box.createRigidArea(new Dimension(0, 5)));
    pannello_pulsanti.add(reset);I had in mind to put the JPanel inside the "PAGE_END" location, and I did it.
    the problem is that the panel has a left alignment, while I want a center alignment for it (I tried to change its alignment with setAlignmentX method, but it doesn't work).
    can anyone help me in solving this problem?
    thanks,
    varying

    import java.awt.*;
    import javax.swing.*;
    public class CenteringComponents
        public static void main(String[] args)
            JButton button1 = new JButton("Button 1");
            JButton button2 = new JButton("Button 2");
            Box centerBox = Box.createHorizontalBox();
            centerBox.add(Box.createHorizontalGlue());
            centerBox.add(button1);
            centerBox.add(Box.createHorizontalGlue());
            centerBox.add(button2);
            centerBox.add(Box.createHorizontalGlue());
            JButton button3 = new JButton("Button 3");
            JButton button4 = new JButton("Button 4");
            Box southBox = Box.createHorizontalBox();
            southBox.add(Box.createHorizontalGlue());
            southBox.add(button3);
            southBox.add(Box.createHorizontalGlue());
            southBox.add(button4);
            southBox.add(Box.createHorizontalGlue());
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(centerBox);
            f.getContentPane().add(southBox, BorderLayout.PAGE_END);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • JPanel hiden behind JFrame decoration

    Hi, I have a JFrame and a JPanel.
    The JPanel is going to be double buffered with my own code(active rendering) and will consume the whole JFrame. I want to add other panels later on top of the JPanel. and a pop up menu aswell. So I create a buffer graphic, paint on it and show it on the JPanel.
    When I set the JPanel as contentPane or add it in the center then a part of the Panel is hiden by the frame decorations. How can I force the Jpanel to display totaly, without a part being hiden.
    I know one solution: create a top cst make it 30 pixels and everytime i paint add it to the y var. But then again... that isn't a 'real' solution.
    I would like to be 0,0 the left top of my Jpanel and not 0,0 hiden behind the decoration...
    So when I typ contentPane.setLayout(new FlowLayout(FlowLayout.CENTER)); then I would like to see the button i would add.
        pauseButton = new JButton("pause");
        pauseButton.setIgnoreRepaint(true);
        // Create the space where the play/pause buttons go.
        playButtonSpace = new JPanel(new BorderLayout());
        playButtonSpace.setOpaque(false);
        playButtonSpace.add(pauseButton);
        contentPane.add(playButtonSpace);Now I can see a small part of the button the rest is hiden behind the frame decoration.
    public test() {
        gamePanel = new JPanel();
        gamePanel.setPreferredSize(new Dimension(500, 600));
        gamePanel.setMinimumSize(new Dimension(500, 600));
        gamePanel.setMaximumSize(new Dimension(500, 600));
        JFrame frame = new JFrame("Hello world!");
        frame.setContentPane(gamePanel);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
        Graphics g = frame.getGraphics();          // quick test
        g.drawString("can you see me1?", 0, 0);
        g.drawString("can you see me2?", 0, 20);
        g.drawString("can you see me3?", 0, 50);
      public static void main(String[] args) {
        new test();
    }can you see me3 is visible the rest is not.
    I use:
    frame.getLayeredPane().paintComponents(g);to do my custom painting.
    How do i show the panel completely?

    Usually we draw overriding the method "paintComponent":
    * Test.java
    import java.awt.*;
    import javax.swing.*;
    class Test {
        public Test() {
            JPanel gamePanel = new JPanel() {
                protected void paintComponent(final Graphics g) {
                    super.paintComponent(g);
                    int h = g.getFontMetrics().getHeight();
                    for (int row = 1; row < 10; row++) {
                        g.drawString("can you see me" + row + "?", 0, row * h);
            JFrame frame = new JFrame();
            frame.setSize(400, 300);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(gamePanel, BorderLayout.CENTER);
            frame.setVisible(true);
        public static void main(final String[] args) {
            new Test();
    }

Maybe you are looking for

  • Using LCD TV as Display

    I have a 12-inch iBook G4, and I wanted to use my LCD screen as my display. I bought a Apple Mini-DVI to Video Adapter, when I connected it up the picture looked grainy. It looks like it wasn't scaled up just blown up (if you understand that). I can

  • Image quality seems poor when exporting to ePub (even on max)

    Hello all,   I've been using InDesign to prep a book for export to ePub format, and it will include several images. Things are going fairly well now that I finally think I've got my mind around the way InDesign works and how to think/prep in advance

  • RFC call in background error

    We are having a unique problem in upgrade BW system. We have several RFC function calls in start routine and abap programs to R/3 and APO systems. After the upgrade these calls are not working in background. When we run the program online/dialog the

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.

  • Photoshop online help does not display

    Hello, I am having exactly the same problem reported last year by Alex with online help. It has not been answered so far. I'm using Photoshop CC 2014 French version under W7 64bits.  I have tried with different browsers (IE, FF and Chrome). I get err