且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将组件动态添加到Java JScrollPane

更新时间:2023-12-03 14:11:52


在JScrollPane中包装P2也不起作用。

Wrapping P2 inside JScrollPane also does not work.

是的,因为这是它的工作方式。如果您花时间阅读如何使用滚动窗格,检查示例,甚至可以参考 JavaDocs 它将为您提供启动和运行UI所需的基本信息。

Yes it does, because that's the way it work. If you take the time to read through the How to use scroll panes, examine the examples and maybe even consult the JavaDocs it would provide you with the basic information you'd need to get you UI up and running.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class JframeExample extends JFrame {

    private final JPanel P1;
    private final JPanel P2;
    private final JPanel main;
    private final JScrollPane scrol;
    private final JButton jButton;
    private final JButton jButton2;

    public JframeExample() {
        P1 = new JPanel();
        P2 = new JPanel();
        main = new JPanel();
        jButton = new JButton("Add");
        jButton2 = new JButton("Remove");
        scrol = new JScrollPane(P2);
        initialize();
        this.add(main);
        this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        this.setSize(400, 400);
        this.setVisible(true);

    }

    public static void main(String[] args) {
        JframeExample jframeExample = new JframeExample();

    }

    private void addPressed(ActionEvent evt) {
        System.out.println("Add Pressed");
        P2.add(new JButton());
        revalidate();
    }

    private void removePressed(ActionEvent evt) {
        System.out.println("Remove Pressed");
        P2.removeAll();
        revalidate();
    }

    private void initialize() {
        main.setLayout(new GridLayout(1, 2));
        main.add(P1);
        main.add(scrol);
        jButton.addActionListener((ActionEvent evt) -> {
            addPressed(evt);
        });
        jButton2.addActionListener((ActionEvent evt) -> {
            removePressed(evt);
        });
        P1.add(jButton);
        P1.add(jButton2);
    }

}

警告字 GroupLayout 真的不适合手工编码,它真的是为UI编辑设计的。

Word of warning GroupLayout really isn't meant for hand coding, it's really designed for UI editors.