public class Main {
public static void main(String[]args) {
Window window = new Window();
window.initializeFrame();
PanelPhone panelPhone = new PanelPhone();
panelPhone.initializePanelPhone();
window.add(panelPhone);
}
}
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.*;
public class PanelPhone extends JPanel {
JPanel panel;
public PanelPhone() {
panel = new JPanel();
panel.setVisible(true);
}
void initializePanelPhone() {
panel.setLayout(null);
panel.setBorder(new EtchedBorder());
panel.setBackground(Color.GRAY);
panel.setLocation(20, 20);
panel.setSize(300,200);
add(panel);
}
}
import javax.swing.*;
import java.awt.*;
public class Window extends Frame {
private JFrame frame;
public Window(){
frame = new JFrame("Phone");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void initializeFrame() {
frame.setSize(new Dimension(1000 ,900));
frame.setLocationRelativeTo(null);
frame.setLayout(null);
}
}
问题是面板在接收参数之前显示 - 即 您正在显示一个没有背景、没有尺寸的空面板
它是如何工作的(运行):
ps 在我看来,没有必要在已经从必要组件继承的类中创建额外的对象,并将设置写入构造函数,但这更多的是建议而不是修复 - 错误恰好在于调用顺序