import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class GridLayoutDemo extends JPanel implements ActionListener{ Panel1 p1; Panel2 p2; GridLayoutDemo(){ p1 = new Panel1(); p2 = new Panel2(); p2.button.addActionListener(this); setLayout(new GridLayout(3,1)); add(new JLabel("计算从起始到终止是因子倍数的数",JLabel.CENTER)); add(p1); add(p2); } public static void main(String[] args) { JFrame jf = new JFrame("GridLayoutDemo"); jf.setSize(600,600); jf.setMinimumSize(new Dimension(100,100)); jf.setMaximumSize(new Dimension(400,400)); jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE); jf.add(new GridLayoutDemo()); //jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { int from = Integer.parseInt(p1.text1.getText()); int to = Integer.parseInt(p1.text2.getText()); int n = Integer.parseInt(p1.text3.getText()); for(int i=from;i<=to;i++) { if (i%n==0) p2.text.append(i+" "); } } } class Panel1 extends JPanel { JTextField text1,text2,text3; Panel1(){ setLayout(new GridLayout(1,6)); text1 = new JTextField(3); text2 = new JTextField(3); text3 = new JTextField(3); add(new JLabel("起始",JLabel.RIGHT)); add(text1); add(new JLabel("终止",JLabel.RIGHT)); add(text2); add(new JLabel("因子",JLabel.RIGHT)); add(text3); } } class Panel2 extends JPanel { JTextArea text; JButton button; Panel2() { setLayout(new BorderLayout()); text = new JTextArea(3,2); text.setLineWrap(true); button = new JButton("开始计算"); JScrollPane js = new JScrollPane(text); add(js,BorderLayout.CENTER); //add(new JLabel()); add(button,BorderLayout.SOUTH); } }
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)