有人可以指导我如何将这两个类合并到一个文件中?一个是构造函数类,另一个是main。
感谢;
主类:
public class JHelloDemo
{
public static void main(String[] args)
{
JHelloFrame frame = new JHelloFrame();
frame.setVisible(true);
}
}
构造函数类:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHelloFrame extends JFrame implements ActionListener{
JLabel question = new JLabel("What is your name?");
Font bigFont = new Font("Arial", Font.BOLD, 16);
JTextField answer = new JTextField(10);
JButton pressMe = new JButton("Press me");
JLabel greeting = new JLabel("");
final int WIDTH = 275;
final int HEIGHT = 225;
public JHelloFrame(){
super("Hello Frame");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
question.setFont(bigFont);
greeting.setFont(bigFont);
add(question);
add(answer);
add(pressMe);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pressMe.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
String name = answer.getText();
String greet = "Hello, " + name;
greeting.setText(greet);
}
}
答案 0 :(得分:0)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHelloFrame extends JFrame implements ActionListener{
JLabel question = new JLabel("What is your name?");
Font bigFont = new Font("Arial", Font.BOLD, 16);
JTextField answer = new JTextField(10);
JButton pressMe = new JButton("Press me");
JLabel greeting = new JLabel("");
final int WIDTH = 275;
final int HEIGHT = 225;
public JHelloFrame(){
super("Hello Frame");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
question.setFont(bigFont);
greeting.setFont(bigFont);
add(question);
add(answer);
add(pressMe);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pressMe.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
String name = answer.getText();
String greet = "Hello, " + name;
greeting.setText(greet);
}
public static void main(String[] args)
{
JHelloFrame frame = new JHelloFrame();
frame.setVisible(true);
}
}
你去了
答案 1 :(得分:0)
您可以简单地将main()方法移动到JHelloFrame,这是您问题的答案。但是,您现有的设计将问题分开,所以我会不管它。
顺便说一下,你应该在Runnable中包装frame.setVisible(true)并将它传递给EventQueue.invokeLater()。有关详细说明,请参阅this question。