[Java GUI] 筛选指定区间内满足条件的数字

嵌套布局的一个简单示例

[Java GUI] 筛选指定区间内满足条件的数字_第1张图片

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

class NumberFrame extends JFrame implements ActionListener {

	private static final long serialVersionUID = -8079275721169313862L;

	private JLabel lblInfo = null;
	JTextField txtStart;
	JTextField txtEnd;
	JTextField txtFactor;
	JTextArea txtRes;
	JButton btnCalc;
	JPanel inputPanel;
	JScrollPane resultPane;
	JPanel panel;

	NumberFrame(String title) {
		super(title);
		lblInfo = new JLabel("Number Game", JLabel.CENTER);
		Container cp = getContentPane();
		cp.add(lblInfo, BorderLayout.NORTH);

		txtStart = new JTextField();
		txtEnd = new JTextField();
		txtFactor = new JTextField();

		panel = new JPanel();
		panel.setLayout(new BorderLayout());

		JPanel lblPane = new JPanel();
		lblPane.setLayout(new GridLayout(4, 1));
		lblPane.add(new JLabel("From"));
		lblPane.add(new JLabel("To"));
		lblPane.add(new JLabel("Factor"));
		lblPane.add(new JLabel());

		JPanel txtPane = new JPanel();
		txtPane.setLayout(new GridLayout(4, 1));
		txtPane.add(txtStart);
		txtPane.add(txtEnd);
		txtPane.add(txtFactor);
		btnCalc = new JButton("Compute");
		btnCalc.addActionListener(this);
		txtPane.add(btnCalc);

		// input panel
		inputPanel = new JPanel();
		inputPanel.setLayout(new BorderLayout());
		inputPanel.add(lblPane, BorderLayout.WEST);
		inputPanel.add(txtPane, BorderLayout.CENTER);
		
		panel.add(inputPanel, BorderLayout.WEST);

		// result panel
		txtRes = new JTextArea(150, 10);
		txtRes.setLineWrap(true);
		resultPane = new JScrollPane(txtRes);
		panel.add(resultPane, BorderLayout.CENTER);

		cp.add(panel);

		setSize(400, 150);
		setLocation(300, 200);
		setResizable( false );
		setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnCalc) {
			txtRes.setText(null);
			try {
				int m = Integer.parseInt(txtStart.getText().trim());
				int n = Integer.parseInt(txtEnd.getText().trim());
				int factor = Integer.parseInt(txtFactor.getText().trim());

				for (int i = m; i <= n; ++i) {
					if (i % factor == 0)
						txtRes.append(String.valueOf(i) + " ");
				}
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			}
		}
	}
}

public class EvenNumberDemo {
	public static void main(String[] args) {
		new NumberFrame("Number Game");
	}
}



你可能感兴趣的:(java,String,null,Class,input,import)