再在上面窗口中间,放入一个登录注册面板,请用代码呈现
时间: 2024-03-13 11:48:11 浏览: 19
好的,以下是在 GameWin 窗口中间添加登录注册面板的代码:
```java
package xjdz;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
public class GameWin extends JFrame {
public GameWin() {
initWindow();
initLoginPanel(); // 添加登录面板
}
/**
* 初始化窗口
*/
private void initWindow() {
this.setSize(999, 666);
this.setTitle("oqcw星际大战仿飞机大战小游戏");
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口背景
JLayeredPane layeredPane = new JLayeredPane();
setContentPane(layeredPane);
// 添加背景图片
JLabel backgroundImageLabel = new JLabel(getBackgroundImageIcon());
backgroundImageLabel.setBounds(0, 0, getWidth(), getHeight());
layeredPane.add(backgroundImageLabel, new Integer(0));
}
/**
* 获取背景图片
*/
private ImageIcon getBackgroundImageIcon() {
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("bg.jpg");
byte[] bytes = new byte[is.available()];
is.read(bytes);
is.close();
return new ImageIcon(bytes);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 启动窗口
*/
public void launch() {
this.setVisible(true);
}
/**
* 初始化登录面板
*/
private void initLoginPanel() {
// 创建登录面板
JPanel loginPanel = new JPanel();
loginPanel.setBounds(200, 200, 600, 300);
loginPanel.setBackground(Color.WHITE);
loginPanel.setLayout(new GridLayout(3, 2));
// 添加组件到登录面板
JLabel usernameLabel = new JLabel("用户名:");
JTextField usernameTextField = new JTextField();
JLabel passwordLabel = new JLabel("密 码:");
JPasswordField passwordField = new JPasswordField();
JButton loginButton = new JButton("登录");
JButton registerButton = new JButton("注册");
loginPanel.add(usernameLabel);
loginPanel.add(usernameTextField);
loginPanel.add(passwordLabel);
loginPanel.add(passwordField);
loginPanel.add(loginButton);
loginPanel.add(registerButton);
// 将登录面板添加到窗口中间
Container contentPane = getContentPane();
contentPane.add(loginPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
GameWin gameWin = new GameWin();
gameWin.launch();
}
/**
* 程序退出时释放资源
*/
@Override
public void dispose() {
super.dispose();
System.gc();
}
}
```
这个代码中,我们在 GameWin 构造方法中添加了一个 initLoginPanel() 方法,用于初始化登录注册面板。这个方法中,我们首先创建了一个 JPanel,设置了其大小、背景颜色、布局为 GridLayout,并添加了用户名、密码、登录和注册的组件。最后,我们将这个登录面板添加到窗口中间。