[英]One class calling another's method
为了整理我的(非常基本的)UI 代码,我将按钮和文本字段拆分为两个单独的类,其中一个主要用于创建框架并运行。 该按钮需要在单击时影响文本字段的内容,所以我使用了mouseEvent
。 但是,我不能调用我的文本字段的方法,因为文本字段 object 存储在 main 中,所以没有 object 可以使用方法。 所有方法都是公共的,所有属性都是私有的。 所有的帮助都是apprciated,谢谢。
我尝试将 object 设为public statiic
无济于事,我不确定我是否在这里遗漏了一些明显的东西。
Fpor上下文, mouseEvent
需要从文本字段object调用rename(String)
方法,称为tf,在class gui1中
编辑:
(主要的)
public interface gui1{
public static void main(String[] args) {
textfieldobj tf = new textfieldobj("You should press button 1",100,100, 150,20);
buttonObject b = new buttonObject("new button!");
(在 buttonObject 类中)
public class buttonObject extends JButton implements{
JButton b;
public buttonObject(String text){
JButton b=new JButton(text);
b.setBounds(100,100,60,60);
b.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
tf.setText("You Did It");//problem area
b.setEnabled(false);
(在文本字段类中)
public void setText(String newtext) {
text = newtext;
super.setText(newtext);
}
textfieldobj
buttonObject
你为什么要重新发明所有这些轮子? JTextField
和JButton
是表示文本字段和按钮的类,您不需要围绕这些进行无操作包装。
按钮单击时需要影响文本字段的内容
那是糟糕的设计; 您不希望您的按钮需要了解文本字段; 如果是这样,除了修改该确切的文本字段外,无法使用所述按钮进行任何操作。
所以我使用了mouseEvent。
是的,这就是要使用的东西。 但是,只需.. 在知道按钮和字段的地方添加侦听器。 这可能是主要的,但这让我们想到了另一点:
public static void main(...
这不是写代码的地方。 制作一个 object,在上面调用一些 'go' 方法,这就是你的 main 应该有的一行。 您想尽快摆脱static
,您就是这样做的。
所以,像:
public class MainApp {
// frames, layout managers, whatever you need as well
private final JButton switchTextButton;
private final JTextField textField;
public MainApp() {
this.switchTextButton = new JButton("Switch it up!");
this.textField = new JTextField();
// add a panel, add these gui elements to it, etc.
setupListeners();
}
private void setupListeners() {
// hey, we have both the button and the textfield in scope here.
switchTextButton.addActionListener(evt -> {
textField.setText("Hello!");
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.