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

Similar Messages

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

  • How do I replace one JPanel on a JFrame with another?

    I want to replace one JPanel on a JFrame with a different JPanel when the user clicks on a certain menu item. The menu item is working corrrectly but I cant seem to repaint / refresh the component.
    My code is as follows:
    c.add(knotPanel, BorderLayout.CENTER);
    c.add(stepPanel, BorderLayout.NORTH);
         if (stepChoice != 9) {
         c.remove(ownPanel);
         c.add(lessonPanel, BorderLayout.EAST);
         else {
         c.remove(lessonPanel);
         c.add(ownPanel, BorderLayout.EAST);
         c.invalidate();
         c.validate();
         c.update(c.getGraphics());
    Any ideas?

    I think you should use CardLayout manager.
    With CardLayout you can switch beetwen JPanels without removing or adding.

  • Having trouble displaying a JPanel on a JFrame

    Hello all,
    I'm fairly new to Java and I am having trouble displaying a JPanel on a JFrame. Pretty much I have a class called Task which has a JPanel object. Everytime the user creates a new task, a JPanel with the required information is created on screen. However, I cannot get the JPanel to display.
    Here is some of the code I have written. If you guys need to see more code to help don't hesitate to ask.
    The user enters the information on the form and clicks the createTask button. If the information entered is valid, a new task is created and the initializeTask method is called.
    private void createTaskButtonMouseClicked(java.awt.event.MouseEvent evt) {                                             
        if (validateNewTaskEntry())
         String name = nameTextField.getText().trim();
         Date dueDate = dueDateChooser.getDate();
         byte hourDue = Byte.parseByte(hourFormattedTextField.getText());
         byte minuteDue = Byte.parseByte(minuteFormattedTextField.getText());
         String amOrPm = amPmComboBox.getSelectedItem().toString();
         String group = groupComboBox.getSelectedItem().toString();
         numberTasks++;
    //     if (numberTasks == 1)
    //     else
         Task newTask = new Task(mainForm, name, dueDate, hourDue, minuteDue,
             amOrPm, group);
         newTask.initializeTask();
         this.setVisible(false);
    }This is the code that I thought would display the JPanel. If I put this code in anther form's load event it will show the panel with the red border.
    public void initializeTask()
         taskPanel = new JPanel();
         taskPanel.setVisible(true);
         taskPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
         taskPanel.setBounds(0,0,50,50);
         taskPanel.setLayout(new BorderLayout());
         mainForm.setLayout(new BorderLayout());
         mainForm.getContentPane().add(taskPanel);
    }I was also wondering if this code had anything to do with it:
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new AddTaskForm(new MainForm()).setVisible(true);
        }As you can see I create a new MainForm. The MainForm is where the task is supposed to be drawn. This code is from the AddTaskForm (where they enter all the information to create a new task). I had to do this because AddTaskForm needs to use variables and methods from the MainForm class. I tried passing the mainForm I already created, but I get this error: non-static variable mainForm cannot be referenced from a static context. So to allow the program to compile I passed in new MainForm() instead. However, in my AddTaskForm class constructor, I pass the original MainForm. Here is the code:
    public AddTaskForm(MainForm mainForm)
       initComponents();
       numberTasks = 0;
       this.mainForm = mainForm;
    }Is a new mainForm actually being created and thats why I can't see the JPanel on the original mainForm? If this is the case, how would I pass the mainForm to addTaskForm? Thanks a ton for any help/suggestions!
    Brian

    UPDATE
    While writing the post an idea popped in my head. I decided to not require a MainForm in the AddTaskForm. Instead to get the MainForm I created an initializeMainForm method.
    This is what I mean by not having to pass new MainForm():
        public static void main(String args[])
         java.awt.EventQueue.invokeLater(new Runnable()
             public void run()
              new MainForm().setVisible(true);
        }Even when I don't create the new MainForm() the JPanel still doesn't show up.
    Again, thanks for any help.
    Brian

  • How to have focus in 2 JPanels on 1 JFrame?

    Hey all..
    Like i wrote in the subject, how can i do that?
    I have 2 JPanels in 1 JFrame. 1 top JPanel and 1 buttom JPanel. I've a keylistener in top JPanel and a buttonslistener in buttom JPanel. When i press on the button on the buttom JPanel, then my keylistener wont trigger in the top JPanel.
    Plz help.
    Thx.

    The whole point to window focus is to avoid this! There is at most one focused component per window.
    As a rule of thumb, when someone uses a KeyListener, they're mistaken. You should be using key binding. This can make your focus problems go away, since you can choose to associate the keyStoke with the whole window, not just the focused component.
    [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]

  • Placing a new Jpanel on a JFrame without moving the existing components.

    I am creating an application in which data is entered over several screens a next button is used to get to the next screen similar to how a wizard functions. To do this I use a JFrame with several panels on top of it each panel on top of the jframe rather than on top of each other. Each panel contains buttons and radio buttons.
    The problem I have is that every time I drag a new Jpanel on to the JFrame it pushes all my carefully arranged controls on the existing panel to the side. The problem seems to be partly because when a new panel is dragged on to the screen it is placed as a component on the already existing panel rather than on the JFrame.
    Is there a way to freeze the components on the panel so they wont more or to place a panel directly onto the jframe rather than onto the previous jpanel to avoid disrupting the previous frame.
    I have played around with the properties but have not had any luck.
    Thanks for any help.

    I am creating an application in which data is entered over several screens a next button is used to get to the next screen similar to how a wizard functionsThe [Card Layout Actions|http://www.camick.com/java/blog.html?name=card-layout-actions] may help in this process.

  • One JPanel is missing after adding two JPanels to a JFrame

    I have two classes, ScoreTableView and CardView, which both extends the JPanel class. ScoreTableView is used to show one table only, and CardView is to show a set of cards for a memory game. My objective is to separate the development of the panels, so that it will easier to modify either of them later. I add instances of these two class to the contentPane of my top level JFrame object. However, I can only see the ScoreTableView(which is supposed to show me a table only) on the top part of the frame, and the CardView panel never show up.
    ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
            scoreTable = new JTable();//this scoreTable is a JTable object
            scoreTable.setModel(scoreTableData);  //scoreTableData is my data    
            JScrollPane jsp = new JScrollPane(scoreTable);          
            p = this;
            p.setLayout(new BorderLayout());
            p.add(jsp, BorderLayout.CENTER);
        }CardView.java
    public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            JPanel cardPanel = new JPanel();
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
          // ... more other none GUI coiding 
             }Here's what I have in my main
            Container contentPane = jf.getContentPane();//jf is the JFrame object          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);      

    Sorry, but I copied the wrong files. Now both panels can show up, but the score table is on the NORTH, and the card panel is on the SOUTH(although I set it to CENTER and wish it can occupy the rest of the window), but the center part of the window has nothing. How can I get rid of the white space, so that the score panel can can 30% of the top part of the window(even after resize), and the card panel can occupy the remaining 70%? I can't attach pictures here, otherwise I can upload some screenshot to show you what's the problem I have. Thank you in advance.
    This is my CardView class, I didnt' copy all of them upstair.
    public class CardView extends JPanel{
        private int cardWidth;
        private int cardHeight;
        private CardModel cm;
        private JPanel cardPanel;
        public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            cardPanel = this;
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
            int[][] list  = init(cardWidth, cardHeight);       
            cm = new CardModel(list);
            int count = 0;
            for(int i=0;i<cardWidth;i++){
                for(int j=0;j<cardWidth;j++){
                    cardsButtons[i][j] = new CardImageButton("Press me"+count, cm, i, j, 0);
                    cardPanel.add(cardsButtons[i][j]);
                    count++;               
    public int[][] init(int n, int m){
            int[][] list  = {
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2},
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2} };
            return list;
        }This is from my main.
           //setup the content panel
            Container contentPane = jf.getContentPane();          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);   ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
    scoreTable = new JTable();//this scoreTable is a JTable object       
    scoreTable.setModel(scoreTableData);  //scoreTableData is my data            
    JScrollPane jsp = new JScrollPane(scoreTable);                  
    p = this;       
    p.setLayout(new BorderLayout());       
    p.add(jsp, BorderLayout.CENTER);   
    }

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

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

  • Putting a jpanel into a jframe

    I have a main JFrame which was created by:
    public class ControllerGUI extends javax.swing.JFrameand inside this somewhere is a JPanel called myPanel.
    I have a seperate class which is a JPanel created by:
    public class Calc extends javax.swing.JPanelI am quite new to swing and have been using the GUI builder in Netbeans, so could someone please tell me how to put the seperate Calc JPanel into the JPanel myPanel which is in the JFrame. Is it something to do with creating a container for it? Thanks.
    Thanks.

    Not sure if you're still around, but here's a very simple example of putting a JPanel derived object into another JPanel. The Calc class here extends JPanel. It does nothing but shows a 3 by 3 grid of JLabels:
    import java.awt.Color;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    class Calc extends JPanel
        public Calc()
            setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
            // what the heck, have it show a 3x3 label grid
            setLayout(new GridLayout(0, 3, 10, 10)); // sets layout for the grid
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    String labelString = "[" + (i + 1) + ", " + (j + 1) + "]";
                    JLabel label = new JLabel(labelString);
                    label.setBorder(BorderFactory.createLineBorder(Color.blue));
                    label.setHorizontalAlignment(SwingConstants.CENTER);
                    add(label); // adds each label to the grid
    }Now I'll add it to myPanel which is a JPanel object, but before adding it, I'll set the myPanel's layout to be BorderLayout, and I'll add the Calc class to the CENTER position:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class FooFrame extends JFrame
        // declare and initialize the myPanel JPanel object and
        // the myCalc Calc object:
        private JPanel myPanel = new JPanel();
        private Calc myCalc = new Calc();
        public FooFrame(String s)
            super(s);
            getContentPane().add(myPanel); // add myPanel to the contentPane making it the main panel
            setPreferredSize(new Dimension(500, 400));
            myPanel.setLayout(new BorderLayout());  // here set the layout of mypanel
            myPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            // create a title panel and add it to the top of myPanel
            JLabel title = new JLabel("Application Title");
            JPanel titlePanel = new JPanel(new FlowLayout()); // redundant since jpanels
                                                            //use flowlayout by default
            titlePanel.add(title);
            myPanel.add(titlePanel, BorderLayout.PAGE_START); // adds title to top of myPanel
            // create a button panel and add it to the bottom of myPanel
            // here we'll use gridlayout
            JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 15, 0));
            JButton okButton = new JButton("OK"); // create buttons
            JButton cancelButton = new JButton("Cancel");
            buttonPanel.add(okButton); // add buttons to button panel
            buttonPanel.add(cancelButton);
            myPanel.add(buttonPanel, BorderLayout.PAGE_END); // adds buttonpanel to bottom of myPanel
            //** add the myCalc object to the center of the myPanel via borderlayout
            myPanel.add(myCalc, BorderLayout.CENTER);
        // initialize and show the JFrame
        private static void createAndShowUI()
            JFrame frame = new FooFrame("FooFrame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // but be careful to show the JFrame in a thread-safe manner:
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Rendering a JPanel over a JFrame

    Hello everybody,
    This is my situation: I have a JFrame extension (created in NetBeans' GUI Editor) that contains some JTextField objects and a JList object. The frame initializes, and then a SwingWorker thread accesses a remote server and downloads information which is then sent to the JList object. The problem I have here is the loading. I'd like to render another JPanel, one that says "LOADING" in very large type, over the JFrame.
    I had originally thought the GlassPane may be useful for this, but upon further investigation it seems that I cannot use a JPanel as the GlassPane. I then attempted to use the LayeredPane by calling getLayeredPane(), and then adding my JPanel in there. I repositioned it, made sure that the LayeredPane had dimensions (they were 0,0 to start off with... I think that's odd considering the JFrame has size...), and made sure everything was visible. No good.
    Alas, I seek the infinite wisdom of the masses. Has anybody done something similar? How did you accomplish it?

    Alas, I seek the infinite wisdom of the masses. Has anybody done something similar? How did you accomplish it?Using CardLayout.
    You can show(...) the "Please wait" panel while loading, then back to show() the regular form panel when loading is done. That also prevents the user from clicking on the regular widgets while the loading proceeds (but that may not fot your requirements).

  • Switch Between Jpanels within a JFrame

    Hi, I am new to this java thing and I need a hand with the following problem
    I have 3 classes
    Invaders
    Game
    OptionsMenu
    Basically, you execute the program which executes Invaders, which then creates a JFrame with a border layout and adds the menu bar to the top, JPanel with either game or OptionsMenu to the center and a further JPanel to the bottom containing buttons and labels
    The specifics of the problem is I can not work out how to change between the panels in the center of the border layout in the frame created by invaders.
    When the program loads its ment to load with the options menu, which is no problem, the problem comes when I need to change the frame from the options menu to the game via a button on the options menu, the options menu passes the variables its gathered to the game constructor and it is then ment to display in the center of the border layout in the JFrame from invaders, any help would be appreciated, I have spent 2 days trying to get it to work and have not been sucessful

    I can not work out how to change between the panels in the center of
    the border layout in the frame created by invaders.Use a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout.

  • How do you switch between jpanels in a jframe?

    I have, what seems, a relatively simple question; however I cant find a solution to it anywhere!
    I have a jframe with a jmenubar which has 4 menu items. When each item is clicked a new JFrame is displayed with certain content. What I am trying to do, instead of creating a new Jframe each time a menu item is clicked, is display all jpanels within the current jframe. When different menu items in the jmenu are clicked it "switches" the main jpanel to display the required content.
    So basically I want 1 JFrame, which has 4 JPanels, (alhough only 1 is shown at any given time). When a menu item in the jmenubar is clicked the JPanel which corresponds to the menu item is displayed on the jframe.
    If your still confused, I basically want jtabbedpane functionality only I want to control the switching through tabs via the jmenubar (and I dont want the jtabbedpane tabs obviously).
    Thanks

    Myles wrote:
    Okay that seems obvious ;)
    What do you mean by "validating the content pane" though?
    Thanks for your quick reply.Containers have a method called validate() which will update them when components are added and removed. Without this, you won't see added components.
    And yes, you can have more than 1 container. JPanels are containers themselves and can have components added and removed from them as well. You only have one content pane in the JFrame, but you could add two JPanels to this, one static and one to act as your swapping container.

  • Add JPanel to a JFrame

    I have two classes. One is the main frame, and the other class is a panel. The constructor of the main frame looks like this:
              JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame frame = new JFrame("main");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel entryMgmt = new EntriesMgmt(dbConn);     
              frame.getContentPane().add(entryMgmt);
              frame.pack();
              frame.setVisible(true);The EntriesMgmt class extends JPanel. The constructor for it looks like this:
    public EntriesMgmt(SqlBackend.DbConn conn){
              this.conn = conn;
              JPanel pane = new JPanel();
              //Add radio buttons
              pane.add(initRadioBtns());
              //Add input area
              pane.add(initInputArea());
              //Add buttons
              pane.add(initButtons());
         }The problem is that only the main window appears and there is nothing in it. I tried creating another JFrame in the EntriesMgmt constructor but it would cause 2 windows to appear and i don't want to use internalFrame because what I'm actually trying to do is have a JTabbedPane in the main window and I would have external JPanel under each tab. But let's concentrate on why is it that my EntriesMgmt panel does not appera in the main window.

    What i did to fix this problem was the following. Since EntriesMgmt class extends JPanel I did not have to define another JPanel in the constructor but I could directly add components. Instead of :
    public EntriesMgmt(){
    JPanel pane = new JPanel();
              //Add radio buttons
              pane.add(initRadioBtns());
              //Add input area
              pane.add(initInputArea());
              //Add buttons
              pane.add(initButtons());I have:
    public EntriesMgmt(){
              //Add radio buttons
              add(initRadioBtns());
              //Add input area
              add(initInputArea());
              //Add buttons
              add(initButtons());And somehow it works. Anyways I would like to know if there was any other way to do it.

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

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

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

Maybe you are looking for

  • Firefox wont start, all soloutions given on website do not work

    I am using Windows XP and the most recent version of Firefox. I was browsing last night and had multiple pages open (the websites were bbc.co.uk, eurogamer.co.uk, ign.co.uk). I clicked on a link for an article and the page started behaving strangely,

  • How do i get my buy all button and see how much im spending on my itunes wish list

    how do i get my buy all button back and see how much im spending on my itunes wish list

  • Anyconnect Client & Clean Access SSO

    I have a ASA 5550 setup with the AnyConnect Essentials License and it works. Behind the VPN we have a CA server running 4.1.8 using SSO. The VPN aspect of this works but I've run into a issue with OSX and the CA Agent. Windows and the CA Agent SSO wo

  • Question on table partition

    Hi Again OTN Peeps, I have a question about copying from one table to another table. The table that i need to copy is partitioned. I'm checking the internet on how to copy data of the table per partition. But I'm not able to see a better explanation.

  • Auto pop-up for wispr in any captive portal won't work anymore

    Hi all, I really like the captive portal function. I am often at Starbucks, and I like the easy way to accept the user agreement. But, since some weeks, the auto pop-up to see the captive portal won't show ... neither Starbucks nor somewhere else! At