.setBounds不适用于JLabel和JButton [英] .setBounds not working for JLabel and JButton
问题描述
我正在尝试在GUI上更改JLabel和JButton的位置。即使我尝试使用.setBounds来改变它们的位置;它们都只出现在屏幕的顶部中央。
I am trying to change the positioning of a JLabel and a JButton on my GUI. Even though I try to use .setBounds to change their locations; they both just appear in the top centre of the screen.
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();
}
}
我为所有进口产品道歉,我不知道我真的知道哪些是我需要的,哪些是没有意义的。
I apologise about all of the imports, I don't really know which ones I need and which ones are just pointless.
基本上我想要一些关于如何改变我的组件定位的帮助。
Basically I would like some help on how to change the positioning of my components.
推荐答案
不要使用setBounds()来设置组件的大小和位置。
Don't use setBounds() to set the size and location of a component.
让布局管理器完成它的工作。这就是事实正在发生的事情。 JPanel使用 FlowLayout
,因此根据FlowLayout的规则定位组件。如果需要,可以更改FlowLayout以将组件对齐到左侧。或者您可以使用不同的布局管理器。
Let the layout manager do its job. That is if fact what is happening. A JPanel uses a FlowLayout
, so the components are being positioned based on the rules of the FlowLayout. You can change the FlowLayout to align components to the left if you want. Or you can use a different layout manager.
阅读布局管理器,以查找您可以使用的其他布局管理器。
Read the Swing tutorial on Layout Managers to find other layout managers you can use.
这篇关于.setBounds不适用于JLabel和JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!