Reputation: 330
package database;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.SwingUtilities;
public class Application {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ApplicationFrame("Application");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public class ApplicationFrame extends JFrame {
private CompaniesPanel companiesPanel;
public ApplicationFrame(String title) {
super(title);
setLayout(new BorderLayout());
JMenuBar menuBar = new MenuBar("Menu");
Container container = getContentPane();
container.add(menuBar, BorderLayout.NORTH);
}
}
public class MenuBar extends JMenuBar {
public MenuBar(String title) {
super();
JMenu menuFile = new JMenu("File");
add(menuFile);
JMenu menuOpen = new JMenu("Open");
menuFile.add(menuOpen);
JMenuItem menuItemCompanies = new JMenuItem("Companies");
menuOpen.add(menuItemCompanies);
menuItemCompanies.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// In here I would like to take a CompaniesPanel and insert
// it into
// an ApplicationFrame if the Companies button is pressed on
// menu
}
});
}
}
public class CompaniesPanel extends JPanel {
public CompaniesPanel() {
Dimension size = getPreferredSize();
size.width = 250;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Company Names"));
setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints = new GridBagConstraints();
}
}
}
I just want my application to open up that menu with the rest being blank, and open up the CompaniesPanel when Companies is pressed from the drop down menu. Is this possible without opening up another jFrame?
Upvotes: 0
Views: 83
Reputation: 324108
container.add(menuBar, BorderLayout.NORTH);
Frist of all that is not how you add a menu to the frame. A frame has a special area reserved for the menu bar.
Instead you just use:
setJMenuBar( menuBar );
Read the section from the Swing tutorial on How to Use Menus for more information and working examples.
As already mentioned a CardLayout
would be a good choice. By adding two panels (one empty, and one for the companines) the preferred size of the layout will be determined by your companies panel so the frame size does not change when you display the companies panel.
The Swing tutorial also has a section on How so Use CardLayout with working examples to get your started.
Keep a reference to the Swing tutorial handy for all the Swing basics.
Upvotes: 1