我正在制作一个根据用户输入是或否使用react的窗口。我在这部分代码中遇到了问题:
public class Mywindow {
public static void main (String [] args){
windowcontinued object = new windowcontinued();
object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //ISSUE HERE
object.setSize(700, 1024); //ISSUE HERE
object.setVisible(true); //ISSUE HERE
}
}
这些简单的操作应该确保程序在关闭时终止、具有一定的大小并且可见。但由于某种原因,在所有三个操作中我都收到错误消息:
The method setDefaultCloseOperation(int) is undefined for the type windowcontinued
The method setSize(int, int) is undefined for the type windowcontinued
The method setVisible(boolean) is undefined for the type windowcontinued
尽管如此,所有这些都应该在导入后已经定义。完整代码如下:
主要代码:
package Myguipackage;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Mywindow {
public static void main (String [] args){
windowcontinued object = new windowcontinued();
object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object.setSize(700, 1024);
object.setVisible(true);
}
}
其他类:
package Myguipackage;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Windowcontinued{
public JLabel text;
public JTextField textfield;
public windowcontinued(){ //Constructor
/* super("CHAT");
setLayout(new FlowLayout()); */
text = new JLabel ("Would you like to talk to me?");
text.add(text);
textfield = new JTextField ("Yes or no? Erase this and type in your answer!");
}
class hear implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==textfield)
string = String.format("You typed in %s", event.getActionCommand());
JOptionPane.showMessageDialog(null, string); //Open a new window that displays String string, which has changed based on which field you hit enter on.
}
}
}
按照 fdsa 的建议使用 extends 关键字后,以下是新代码:
打包 Myguipackage;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class mywindow extends JFrame{
public static void main (String [] args){
windowcontinued object = new windowcontinued();
object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object.setSize(700, 1024);
object.setVisible(true);
}
}
尽管 Class windowcontinued 仍然相同。
最佳答案
正如其他发帖者所说,在命名类时请遵循 java 命名约定。它使您的代码更易于遵循。
您似乎对 import
语句的目的感到困惑。导入对象时,只能对该类型的对象使用其方法。如果您希望您的类模仿现有类的功能,则需要扩展
原始类,而不仅仅是导入
它。
关于java - java中的对象有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31997252/