小弟做作业又有问题啦
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);
}
}
以上,显示一个简单的界面:
点击"Left", "Center", "Right"时对应更改上方的JTextField (在code中叫做"jtfMessage") 的Alignment,功能正常。
在"Column Size"那个JTextField里打个数值按回车把上方的JTextField的column更改为对应的值,结果按了回车没反应。试过ActionListener添加的没错,反正就是ActionListener中的那句statement不起作用,百思不得其解,求解答!
------解决方案--------------------
JTextField? 不能响应ActionListener这个事件,这个算是高级事件能响应的不多。你要添加键盘事件才会有效果地。
------解决方案--------------------