jLabel.setBounds(400, 200, 300, 300);,怎么将图片一直处于GUI中央?
时间: 2024-04-03 17:32:27 浏览: 16
你可以使用布局管理器来实现将组件始终放置在 GUI 的中央位置。
以下是使用 BorderLayout 布局管理器将标签组件放置在 GUI 中央的代码示例:
```java
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JLabel label = new JLabel(new ImageIcon("image.png"));
frame.add(label, BorderLayout.CENTER);
frame.setVisible(true);
}
}
```
在代码中,使用 BorderLayout 布局管理器将标签组件添加到 JFrame 中。由于 BorderLayout 布局管理器中添加到 CENTER 位置的组件会始终处于中央位置,因此标签组件会始终放置在 GUI 的中央位置。
相关问题
JLabel jLabel = new JLabel(new ImageIcon("C:\\Users\\59808\\IdeaProjects\\first\\exercise\\src\\image\\image.jpg")); jLabel.setBounds(400, 200, 300, 300);//+放在正中间 this.getContentPane().add(jLabel);可逆改成放在中心
你可以使用布局管理器来实现将标签组件始终放置在 GUI 的中心位置。
以下是使用 GridBagLayout 布局管理器将标签组件放置在 GUI 中央的代码示例:
```java
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JLabel label = new JLabel(new ImageIcon("C:\\Users\\59808\\IdeaProjects\\first\\exercise\\src\\image\\image.jpg"));
GridBagLayout layout = new GridBagLayout();
frame.setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.CENTER;
frame.add(label, constraints);
frame.setVisible(true);
}
}
```
在代码中,使用 GridBagLayout 布局管理器将标签组件添加到 JFrame 中,并设置 GridBagConstraints 的属性将组件放置在中心位置。由于 GridBagLayout 布局管理器可以自由设置组件的位置和大小,因此可以更灵活地实现组件的布局。
public RegisterReaders() { setTitle("注册界面"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(WINDOW_WIDTH, WINDOW_HEIGHT); setResizable(false); setLocationRelativeTo(null); setLayout(null); JLabel lblID = new JLabel("读者ID: "); tfID = new JTextField(15); JLabel lblName = new JLabel("读者名称: "); tfName = new JTextField(15); JLabel lblPassword = new JLabel("读者密码: "); pfPassword = new JPasswordField(15); btnRegister = new JButton("注册"); btnReturn = new JButton("去登录"); lblID.setBounds(10, 10, 80, 20); tfID.setBounds(100, 10, 180, 20); lblName.setBounds(10, 40, 80, 20); tfName.setBounds(100, 40, 180, 20); lblPassword.setBounds(10, 70, 80, 20); pfPassword.setBounds(100, 70, 180, 20); btnRegister.setBounds(100, 110, 80, 25); btnReturn.setBounds(190, 110, 90, 25); add(lblID); add(tfID); add(lblName); add(tfName); add(lblPassword); add(pfPassword); add(btnRegister); add(btnReturn);
这段代码看起来像是 Java Swing GUI 界面的代码,是用来设计一个读者注册界面的。其中包括了读者的 ID,名称和密码的输入框,以及注册和返回登录界面的按钮。这段代码还设置了窗口的标题,大小,位置居中,并且不能改变大小。整个界面使用的是绝对布局,通过 setBounds 方法设置组件在窗口中的位置和大小。