我有两个不同的类(mainClass
)和(visual
)。在可视类中,我有一个方法,在方法内,我将所需的代码放入了简单的JButton
中。在主类中,我创建了一个对象以从可视类中调用方法,以在主类中显示按钮。但这行不通。我将不胜感激。
package init;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
public class mainClass {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainClass window = new mainClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainClass() {
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);
In the code below I made an object and called the method from the visual class
visual bt = new visual();
bt.btn();
}
}
//////////////// VISUAL CLASS ///////////////////////
package init;
import javax.swing.JButton;
import javax.swing.JFrame;
public class visual {
public JFrame frame;
public void btn() {
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(141, 155, 151, 45);
frame.getContentPane().add(btnNewButton);
}
}
答案 0 :(得分:0)
对于您要在此处实现的目标,您不需要2个课程。您可以这样做:
import javax.swing.*;
import java.awt.*;
public class MainClass {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnNewButton = new JButton("New button");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(btnNewButton);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}