Java 点击按钮
Java Clicking Buttons
如何告诉我的动作侦听器单击按钮并将按钮文本显示到文本区域?
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() instanceof JButton) {
String text = e.getActionCommand();
JOptionPane.showMessageDialog(null, text);
}
}
};
JTextArea area
在 actionlistener 之后初始化,所以当我尝试定义 area.
时它给我一个错误。你能帮帮我吗?
How do I tell my action listener to click a button
对于 "click" 按钮,您只需调用该按钮的 doClick()
方法。
来自JavaDoc:
public void doClick()
Programmatically perform a "click". This does the same thing as if the user had pressed and released the button.
如果您的按钮是全局的,您可以简单地调用如下方法:
someButton.doClick();
如果它们不是全局的,您将需要以某种方式获取对按钮的引用:
someContainer.getSomeButton().doClick();
你问题的第二部分问:
The JTextArea area is initialized after the actionlistener and so when i try to define area
. it give me an error.
您可以尝试检查 JTextArea
是否已经初始化,如果没有,请在此时进行初始化。类似于:
if (area == null) {
area = new JTextArea();
// do the rest of your initialization and placement in the UI
}
// continue with writing text into the `area` and your other program logic
area.append(myText);
// etc...
为了让按钮调用 actionPerformed()
方法,您需要将 actionListener
的实例添加到按钮。
button.addActionListener(listener);
如何告诉我的动作侦听器单击按钮并将按钮文本显示到文本区域?
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() instanceof JButton) {
String text = e.getActionCommand();
JOptionPane.showMessageDialog(null, text);
}
}
};
JTextArea area
在 actionlistener 之后初始化,所以当我尝试定义 area.
时它给我一个错误。你能帮帮我吗?
How do I tell my action listener to click a button
对于 "click" 按钮,您只需调用该按钮的 doClick()
方法。
来自JavaDoc:
public void doClick()
Programmatically perform a "click". This does the same thing as if the user had pressed and released the button.
如果您的按钮是全局的,您可以简单地调用如下方法:
someButton.doClick();
如果它们不是全局的,您将需要以某种方式获取对按钮的引用:
someContainer.getSomeButton().doClick();
你问题的第二部分问:
The JTextArea area is initialized after the actionlistener and so when i try to define
area
. it give me an error.
您可以尝试检查 JTextArea
是否已经初始化,如果没有,请在此时进行初始化。类似于:
if (area == null) {
area = new JTextArea();
// do the rest of your initialization and placement in the UI
}
// continue with writing text into the `area` and your other program logic
area.append(myText);
// etc...
为了让按钮调用 actionPerformed()
方法,您需要将 actionListener
的实例添加到按钮。
button.addActionListener(listener);