.setBounds不适用于JLabel和JButton

Jam*_*lin -1 java swing jlabel jbutton layout-manager

我试图在我的GUI上更改JLabel和JButton的位置.即使我尝试使用.setBounds来改变它们的位置; 它们都只出现在屏幕的顶部中央.

import java.awt.color.*;
import java.awt.font.*;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.UIManager.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class yo implements MouseListener {

Image image;
JButton button = new JButton("Wassup");
JFrame frame = new JFrame();
JLabel heloo = new JLabel("yo");
JPanel panel = new JPanel()
{
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        ImageIcon i = new ImageIcon("hi.jpg");
        image = i.getImage();
        g.drawImage(image,150,150,null);
        g.drawString("Hello",100,100);
        g.drawString("Hi",50,50);
    }
};


public yo()
{
    frame.add(panel);
    frame.setTitle("Hello");
    frame.setSize(500,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    panel.add(heloo);
    panel.add(button);
    button.setBounds(200,100,200,100);
    heloo.setBounds(100,100,100,100);
    button.addMouseListener(this);
}

public void mouseClicked (MouseEvent event)
{
    heloo.setText(String.format("Clicked at %d,%d", event.getX(), event.getY()));
}
public void mouseEntered (MouseEvent Event){}
public void mouseExited (MouseEvent Event){}
public void mousePressed (MouseEvent Event){}
public void mouseReleased (MouseEvent Event){}

public static void main(String[] args)
{
    new yo();
}
}
Run Code Online (Sandbox Code Playgroud)

我为所有的进口道歉,我真的不知道我需要哪些,哪些只是毫无意义.

基本上我想要一些关于如何改变组件定位的帮助.

cam*_*ckr 7

不要使用setBounds()来设置组件的大小和位置.

让布局管理器完成它的工作.这就是事实发生的事情.JPanel使用a FlowLayout,因此根据FlowLayout的规则定位组件.如果需要,可以更改FlowLayout以将组件对齐到左侧.或者您可以使用不同的布局管理器.

阅读布局管理器上的Swing教程,找到可以使用的其他布局管理器.

  • @JamesLoughlin,那不是你如何创建自定义GUI !! 绝对没有理由这样做.您可以使用许多不同的布局管理器在面板上定位两个组件.花时间学习优秀的编程实践和不错的编程实践. (4认同)