日期:2014-05-20 浏览次数:20795 次
public class EX11 extends JFrame {
private JTextField jtfMessage = new JTextField("Type anything", 30);
private JRadioButton jrbLeft = new JRadioButton("Left");
private JRadioButton jrbCenter = new JRadioButton("Center");
private JRadioButton jrbRight = new JRadioButton("Right");
private JTextField jtfColumnSize = new JTextField("30", 10);
private Listener listener = new Listener();
private TextFieldListener textFieldListener = new TextFieldListener();
public EX11() {
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
p1.add(new JLabel("Text field"));
p1.add(jtfMessage);
jtfMessage.setHorizontalAlignment(JTextField.CENTER);
add(p1);
JPanel p2 = new JPanel(new GridLayout(1, 3, 5, 5));
p2.add(jrbLeft);
p2.add(jrbCenter);
p2.add(jrbRight);
ButtonGroup group = new ButtonGroup();
group.add(jrbLeft);
group.add(jrbCenter);
group.add(jrbRight);
jrbLeft.addItemListener(listener);
jrbCenter.addItemListener(listener);
jrbRight.addItemListener(listener);
jrbCenter.setSelected(true);
p2.setBorder(new TitledBorder("Horizontal Alignment"));
JPanel p3 = new JPanel(new GridLayout(1, 2, 5, 5));
p3.setBorder(new LineBorder(Color.black));
p3.add(new JLabel("Column Size"));
p3.add(jtfColumnSize);
jtfColumnSize.addActionListener(textFieldListener);
JPanel p4 = new JPanel(new GridLayout(1, 2, 5, 5));
p4.add(p2);
p4.add(p3);
add(p4, BorderLayout.SOUTH);
}
private class Listener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
if (jrbLeft.isSelected())
jtfMessage.setHorizontalAlignment(JTextField.LEFT);
else if (jrbCenter.isSelected())
jtfMessage.setHorizontalAlignment(JTextField.CENTER);
else if (jrbRight.isSelected())
jtfMessage.setHorizontalAlignment(JTextField.RIGHT);
}
}
private class TextFieldListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
jtfMessage.setColumns(Integer.parseInt(jtfColumnSize.getText()));
}
}
public static void main(String[] args) {
EX11 frame = new EX11();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}