I have a problem with my application GUI. I would like to create one global JMenuBar and share it to other JPanels, but if i want to assign to multi JPanels i have error:
#
"The menuBar component is added to a parent component more than once.
•panelAll.add(menuBar);
•panelTask.add(menuBar);"
#
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
JPanel panelAll = new JPanel();
frame.getContentPane().add(panelAll, "name_218556506364138");
panelAll.setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 795, 21);
panelAll.add(menuBar);
JPanel panelTask = new JPanel();
frame.getContentPane().add(panelTask, "name_218567310779840");
panelTask.setLayout(null);
panelTask.add(menuBar);
JPanel panelMyTask = new JPanel();
frame.getContentPane().add(panelMyTask, "name_218578712986622");
panelMyTask.add(menuBar);
JPanel panelMySoftware = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_218590026900741");
panelMySoftware.add(menuBar);
JPanel panelMyDevices = new JPanel();
frame.getContentPane().add(panelMyDevices, "name_218598029981563");
panelMyDevices.add(menuBar);
}
}
Image
i don't think its a good idea to add a JMenuBar into a JPanel, but if you insist...
a JMenuBar can be added only to one container, so you need to create more instances of the JMenuBar. That should work without problems if you use the command pattern.
//first instance
JMenuBar taskMenuBar = new MyJMenuBarImplementation();
JPanel panelMyTask = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_xxx");
panelMyTask.add(taskMenuBar);
//second instance
JMenuBar softwareMenuBar = new MyJMenuBarImplementation();
JPanel panelMySoftware = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_yyy");
panelMySoftware.add(softwareMenuBar);
//and so on...
Related
I'm trying to have one panel appear under the other (textPanel to appear under mainPanel).
But instead, textPanel is appearing overtop of mainPanel:
FlatLightLaf.setup();
FlatLightLaf.supportsNativeWindowDecorations();
UIManager.setLookAndFeel(new FlatLightLaf());
JFrame frame = new JFrame();
frame.setTitle("Title");
frame.setSize(640, 480);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem menuFileSave = new JMenuItem("Save");
menuFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
menu.add(menuFileSave);
menuBar.add(menu);
FlowLayout mainLayout = new FlowLayout(FlowLayout.LEFT);
frame.setJMenuBar(menuBar);
JPanel mainPanel = new JPanel(new BorderLayout());
String datesString[] = {"Tuesday May-03-2022", "Monday May-02-2022"};
#SuppressWarnings("rawtypes")
JComboBox dateDropDown = new JComboBox<>(datesString);
dateDropDown.setFont(new Font("Calibri", Font.PLAIN, 17));
dateDropDown.setVisible(true);
mainPanel.add(dateDropDown);
mainPanel.setVisible(true);
frame.add(mainPanel);
JPanel textPanel = new JPanel(new BorderLayout());
JTextArea textArea = new JTextArea();
textPanel.add(textArea);
textPanel.setVisible(true);
frame.add(textPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
How do I ensure textPanel goes below mainPanel on its own row/line, and not overtop of it?
The default, when adding one component, without further arguments, to a JFrame is that the component in question will take up the entire client area, since JFrame uses a BorderLayout by default. So, your solution is to use a further argument, telling it to add it at the bottom of the layout:
frame.add(textPanel, BorderLayout.PAGE_END);
I need to create a JMenuBar that will be shown under of JTabbedPane named as shapes. When I changed tab, menu bar will not be shown in the other tab. You can see what I mean from images.
I created a menu bar and add it to JFrame but that is not I mean. If you did not understand a point let me explain.
public class Gui extends JPanel {
JFrame frame;
JTabbedPane tabbedPane;
JMenuBar menuBar;
JMenu createShapes, display, help;
JMenuItem RandomShapes, Rectangle, Circle, Square;
public void createFrame() {
frame = new JFrame();
frame.setSize(1000, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
frame.setFocusable(false);
setVisible(true);
setSize(1000, 600);
}
public void createMenus() {
menuBar = new JMenuBar();
//frame.setJMenuBar(menuBar);
createShapes = new JMenu("CreateShapes");
menuBar.add(createShapes);
display = new JMenu("Display");
menuBar.add(display);
help = new JMenu("Help");
menuBar.add(help);
RandomShapes = new JMenuItem("Random Shapes");
createShapes.add(RandomShapes);
Rectangle = new JMenuItem("Rectangle");
createShapes.add(Rectangle);
Circle = new JMenuItem("Circle");
createShapes.add(Circle);
Square = new JMenuItem("Square");
createShapes.add(Square);
}
public Gui() {
createFrame();
createMenus();
frame.add(this);
//===frames part
tabbedPane = new JTabbedPane();
frame.getContentPane().add(tabbedPane);
JPanel gui2 = new JPanel();
tabbedPane.addTab("Shapes", this);
tabbedPane.addTab("Images", gui2);
//===endframespart
}
}
The other tab image
Shapes tab image
Actually, you cannot set menu bar to JTabbedPane.
You need to add JInternalFrame inside one of the tabs of JTabbedPane, then
you can call setJMenuBar of JInternalFrame.
Here is a simple example:
JInternalFrame jInternalFrame = new JInternalFrame();
jMenuBar = new javax.swing.JMenuBar();
jMenu1 = new JMenu("Save");
jMenu2 = new JMenu("Open");
jMenuBar.add(jMenu1);
jMenuBar.add(jMenu2);
jInternalFrame.setJMenuBar(jMenuBar);
tabbedPane.addTab("tab3", jInternalFrame);
I'm working on a Java desktop Application that uses multiple Jpanels as cards in a CardLayout, the problem is that when I switch between the cards the JmenuBar disappears totally or just parts of it.I have a mainFramewhich holds all the Jpanels and the JmenuBar, the other Jpanels have some texts and JButtons and JLabels Here's how I'm implementing this :
This is the Frame that holds everything mainFrame.java
public class mainFrame extends JFrame {
JPanel cards ;
menubar menu= new menubar();
mainPanel card1 = new mainPanel();
Ajout card2= new Ajout();
//ViewAjoutEnf card3= new ViewAjoutEnf();
public mainFrame(){
setResizable(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
this.add(menu);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cards = new JPanel(new CardLayout());
cards.add(card1, "Card 1");
cards.add(card2, "Card 2");
// cards.add(card3, "Card 3");
getContentPane().add(cards);
}
This is the JmenuBar class menubar.Java:
public class menubar extends JMenuBar{
JMenu menuouvrir = new JMenu("ملف");
JMenuItem ajoutbase = new JMenuItem("فتح");
JMenuItem quiter = new JMenuItem("خروج ");
JMenuItem motpass = new JMenuItem("تبديل كلمة السر");
JMenu menuajout = new JMenu("ادخال ");
JMenuItem ajoutprodui = new JMenuItem("ادخال منتوج");
JMenuItem listproduit = new JMenuItem("لائحة المنتوجات");
JMenu menusortie = new JMenu("اخراج");
JMenuItem sortiproduit = new JMenuItem("اخراج منتوج");
JMenu retour = new JMenu("عودة ");
JMenu menuapropos = new JMenu("?");
public menubar (){
this.setBounds(0, 0, 1370, 30);
this.add(Box.createHorizontalGlue());
this.setFont(new Font("sans-serif", Font.PLAIN, 12));
menuouvrir.add(ajoutbase);
menuouvrir.add(motpass);
menuouvrir.addSeparator();
menuouvrir.add(quiter);
menuajout.add(ajoutprodui);
menuajout.add(listproduit);
menusortie.add(sortiproduit);
this.add(menuapropos);
this.add(retour);
this.add(menusortie);
this.add(menuajout);
this.add(menuouvrir);
this.setVisible(true);
}
and these are the Two Jpanels i have:
mainPanel.Java
public class mainPanel extends JPanel {
JButton but = new JButton("dsdffd");
public mainPanel(){
this.setLayout(null);
this.add(but);
but.setBounds(70,500,70,70);
this.setBackground(Color.white);
this.setVisible(true);
}
}
and Ajou.Java:
public class Ajout extends JPanel{
JButton but = new JButton("dsdffd");
public Ajout(){
this.setLayout(null);
this.add(but);
but.setBounds(70,500,70,70);
this.setBackground(Color.white);
this.setVisible(true);
}
}
Don't extend JMenuBar. There is no reason to do this. You create an instance of JMenuBar and and add JMenu instances to the menu bar.
Don't use a null layout. A JMenuBar has its own layout manager.
I don't see where you add the menu bar to the frame using the setJMenBar(...) method.
Read the section from the Swing tutorial on How to Use Menus for more information and working examples. The examples will also show you how to better structure your code.
Also, don't keep extending panels just to add a single component to the panel. You can add multiple components to any panel. And make sure your panels use a layout manager.
So in my GUI, I have a JFrame that's a borderlayout. There's a menubar, and some GUI stuff in NORTH and WEST. In CENTER, there is one JLabel. I want it to move to the center (both horizontally and vertically) of the JPanel. How do I do that correctly? I tried box layout and grid layout. One requirement is that I cannot use gridbag layout.
public class NewClass extends JFrame{
public NewClass () {
setVisible(true);
setSize(500,500);
setDefaultCloseOperation (EXIT_ON_CLOSE);
//menubar
JMenuBar bar = new JMenuBar();
JMenu editMenu = new JMenu("Edit");
JMenuItem mItem = new JMenuItem("Cut"); // edit->cut
editMenu.add(mItem);
mItem = new JMenuItem("Copy"); // edit->copy
editMenu.add(mItem);
mItem = new JMenuItem("Paste"); // edit->paste
editMenu.add(mItem);
bar.add(editMenu);
this.setJMenuBar(bar);
//north panel
JPanel topPanel = new JPanel();
this.add(topPanel,BorderLayout.NORTH);
JLabel myLabel = new JLabel ("Label:") ;
topPanel.add(myLabel);
JButton mytopButton = new JButton ("Push Me");
topPanel.add(mytopButton);
//left panel
JPanel leftPanel = new JPanel();
leftPanel.setBorder (new TitledBorder("Commands:"));
leftPanel.setLayout (new GridLayout (10,1));
this.add(leftPanel,BorderLayout.WEST);
JButton myLeftButton1 = new JButton ("Button 1");
leftPanel.add(myLeftButton1);
JButton myLeftButton2 = new JButton ("Button 2");
leftPanel.add(myLeftButton2);
JButton myLeftButton3 = new JButton ("Button3");
leftPanel.add(myLeftButton3);
//center panel
JPanel centerPanel = new JPanel();
this.add(centerPanel,BorderLayout.CENTER);
JLabel mapLabel = new JLabel("Test_String"); //move this to center of JPanel
centerPanel.add(mapLabel);
centerPanel.setBorder (new EtchedBorder(Color.black,Color.black));
centerPanel.setBackground (Color.white);
}
}
Check the API for methods that affect the alignment of the component.
There are methods that affect the alignment of the component within the layout manager and others that affect the alignment of the text within the label itself.
Start by taking a look at the JavaDocs for JLabel
Specifically, JLabel#setHorizontalAlignment and JLabel#setVerticalAlignment
Answered. Thanks everyone.
JPanel centerPanel = new JPanel();
centerPanel.setLayout (new GridLayout ()); //added
this.add(centerPanel,BorderLayout.CENTER);
JLabel mapLabel = new JLabel("Test_String");
mapLabel.setHorizontalAlignment(SwingConstants.CENTER); //added
mapLabel.setVerticalAlignment(SwingConstants.CENTER); //added
centerPanel.add(mapLabel);
centerPanel.setBorder (new EtchedBorder(Color.black,Color.black));
centerPanel.setBackground (Color.white);
I just started to learn swing by myself, I'm little bit confused why my event does not work here:
1.I'm trying to delete everything from my panel if the user click menu bar -> load but it force me to change the panel to final because i'm using it inside the event!
2.I have defined new panel in my event and defined two more container to add to that panel and then add it to the main frame but it seems nothing happening!
Please help me if you can find out what is wrong.
Sorry in advance for messy code.
I appreciate any hints.
public class SimpleBorder {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
myFrame frame = new myFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MyFrame extends JFrame {
public MyFrame()
{
setSize(500,500);
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel label = new JLabel("my name is bernard...");
Color myColor = new Color(10, 150, 80);
panel.setBackground(myColor);
label.setFont(new Font("Serif", Font.PLAIN, 25));
Dimension size = label.getPreferredSize();
Insets insets = label.getInsets();
label.setBounds(85+insets.left, 120+insets.top , size.width, size.height);
panel.add(label);
JMenuBar menu = new JMenuBar();
setJMenuBar(menu);
JMenu col = new JMenu("Collection");
menu.add(col);
JMenu help = new JMenu("Help");
menu.add(help);
Action loadAction = new AbstractAction("Load")//menu item exit goes here
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event)
{
JTextArea text = new JTextArea(10, 40);
JScrollPane scrol1 = new JScrollPane(text);
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JScrollPane scrol2 = new JScrollPane(list);
JPanel panel2 = new JPanel(new BorderLayout());
panel2 = new JPanel(new GridLayout(1, 2 ));
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
}
};
JMenuItem load = new JMenuItem(loadAction);
col.add(load);
add(panel);
}
}
Call revalidate()/repaint() on your JFrame instance after adding the new panel:
JPanel panel2 = new JPanel(new BorderLayout());
// panel2 = new JPanel(new GridLayout(1, 2 ));//why this it will overwrite the above layout
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
revalidate();
repaint();
Also call pack() on you JFrame instance so all components are spaced by the layoutmanager. As said in a comment dont extend the JFrame class, create a variable of the frame and initiate all that you need on the frames instance, and dont set a layout to null, unless you love hard work :P
Alternatively as mentioned by mKorbel, a CardLayout may be more what you want, it will allow you to use a single JPanel and switch between others/new ones:
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
//add card panel to frame
frame.add(cards);
//swap cards
CardLayout cl = (CardLayout)(cards.getLayout());//get layout of cards from card panel
cl.show(cards, TEXTPANEL);//show another card