在Java Swing中切换框架

3

我仅在Window Builder上制作了一个小应用程序,并需要一些帮助。我已经单独创建了两个框架,但我不知道如何指定按钮的操作方式,以使得当我单击第一个框架中的“下一个”按钮时,它可以转移到第二个框架。

这是每个文件的源代码。

first.java

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.AbstractAction;

import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.event.ActionListener;


public class first extends JFrame {

private JPanel contentPane;
private final Action action = new SwingAction();
private final Action action_1 = new SwingAction();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                first frame = new first();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public first() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnNext = new JButton("Next");
    btnNext.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    btnNext.setAction(action_1);
    btnNext.setBounds(257, 228, 55, 23);
    contentPane.add(btnNext);

    JButton btnExit = new JButton("Exit");
    btnExit.setBounds(344, 228, 51, 23);
    contentPane.add(btnExit);

    JRadioButton rdbtnAdd = new JRadioButton("Add");
    rdbtnAdd.setBounds(27, 80, 109, 23);
    contentPane.add(rdbtnAdd);

    JRadioButton rdbtnDelete = new JRadioButton("Delete");
    rdbtnDelete.setBounds(27, 130, 109, 23);
    contentPane.add(rdbtnDelete);

    JRadioButton rdbtnEdit = new JRadioButton("Edit");
    rdbtnEdit.setBounds(27, 180, 109, 23);
    contentPane.add(rdbtnEdit);

    JLabel lblSelectAnOption = new JLabel("Select an Option");
    lblSelectAnOption.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblSelectAnOption.setBounds(27, 36, 121, 23);
    contentPane.add(lblSelectAnOption);
}
private class SwingAction extends AbstractAction {
    public SwingAction() {
        putValue(NAME, "Next");
        putValue(SHORT_DESCRIPTION, "Some short description");
    }
    public void actionPerformed(ActionEvent e) {
        new second_add();
    }
}
}

second.java

    import java.awt.BorderLayout;
    import java.awt.EventQueue;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    import javax.swing.JComboBox;
    import javax.swing.AbstractAction;
    import java.awt.event.ActionEvent;
    import javax.swing.Action;
    import java.awt.event.ActionListener;


    public class second_add extends JFrame {

        private JPanel contentPane;
        private JTextField txtTypeYourQuestion;
        private JTextField txtQuestionWeight;
        private JTextField txtEnter;
        private JTextField txtEnter_1;
        private JTextField txtValue;
        private JTextField txtValue_1;
        private final Action action = new SwingAction();

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        second_add frame = new second_add();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public second_add() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 450, 300);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);

            txtTypeYourQuestion = new JTextField();
            txtTypeYourQuestion.setBounds(22, 11, 177, 20);
            txtTypeYourQuestion.setText("Type your Question Here");
            contentPane.add(txtTypeYourQuestion);
            txtTypeYourQuestion.setColumns(10);

            txtQuestionWeight = new JTextField();
            txtQuestionWeight.setBounds(209, 11, 86, 20);
            txtQuestionWeight.setText("Question weight");
            contentPane.add(txtQuestionWeight);
            txtQuestionWeight.setColumns(10);

            txtEnter = new JTextField();
            txtEnter.setBounds(22, 55, 86, 20);
            txtEnter.setText("Enter . . .");
            contentPane.add(txtEnter);
            txtEnter.setColumns(10);

            txtEnter_1 = new JTextField();
            txtEnter_1.setText("Enter . . . ");
            txtEnter_1.setBounds(22, 104, 86, 20);
            contentPane.add(txtEnter_1);
            txtEnter_1.setColumns(10);

            txtValue = new JTextField();
            txtValue.setText("Value . .");
            txtValue.setBounds(118, 55, 51, 20);
            contentPane.add(txtValue);
            txtValue.setColumns(10);

            txtValue_1 = new JTextField();
            txtValue_1.setText("Value . .");
            txtValue_1.setBounds(118, 104, 51, 20);
            contentPane.add(txtValue_1);
            txtValue_1.setColumns(10);

            JButton btnFinish = new JButton("Finish");
            btnFinish.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                }
            });
            btnFinish.setAction(action);
            btnFinish.setBounds(335, 228, 89, 23);
            contentPane.add(btnFinish);

            JButton btnAddChoice = new JButton("Add choice");
            btnAddChoice.setBounds(236, 228, 89, 23);
            contentPane.add(btnAddChoice);

            JButton btnAddQuestion = new JButton("Add question");
            btnAddQuestion.setBounds(136, 228, 89, 23);
            contentPane.add(btnAddQuestion);

        }
        private class SwingAction extends AbstractAction {
            public SwingAction() {
                putValue(NAME, "");
                putValue(SHORT_DESCRIPTION, "Some short description");
            }
            public void actionPerformed(ActionEvent e) {
            }
        }
    }
5个回答

2
  • 在一个应用程序中拥有多个JFrame实例会降低可用性。
  • 考虑使用类似CardLayout的东西代替。

2
为什么我的回答被编辑成指向 Stack Overflow 上其他讨论的链接?我在发布回复时根本不知道那个特定的问题。我可以理解为了格式或链接到 Java 文档而进行编辑,但将其更改为指向其他人的答案的 URL 是不正确的。请撤销这个错误的链接。 - undefined
1
好的,没关系。我自己已经编辑掉了。如果你想提供额外的信息或参考资料,请尽管这样做。只是请不要在我的回答中提供它们。 - undefined

1
你可以通过创建其对象并使用setVisible方法来导航到帧。如果您想在按钮单击时执行此操作,请将其编写在其事件处理程序中。
JFrame o = new JFrame();
o.setVisible(true);
dispose();        // This will close the current frame

1

修改为如下内容 -

JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        second_add second = new second_add();   
        setVisible(false); // Hide current frame
        second.setVisible(true);
    }
});

1

快速且简单的解决方案是在您的按钮点击操作中将第一帧的可见性设置为false,将第二帧的可见性设置为true。(请参阅Sajal Dutta的答案)

但是,为了使多个帧的行为保持一致,让每个帧都存储在HashTable中,该HashTable位于您的主类中(即持有main方法并且扩展JFrame)。ID是帧的顺序(第一帧D1,第二帧ID2等)。

然后创建一个静态方法

public void switchFrame(JFrame originatingFrame, int NextFrame){
    originatingFrame.this.setVisible(false);
    ((JFrame) myHashTable.get(NextFrame)).setVisible(true);
}

在您的主类中,可以通过每个帧调用来使用。
mainClass.switchFrame(this, IdOfFrameYouWantToGoTo);

那样的话,如果您想创建像向导一样的东西,您还可以实现“返回”和“跳过”按钮。
注意:我没有测试过这段代码。这只应被视为如何执行此操作的一般概述。

0
下面的代码片段将展示如何以菜单形式从一个页面导航到另一个页面。
 import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.CardLayout;
    import java.awt.Container;
    import java.awt.GraphicsEnvironment;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Panel;
    import java.awt.TextArea;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    import java.io.PrintStream;
    import java.util.ArrayList;

    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;

public class AddressBookDemo implements ActionListener, Runnable {

    ArrayList personsList;
    PersonDAO pDAO;
    Panel panel;
    JFrame appFrame;
    JLabel jlbName, jblPassword, jlbAddress;
    JPasswordField jPassword;
    JTextField jtfName, jtfAddress;
    JButton jbbSave, jbnClear, jbnExit, btnNext, button;
    String name, address, password;
    final int CARDS = 4;
    CardLayout cl = new CardLayout();
    JPanel cardPanel = new JPanel(cl);
    CardLayout c2 = new CardLayout();
    JPanel cardPanel2 = new JPanel(c2);
    int currentlyShowing = 0;
    Thread errorThrower; 
    // int phone;
    // int recordNumber; // used to naviagate using >> and buttons
    Container cPane;
    Container cPane2;

    private JFrame frame;
    private TextArea textArea;
    private Thread reader;
    private Thread reader2;
    private boolean quit;

    private final PipedInputStream pin = new PipedInputStream();
    private final PipedInputStream pin2 = new PipedInputStream();
    public static void main(String args[]) {
        new AddressBookDemo();
    }

    public AddressBookDemo() {
        name = "";
        password = "";
        address = "";
        // phone = -1; //Stores 0 to indicate no Phone Number
        // recordNumber = -1;
        createGUI();
        personsList = new ArrayList();
        // creating PersonDAO object
        pDAO = new PersonDAO();
    }

    public void createGUI() {

        /* Create a frame, get its contentpane and set layout */
        appFrame = new JFrame("ManualDeploy ");
        cPane = appFrame.getContentPane();
        cPane.setLayout(new GridBagLayout());
//      frame=new JFrame("Java Console");
        textArea=new TextArea();
        textArea.setEditable(false);
        Button button=new Button("clear");

         panel=new Panel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
        gridBagConstraintsx01.gridx = 0;
        gridBagConstraintsx01.gridy = 0;
        gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
        panel.add(textArea,gridBagConstraintsx01);
        GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
        gridBagConstraintsx03.gridx = 0;
        gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx03.gridy = 1;
        panel.add(button,gridBagConstraintsx03);
//      frame.add(panel);

//      frame.setVisible(true);     
//      cPane2 = frame.getContentPane();
//      cPane2.setLayout(new GridBagLayout());
        button.addActionListener(this);

        try
        {
            PipedOutputStream pout=new PipedOutputStream(this.pin);
            System.setOut(new PrintStream(pout,true));  
        } 
        catch (java.io.IOException io)
        {
            textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
        }
        catch (SecurityException se)
        {
            textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
        } 

        try 
        {
            PipedOutputStream pout2=new PipedOutputStream(this.pin2);
            System.setErr(new PrintStream(pout2,true));
        } 
        catch (java.io.IOException io)
        {
            textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
        }
        catch (SecurityException se)
        {
            textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
        }       

        quit=false; // signals the Threads that they should exit

        // Starting two seperate threads to read from the PipedInputStreams             
        //
        reader=new Thread(this);
        reader.setDaemon(true); 
        reader.start(); 
        //
        reader2=new Thread(this);   
        reader2.setDaemon(true);    
        reader2.start();

        // testing part
        // you may omit this part for your application
        // 
        System.out.println("Hello World 2");
        System.out.println("All fonts available to Graphic2D:\n");
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames=ge.getAvailableFontFamilyNames();
        for(int n=0;n<fontNames.length;n++)  System.out.println(fontNames[n]);      
        // Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
        // We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
        System.out.println("\nLets throw an error on this console");    
        errorThrower=new Thread(this);
        errorThrower.setDaemon(true);
        errorThrower.start();



        arrangeComponents();
        // arrangeComponents2();
        final int CARDS = 2;
        final CardLayout cl = new CardLayout();
        final JPanel cardPanel = new JPanel(cl);
        JMenu menu = new JMenu("M");
        for (int x = 0; x < CARDS; x++) {
            final int SELECTION = x;
            JPanel jp = new JPanel();
            if (x == 0) {
                jp.add(cPane);
            } else if (x == 1) {
                 jp.add(panel);
            } else if (x == 2)
                jp.add(new JButton("Panel 2"));
            else
                jp.add(new JComboBox(new String[] { "Panel 3" }));
            cardPanel.add("" + SELECTION, jp);
            JMenuItem menuItem = new JMenuItem("Show Panel " + x);
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    currentlyShowing = SELECTION;
                    cl.show(cardPanel, "" + SELECTION);
                }
            });
            menu.add(menuItem);
        }
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);

        btnNext = new JButton("Next >>");

        JButton btnPrev = new JButton("<< Previous");
        JPanel p = new JPanel(new GridLayout(1, 2));
        p.add(btnPrev);
        p.add(btnNext);
        btnNext.setVisible(false);
        JFrame f = new JFrame();
        f.getContentPane().add(cardPanel);
        f.getContentPane().add(p, BorderLayout.SOUTH);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 500);
        f.setLocationRelativeTo(null);
        f.setJMenuBar(menuBar);
        f.setVisible(true);
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (currentlyShowing < CARDS - 1) {
                    cl.next(cardPanel);
                    currentlyShowing++;
                }
            }
        });
        btnPrev.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (currentlyShowing > 0) {
                    cl.previous(cardPanel);
                    currentlyShowing--;
                }
            }
        });

    }

    public void arrangeComponents() {
        jlbName = new JLabel("Username");
        jblPassword = new JLabel("Password");
        jlbAddress = new JLabel("Sftpserver");
        jtfName = new JTextField(20);
        jPassword = new JPasswordField(20);
        jtfAddress = new JTextField(20);
        jbbSave = new JButton("move sftp");
        jbnClear = new JButton("Clear");
        jbnExit = new JButton("Exit");
        /* add all initialized components to the container */
        GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
        gridBagConstraintsx01.gridx = 0;
        gridBagConstraintsx01.gridy = 0;
        gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
        cPane.add(jlbName, gridBagConstraintsx01);
        GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
        gridBagConstraintsx02.gridx = 1;
        gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx02.gridy = 0;
        gridBagConstraintsx02.gridwidth = 2;
        gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
        cPane.add(jtfName, gridBagConstraintsx02);
        GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
        gridBagConstraintsx03.gridx = 0;
        gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx03.gridy = 1;
        cPane.add(jblPassword, gridBagConstraintsx03);
        GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
        gridBagConstraintsx04.gridx = 1;
        gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx04.gridy = 1;
        gridBagConstraintsx04.gridwidth = 2;
        gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
        cPane.add(jPassword, gridBagConstraintsx04);
        GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
        gridBagConstraintsx05.gridx = 0;
        gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx05.gridy = 2;
        cPane.add(jlbAddress, gridBagConstraintsx05);
        GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
        gridBagConstraintsx06.gridx = 1;
        gridBagConstraintsx06.gridy = 2;
        gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
        gridBagConstraintsx06.gridwidth = 2;
        gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
        cPane.add(jtfAddress, gridBagConstraintsx06);
        GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
        gridBagConstraintsx09.gridx = 0;
        gridBagConstraintsx09.gridy = 4;
        gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
        cPane.add(jbbSave, gridBagConstraintsx09);
        GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
        gridBagConstraintsx10.gridx = 1;
        gridBagConstraintsx10.gridy = 4;
        gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
        cPane.add(jbnClear, gridBagConstraintsx10);
        GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
        gridBagConstraintsx11.gridx = 2;
        gridBagConstraintsx11.gridy = 4;
        gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
        cPane.add(jbnExit, gridBagConstraintsx11);
        jbbSave.addActionListener(this);
        // jbnDelete.addActionListener(this);
        jbnClear.addActionListener(this);
        jbnExit.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("inside button123");
        if (e.getSource() == jbbSave) {
            savePerson();
        } else if (e.getSource() == jbnClear) {
            clear();
        } else if (e.getSource() == jbnExit) {
            System.exit(0);
        }
        else if (e.getSource() == button)
        {
            System.out.println("inside button");
            textArea.setText(" ");
        }
    }

    // Save the Person into the Address Book
    public void savePerson() {
        name = jtfName.getText();
        password = jPassword.getText();
        address = jtfAddress.getText();
        if (name.equals("")) {
            JOptionPane.showMessageDialog(null, "Please enter password",
                    "ERROR", JOptionPane.ERROR_MESSAGE);
        } else if (password != null && password.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Please enter password",
                    "ERROR", JOptionPane.ERROR_MESSAGE);
        }

        else {
            btnNext.setVisible(true);
            JOptionPane.showMessageDialog(null, "Person Saved");
        }
    }

    public void clear() {
        jtfName.setText("");
        jPassword.setText("");
        jtfAddress.setText("");
        personsList.clear();
    }

    public synchronized void run()
    {
        try
        {           
            while (Thread.currentThread()==reader)
            {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin.available()!=0)
                {
                    String input=this.readLine(pin);
                    textArea.append(input);
                }
                if (quit) return;
            }

            while (Thread.currentThread()==reader2)
            {
                try { this.wait(100);}catch(InterruptedException ie) {}
                if (pin2.available()!=0)
                {
                    String input=this.readLine(pin2);
                    textArea.append(input);
                }
                if (quit) return;
            }           
        } catch (Exception e)
        {
            textArea.append("\nConsole reports an Internal error.");
            textArea.append("The error is: "+e);            
        }

        // just for testing (Throw a Nullpointer after 1 second)
//      if (Thread.currentThread()==errorThrower)
//      {
//          try { this.wait(1000); }catch(InterruptedException ie){}
//          throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
//      }

    }

    public synchronized String readLine(PipedInputStream in) throws IOException
    {
        String input="";
        do
        {
            int available=in.available();
            if (available==0) break;
            byte b[]=new byte[available];
            in.read(b);
            input=input+new String(b,0,b.length);                                                       
        }while( !input.endsWith("\n") &&  !input.endsWith("\r\n") && !quit);
        return input;
    }   
    public synchronized void windowClosed(WindowEvent evt)
    {
        quit=true;
        this.notifyAll(); // stop all threads
        try { reader.join(1000);pin.close();   } catch (Exception e){}      
        try { reader2.join(1000);pin2.close(); } catch (Exception e){}
        System.exit(0);
    }       



}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接