我是Event Listeners的新手。我找到了这个练习。我的目标是使用用户输入更改BorderLayout
。我尝试使用DocumentListener
和ActionListener
,但我无法使其正常运行。这是我可以编码的内容:
public class Eventlistenertest extends JFrame {
public Eventlistenertest(){
JPanel p1 = new JPanel(new BorderLayout(i, j)); // here is i and j.
p1.add(new JButton("East"), BorderLayout.EAST);
p1.add(new JButton("South"), BorderLayout.SOUTH);
p1.add(new JButton("West"), BorderLayout.WEST);
p1.add(new JButton("North"), BorderLayout.NORTH);
p1.add(new JButton("Center"), BorderLayout.CENTER);
p1.setBorder(new TitledBorder("Container of BorderLayout"));
JTextField VGap = new JTextField(35);
JTextField HGap = new JTextField(35);
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 20));
p2.add(new JLabel("HGap"));
p2.add(HGap);
p2.add(new JLabel("VGap"));
p2.add(VGap);
p2.setBorder(new TitledBorder("BorderLayout Properties"));
setLayout(new GridLayout(2, 1, 5, 5));
add(p1);
add(p2);
int i =Integer.parseInt(HGap.getText());
int j =Integer.parseInt(VGap.getText());
}
/** Main method */
public static void main(String[] args) {
Eventlistenertest frame = new Eventlistenertest();
frame.setTitle("ShowBorderLayout");
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
我需要在开始时将i
和j
设为零,并在JTextField
输入后更改它们。我怎么能这样做?
答案 0 :(得分:2)
首先看看How to Use Text Fields和How to Write an Action Listeners
基本上,一种方法是在字段中添加ActionListener
,当用户按 Enter 时,向上布局
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int vgap = 0;
int hgap = 0;
if (VGap.getText().trim().length() > 0) {
try {
vgap = Integer.parseInt(VGap.getText());
} catch (NumberFormatException exp) {
System.out.println("Invalid number for vgap");
}
}
if (HGap.getText().trim().length() > 0) {
try {
hgap = Integer.parseInt(HGap.getText());
} catch (NumberFormatException exp) {
System.out.println("Invalid number for vgap");
}
}
borderLayout.setHgap(hgap);
borderLayout.setVgap(vgap);
p1.revalidate();
}
};
VGap.addActionListener(listener);
HGap.addActionListener(listener);
有一个要求,您首先应用于BorderLayout
的{{1}}实例必须与您更新的实例相同。
你可以使用p1
,但这个过程会变得复杂得多