JFrame中只显示一个组件

Fun*_*uit 2 java swing jpanel jframe layout-manager

作为我加密项目的改进,我决定制作一个小GUI.但是,当我运行程序时,只有顶部元素出现在屏幕上,它似乎模糊了其他元素,尽管我无法检查.有谁知道为什么?

下面是我的代码中除了整体e()d()因为这些简单的字符串进行加密,并有无关的GUI.我还希望能够在不编辑加密的情况下尽可能加快速度,以使其尽可能好.

@SuppressWarnings("serial")
public class EncDecExample extends JFrame implements ActionListener {
    final static JPanel top = new JPanel();
    final static JPanel mid = new JPanel();
    final static JPanel bot = new JPanel();
    final static JTextField in = new JTextField(10);
    final static JTextField out = new JTextField(10);
    final static JButton enc = new JButton("Encrypt");
    final static JButton dec = new JButton("Decrypt");
    final static JFrame f = new JFrame("Encryption/decryption");

    public static void main(String[] args) {
//        EncDec.exampleImplement();

        f.setSize(500, 500);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        out.setEditable(false);
        out.setText("Hello");
        in.setVisible(true);
        out.setVisible(true);
        enc.setVisible(true);
        dec.setVisible(true);
        top.add(in);
        mid.add(enc);
        mid.add(dec);
        bot.add(out);
        f.add(top);
        f.add(mid);
        f.add(bot);
        f.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == enc && !in.getText().equalsIgnoreCase("")) {
            out.setText(EncDec.e(in.getText(), 5));
        }
        else if(e.getSource() == dec && !in.getText().equalsIgnoreCase("")) {
            out.setText(EncDec.d(in.getText()));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*son 10

a的内容窗格JFrame有一个BorderLayout.如果将一个组件放在一个没有约束的BL中,它最终会在CENTER.中心只能显示一个组件.

为了立竿见影,我建议:

f.add(top, BorderLayout.PAGE_START);
f.add(mid);
f.add(bot, BorderLayout.PAGE_END);
Run Code Online (Sandbox Code Playgroud)

其他要点.

  1. 取出f.setSize(500, 500);并调用pack()之前setVisible(true)
  2. 要获得结束GUI的更好方法,请更改f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  3. in.setVisible(true);除了框架本身,取出这些.当组件添加到顶级容器并且该容器本身可见时,该组件将自动变为可见.
  4. 更改
    public class EncDecExample extends JFrame
    为此
    public class EncDecExample
    代码保留对框架的引用,这是正确的方法.