使用JButton在JPanel之间切换?

时间:2019-04-29 16:04:40

标签: java swing cardlayout

尝试制作抽认卡应用程序。 JButton b_switchmode将用于在面板之间进行切换(编辑模式和测试模式,均具有为单独使用而创建的面板)。不太确定如何从我创建的GUI中进行操作。理想情况下,我将单击JButton b_switchmode,然后从“编辑模式”切换到“测试模式”。

我知道可能需要CardLayout,但是我无法实现使程序可执行的正确语法。

所以我想知道如何:

  • 插入CardLayout以便能够在JPanels

  • 之间切换
  • 允许JButton b_switchmodeJPanels

  • 之间执行切换

public class App2 {
    private static JFrame frame;
    private static JPanel editpanel;
    private static JPanel testpanel; 
    private static JLabel l_appmode;
    private static JLabel l_number;
    private static JLabel l_question;
    private static JLabel l_answer;
    public  static JTextField t_questions;
    public  static JTextField t_answer;
    public  static JButton    b_switchmode;
    public  static JButton    b_previous;
    public  static JButton    b_next;
    public  static JButton    b_add;
    public  static JButton    b_save;
    public  static JButton    b_question;
    public  static JButton    b_answer;
    static int width  = 600;
    static int height = 450;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    gui();
}

private static void gui(){
  frame = new JFrame("Assignment2");
  frame.setTitle("Flash Cards");
  frame.setSize(width,height);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  l_appmode  = new JLabel("Current Mode: Edit");  
  l_number = new JLabel ("");
  l_question  = new JLabel("Question:");
  l_answer    = new JLabel("Answer:");

  t_questions = new JTextField("");
  t_answer    = new JTextField("");

  b_switchmode = new JButton("Switch Mode");
  b_previous = new JButton("Previous");
  b_next = new JButton("Next");
  b_add = new JButton("Add");
  b_save = new JButton("Save");
  b_question = new JButton("Question");
  b_answer = new JButton("Answer");


  editpanel = new JPanel();
  int rows = 6, columns = 1;
  int hgap = 20; int vgap = 20;
  editpanel.setLayout(new GridLayout(rows, columns, hgap, 
  vgap));

  editpanel.add(l_appmode);
  editpanel.add(l_number);

  editpanel.add(l_question);
  editpanel.add(t_questions);

  editpanel.add(l_answer);
  editpanel.add(t_answer);

  editpanel.add(b_switchmode);
  editpanel.add(b_previous);
  editpanel.add(b_next);
  editpanel.add(b_add);
  editpanel.add(b_save);

  //testpanel.add(b_question);
  //testpanel.add(t_questions);
  //testpanel.add(b_answer);
  //testpanel.add(t_answer);

  frame.add(editpanel);
  //frame.add(testpanel);
  frame.setVisible(true);
}

0 个答案:

没有答案