JTextField中的增/减输入值

时间:2018-11-19 00:16:31

标签: java swing jtextfield

对于我的作业,我需要创建一个应用程序,在其中可以递增或递减JTextField中的值,并且颜色将在下部面板上更改。文本字段是可编辑的,因此只要顶部面板的文本框中的任何值发生更改,下部面板的背景颜色就会立即更新以匹配它。但是,我对此感到麻烦。

我也很难将输入的输入限制为0和256之外的值,以将其视为零。

有没有指针?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class App1 extends JFrame implements ActionListener {
int value1 = 0, value2 = 0, value3 = 0; 
String svalue1, svalue2, svalue3; 
JPanel jp, p1, p2, p3, p4;
JLabel jl1, jl2, jl3; 
JTextField tf1, tf2, tf3; 
JButton b1, b2, b3, b4, b5, b6; 

public static void main(String[] args) {
    App1 app1 = new App1(); 

}

App1()
{
    this.setSize(800,600); 
    this.setTitle("Application 1");
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new JPanel(); 
    jp.setBackground(new Color(value1,value2,value3));
    jp.setLayout(new GridLayout(2,1));
    this.add(jp);

    p1 = new JPanel();
    p1.setLayout(new GridLayout(1,3));
    jp.add(p1); 

    //Panel for "R"
    p2 = new JPanel();
    p2.setBackground(Color.RED);
    //p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));;
    p1.add(p2);
    jl1 = new JLabel("Red"); p2.add(jl1); 
    b1 = new JButton("+");
    b1.addActionListener(this);
    p2.add(b1);
    tf1 = new JTextField("0"); tf1.setEditable(true); p2.add(tf1); 
    tf1.setBounds(140, 70, 200,30);
    b2 = new JButton("-");
    jl1.setAlignmentX(Component.CENTER_ALIGNMENT); tf1.setAlignmentX(Component.CENTER_ALIGNMENT);
    b1.setAlignmentX(Component.CENTER_ALIGNMENT); b2.setAlignmentX(Component.CENTER_ALIGNMENT);
    b2.addActionListener(this);
    p2.add(b2);

public void actionPerformed(ActionEvent e) {
    svalue1 = tf1.getText();
    value1 = Integer.parseInt(svalue1); 
    tf1.setText(svalue1);
    jp.setBackground(new Color(value1, value2, value3));

if(e.getSource() == b1) 
        {
            if(value1 < 256)
            value1++; tf1.setText("" + value1);
            //setBK(value1,value2,value3);
            jp.setBackground(new Color(value1,value2,value3));
        }
    if(e.getSource() == b2) 
        {
            if(value1 > 0)
            value1--; tf1.setText("" + value1);
            //setBK(value1,value2,value3);
            jp.setBackground(new Color(value1,value2,value3));
        }

1 个答案:

答案 0 :(得分:0)

您的actionPerformed方法未正确实现。请改用以下代码。

public void actionPerformed(ActionEvent e) {
    svalue1 = tf1.getText();
    value1 = Integer.parseInt(svalue1);

    if(e.getSource() == b1) {
        value1++;

        if(value1 >= 256) {
            value1 = 0;
        }
    }


     else if(e.getSource() == b2) {
        value1--;

        if (value1 < 0) {
            value1 = 0;
        }
     }

     tf1.setText("" + value1);
     jp.setBackground(new Color(value1, value2, value3));
}

希望这会有所帮助!