JTextField 只能输入限定的数字

本文介绍了一个自定义的Swing组件——NumberLenghtLimitedDm,该组件继承自PlainDocument,用于限制JTextField中只能输入指定长度的数字。通过覆盖insertString方法实现过滤非数字字符及长度控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package com.util;

import javax.swing.text.*;

/**
* 实现让文体框只能输入限定长度的数字
* @author 曾祥训
*
*/
public class NumberLenghtLimitedDmt extends PlainDocument {

/**
*
*/
private static final long serialVersionUID = -7371120135793981234L;

private int limit;

public NumberLenghtLimitedDmt(int limit) {
super();
this.limit = limit;
}

public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {

char[] upper = str.toCharArray();
int length = 0;
for (int i = 0; i < upper.length; i++) {
if (upper[i] >= '0' && upper[i] <= '9') {
upper[length++] = upper[i];
}
}
super.insertString(offset, new String(upper, 0, length), attr);
}
}
}



使用
JTextField txtAge = new JTextField();
txtAge.setDocument(new NumberLenghtLimitedDmt(3));
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; public class GuessNumberGameGUI extends JFrame { // 游戏状态 private int targetNumber; private int attempts; private int maxAttempts; private int maxNumber; private int totalGames = 0; private int totalWins = 0; private int bestScore = Integer.MAX_VALUE; // UI组件 private JLabel titleLabel; private JLabel promptLabel; private JLabel resultLabel; private JLabel attemptsLabel; private JTextField guessField; private JButton guessButton; private JButton newGameButton; private JButton statsButton; private JComboBox<String> difficultyCombo; public GuessNumberGameGUI() { // 设置窗口属性 setTitle("猜数游戏"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 初始化UI组件 initComponents(); // 默认开始一个简单难度的游戏 startNewGame(1); } private void initComponents() { // 创建面板 JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 顶部面板 - 标题和难度选择 JPanel topPanel = new JPanel(new GridLayout(2, 1, 5, 5)); titleLabel = new JLabel("猜数游戏", JLabel.CENTER); titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); JPanel difficultyPanel = new JPanel(); difficultyPanel.add(new JLabel("选择难度:")); String[] difficulties = {"简单 (1-50)", "中等 (1-100)", "困难 (1-200)"}; difficultyCombo = new JComboBox<>(difficulties); difficultyCombo.addActionListener(e -> { startNewGame(difficultyCombo.getSelectedIndex() + 1); }); difficultyPanel.add(difficultyCombo); topPanel.add(titleLabel); topPanel.add(difficultyPanel); // 中间面板 - 游戏区域 JPanel centerPanel = new JPanel(new GridLayout(3, 1, 5, 5)); promptLabel = new JLabel("请输入一个数字:", JLabel.CENTER); promptLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16)); guessField = new JTextField(); guessField.setFont(new Font("微软雅黑", Font.PLAIN, 16)); guessField.setHorizontalAlignment(JTextField.CENTER); guessField.addActionListener(e -> checkGuess()); resultLabel = new JLabel("", JLabel.CENTER); resultLabel.setFont(new Font("微软雅黑", Font.BOLD, 16)); attemptsLabel = new JLabel("", JLabel.CENTER); attemptsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14)); centerPanel.add(promptLabel); centerPanel.add(guessField); centerPanel.add(resultLabel); centerPanel.add(attemptsLabel); // 底部面板 - 按钮 JPanel bottomPanel = new JPanel(new GridLayout(1, 3, 5, 5)); guessButton = new JButton("猜"); guessButton.addActionListener(e -> checkGuess()); newGameButton = new JButton("新游戏"); newGameButton.addActionListener(e -> startNewGame(difficultyCombo.getSelectedIndex() + 1)); statsButton = new JButton("统计"); statsButton.addActionListener(e -> showStatistics()); bottomPanel.add(guessButton); bottomPanel.add(newGameButton); bottomPanel.add(statsButton); // 添加所有面板到主面板 mainPanel.add(topPanel, BorderLayout.NORTH); mainPanel.add(centerPanel, BorderLayout.CENTER); mainPanel.add(bottomPanel, BorderLayout.SOUTH); // 添加主面板到窗口 add(mainPanel); } private void startNewGame(int difficulty) { // 根据难度设置游戏参数 switch (difficulty) { case 1: // 简单 maxNumber = 50; maxAttempts = 10; break; case 2: // 中等 maxNumber = 100; maxAttempts = 7; break; case 3: // 困难 maxNumber = 200; maxAttempts = 5; break; } // 重置游戏状态 Random random = new Random(); targetNumber = random.nextInt(maxNumber) + 1; attempts = 0; totalGames++; // 更新UI guessField.setText(""); guessField.setEnabled(true); guessButton.setEnabled(true); resultLabel.setText(""); attemptsLabel.setText("尝试次数: 0/" + maxAttempts); promptLabel.setText("请输入一个1-" + maxNumber + "之间的数字:"); } private void checkGuess() { try { int guess = Integer.parseInt(guessField.getText()); if (guess < 1 || guess > maxNumber) { resultLabel.setText("请输入1-" + maxNumber + "之间的数字!"); return; } attempts++; attemptsLabel.setText("尝试次数: " + attempts + "/" + maxAttempts); if (guess == targetNumber) { // 猜对了 totalWins++; if (attempts < bestScore) { bestScore = attempts; } resultLabel.setText("恭喜! 猜对了!"); guessField.setEnabled(false); guessButton.setEnabled(false); } else if (guess < targetNumber) { resultLabel.setText("太小了! 再试一次!"); } else { resultLabel.setText("太大了! 再试一次!"); } if (attempts >= maxAttempts && guess != targetNumber) { resultLabel.setText("游戏结束! 数字是: " + targetNumber); guessField.setEnabled(false); guessButton.setEnabled(false); } guessField.setText(""); guessField.requestFocus(); } catch (NumberFormatException ex) { resultLabel.setText("请输入有效的数字!"); } } private void showStatistics() { String stats = String.format( "<html><center>" + "<h2>游戏统计</h2>" + "<p>总游戏次数: %d</p >" + "<p>胜利次数: %d</p >" + "<p>胜率: %.1f%%</p >" + "<p>最佳成绩: %s</p >" + "</center></html>", totalGames, totalWins, totalGames > 0 ? (totalWins * 100.0 / totalGames) : 0, bestScore == Integer.MAX_VALUE ? "暂无" : (bestScore + "次") ); JOptionPane.showMessageDialog(this, stats, "游戏统计", JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { GuessNumberGameGUI game = new GuessNumberGameGUI(); game.setVisible(true); }); } }根据这个代码帮我写个Java程序设计
最新发布
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值