For my assignment, I need to make an application where I can increment or decrement the value in the JTextField
and the color will change on the lower panel. The text field is editable so whenever any of the values in the top panel's text box changes, the lower panel's background color will immediately update to match it. However, I am having trouble with that.
I'm also having trouble limiting the entered input to values outside of 0 and 256 to be treated as zero.
Is there any pointers?
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));
}