📄 vetoablechangedemo.java
字号:
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class VetoableChangeDemo extends JFrame implements ItemListener{ NewLabel2 label1, label2, label3; FontColor2 fontColor; JComboBox jcb; public VetoableChangeDemo() {/* A FontColor2 object is created. This object maintains a Color *//* object as a constrained property. */ fontColor = new FontColor2(Color.black, this);/* Three NewLabel objects are created and placed on a JFrame. The *//* NewLabel class is a JLabel that uses a FontColor object to set *//* the color of the label text. */ label1 = new NewLabel2("hello", fontColor); label1.setFont(new Font("Serif", Font.BOLD, 14)); label2 = new NewLabel2("there", fontColor); label2.setFont(new Font("Serif", Font.BOLD, 14)); label3 = new NewLabel2("boys", fontColor); label3.setFont(new Font("Serif", Font.BOLD, 14));/* A JComboBox is used to change the color of the NewLabel object text *//* The JComboBox registers an ItemListener. */ String[] colorList = {"black", "red", "blue", "green"}; jcb = new JComboBox(colorList); jcb.setSelectedIndex(0); jcb.addItemListener(this); JPanel centerPanel = new JPanel(); centerPanel.add(label1); centerPanel.add(label2); centerPanel.add(label3); JPanel southPanel = new JPanel(); southPanel.add(jcb); getContentPane().add(centerPanel, BorderLayout.CENTER); getContentPane().add(southPanel, BorderLayout.WEST); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 300, 200); setVisible(true); }/* Since the VetoableChangeDemo class serves as the ItemListener, *//* it provides an implementation of the itemStateChanged() method. *//* The FontColor2 object calls its setColor() method passing it the *//* selected color. */ public void itemStateChanged(ItemEvent event) { JComboBox comboBox = (JComboBox)event.getItemSelectable(); String color = (String)comboBox.getSelectedItem(); if ( color.equals("black") ) fontColor.setColor(Color.black); if ( color.equals("red") ) fontColor.setColor(Color.red); if ( color.equals("blue") ) fontColor.setColor(Color.blue); if ( color.equals("green") ) fontColor.setColor(Color.green); /* If the color change is vetoed, the label text color is reset to *//* its previous value. This next block of code insures that the *//* current selection of the JComboBox will be reset as well. */ Color c = fontColor.getColor(); if ( c.equals(Color.black) ) comboBox.setSelectedIndex(0); if ( c.equals(Color.red) ) comboBox.setSelectedIndex(1); if ( c.equals(Color.blue) ) comboBox.setSelectedIndex(2); if ( c.equals(Color.green) ) comboBox.setSelectedIndex(3); } public static void main(String args[]) { VetoableChangeDemo demo = new VetoableChangeDemo(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -