我正在尝试创建一个菜单,我需要打开一个JPanel。我怎样才能做到这一点?
我希望用户按“个人详细信息”为例,然后打开一个可以添加按钮和文本字段的区域。
public class Payroll{
public static void main(String[] args) {
JFrame frame = new JFrame(" Payroll ");
//create the employees details menu
JMenu employees = new JMenu("Employees");
employees.setMnemonic(KeyEvent.VK_E);
// add employees items
JMenuItem details = new JMenuItem("Individual Details");
details.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
/**********missing code is here, how can i open a JPanel from here?**/
}
});
employees.add(details);
//menu bar
JMenuBar menuBar = new JMenuBar( );
menuBar.add(employees);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(700,550);
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您可以创建另一个具有jpanel的类和用于获取userinput的字段。然后在menuitem actionPerformed事件中创建它的实例...
例如;
这是具有面板的类
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyPanel {
public MyPanel() {
JFrame f=new JFrame();
f.setSize(300,200);
f.setLayout(new GridLayout(1, 1));
JPanel p=new JPanel();
p.setLayout(new GridLayout(3, 1, 2, 2));
JTextField t1=new JTextField(20);
p.add(t1);
f.add(p);
f.setVisible(true);
}
}
并在事件中创建它的实例..
public class Payroll{
public static void main(String[] args) {
JFrame frame = new JFrame(" Payroll ");
JMenu employees = new JMenu("Employees");
employees.setMnemonic(KeyEvent.VK_E);
// add employees items
JMenuItem details = new JMenuItem("Individual Details");
details.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
MyPanel panel=new MyPanel(); // call MyPanel here
}
});
employees.add(details);
//menu bar
JMenuBar menuBar = new JMenuBar( );
menuBar.add(employees);
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(700,550);
frame.setVisible(true);
}
}
答案 1 :(得分:0)
您可以尝试如下,
JPanel panel = new JPanel();
JButton okButton = new JButton("OK");
panel.add(okButton);
JButton cancelButton = new JButton("Cancel");
panel.add(cancelButton);
frame.add(panel);