我正在开发一个Java Swing项目,我希望页面顶部有JMenuBar
JMenu
s,当我选择JMenu
时,我想要JFrame
1}}填充一些输入字段。我尝试将构成框架的面板添加到JMenu
,当我按下每个JMenu
时,JFrame
由不同的组件填充。我的问题是,我可以用不同的方式得到这个结果吗?
答案 0 :(得分:0)
对于JFrame,JMenu栏的场景,其中每个菜单适用于不同的视图/面板......
您应该考虑使用CardLayout
将此JPanel指定为CardLayout。
将每个JPanel添加为卡片中的卡片
cards.add(card1,“Card 1”);
cards.add(card2,“Card 2”);
cards.add(card3,“Card 3”);
在每个菜单上,单击切换到所需的面板:按
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, "Card 2");
答案 1 :(得分:0)
这是Maverick_Mrt写的一个很小的例子:
package test;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class CardTest extends JFrame {
public CardTest() {
super("Card Test");
this.getContentPane().setLayout(new BorderLayout());
JMenuBar menuBar = new JMenuBar();
JMenu cardsMenu = new JMenu("Cards");
JMenuItem card1 = new JMenuItem("Card 1");
JMenuItem card2 = new JMenuItem("Card 2");
cardsMenu.add(card1);
cardsMenu.add(card2);
menuBar.add(cardsMenu);
this.getContentPane().add(menuBar, BorderLayout.NORTH);
JPanel cardPanel1 = new JPanel();
cardPanel1.setLayout(new BorderLayout());
cardPanel1.add(new JLabel("Card_ 1"), BorderLayout.CENTER);
JPanel cardPanel2 = new JPanel();
cardPanel2.setLayout(new BorderLayout());
cardPanel2.add(new JLabel("Card_ 2"), BorderLayout.CENTER);
JPanel cards = new JPanel();
cards.setLayout(new CardLayout());
cards.add(cardPanel1, "Card 1");
cards.add(cardPanel2, "Card 2");
card1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, "Card 1");
}
});
card2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, "Card 2");
}
});
this.getContentPane().add(cards,BorderLayout.CENTER);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String args[]) {
CardTest cardTest = new CardTest();
}
}