所以我对于如何从其他组件访问其他屏幕组件/变量(我不知道该怎么称呼它们,但是文本框,按钮等等)并不感到困惑#&# 39; s mouseClicked方法。例如,让我们说一旦点击了一个按钮,就会禁用另一个按钮。我的意思是,在这个简单的计算器示例中(带有两个文本框和一个加减按钮),它完全没有意义,但我只是想了解这个概念。使用其他编程语言,你可以直接访问它们但是使用java,我不确定......无论如何,这里是相关的代码:
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int num1 = Integer.parseInt(textField.getText().toString());
int num2 = Integer.parseInt(textField_1.getText().toString());
int total = num1 + num2;
btnSubtract.setEnabled(false);
JOptionPane.showMessageDialog(null, total);
}
});
JButton btnSubtract = new JButton("Subtract");
btnSubtract.setBounds(144, 124, 89, 23);
frame.getContentPane().add(btnSubtract);
}
}
或者,如果我需要编辑其他内容,这里也是所有自动生成的代码:
public class SimpleCalcApp {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimpleCalcApp window = new SimpleCalcApp();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SimpleCalcApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(147, 27, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(147, 59, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int num1 = Integer.parseInt(textField.getText().toString());
int num2 = Integer.parseInt(textField_1.getText().toString());
int total = num1 + num2;
btnSubtract.setEnabled(false);
JOptionPane.showMessageDialog(null, total);
}
});
btnAdd.setBounds(144, 90, 89, 23);
frame.getContentPane().add(btnAdd);
JButton btnSubtract = new JButton("Subtract");
btnSubtract.setBounds(144, 124, 89, 23);
frame.getContentPane().add(btnSubtract);
}
}
我希望这只是一个简单的解决方案,但谁知道,对于像我这样的新手来说,Java似乎相当抽象。无论如何,感谢先进的任何答案家伙:)
答案 0 :(得分:1)
您只需访问它。不要忘记创建字段final
,因为您是从匿名类中访问它。
JButton btnAdd = new JButton("Add");
final JButton btnSubtract = new JButton("Subtract");
btnAdd.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int num1 = Integer.parseInt(textField.getText().toString());
int num2 = Integer.parseInt(textField_1.getText().toString());
int total = num1 + num2;
btnSubtract.setEnabled(false);
JOptionPane.showMessageDialog(null, total);
}
});
btnAdd.setBounds(144, 90, 89, 23);
btnSubtract.setBounds(144, 124, 89, 23);
frame.getContentPane().add(btnAdd);
frame.getContentPane().add(btnSubtract);