Java核心技术II-第6章-跟踪文本框中的修改-源代码
package javaee.vii.ch06;import javax.swing.JFrame;/** * * @author lcwell */public class ChangeTrackingTest { public static void main(String[] args) { JFrame frame = new ColorFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}
?
package javaee.vii.ch06;import java.awt.Color;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.event.DocumentEvent;import javax.swing.event.DocumentListener;/** * A frame with three text fields to set the background color. * * @author lcwell */public class ColorFrame extends JFrame { public ColorFrame() { setTitle("ChangeTrackingTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); DocumentListener listener = new DocumentListener() { @Override public void insertUpdate(DocumentEvent event) { setColor(); } @Override public void removeUpdate(DocumentEvent e) { setColor(); } @Override public void changedUpdate(DocumentEvent e) { } }; panel = new JPanel(); panel.add(new JLabel("Red:")); redField = new JTextField("255", 3); panel.add(redField); redField.getDocument().addDocumentListener(listener); panel.add(new JLabel("Green:")); greenField = new JTextField("255", 3); panel.add(greenField); greenField.getDocument().addDocumentListener(listener); panel.add(new JLabel("Blue:")); blueField = new JTextField("255", 3); panel.add(blueField); blueField.getDocument().addDocumentListener(listener); add(panel); pack(); } /** * Set the background color to the values stored in the text fields. */ public void setColor() { try { int red = Integer.parseInt(redField.getText().trim()); int green = Integer.parseInt(greenField.getText().trim()); int blue = Integer.parseInt(blueField.getText().trim()); panel.setBackground(new Color(red, green, blue)); } catch (NumberFormatException e) { } } private JPanel panel; private JTextField redField; private JTextField greenField; private JTextField blueField; private static final int DEFAULT_WIDTH = 220; private static final int DEFAULT_HEIGHT = 80;}
?运行效果:
?
?