java - JLabel,如何设置坐标
问题描述
我想通过在特定位置使用坐标来放置 JLabel。但相反,标签出现在我的窗口顶部的中间。请告诉我我做错了什么。
类 PaintPanel 扩展 JPanel {
private Color color = Color.RED;
private GeneralPath path;
Graphics2D graphics2D;
ArrayList<PathToDraw> generalPathToDraws;
public PaintPanel() {
path = new GeneralPath();
ArrayList<Object> generalPathToDraws = new ArrayList<>();
//path.moveTo(564, 278);
}
//add multiplay general pathes to drowing
public void addMultiplayPathesAndDrowThem(ArrayList<PathToDraw> ptd){
generalPathToDraws = ptd;
updateGraphics();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
graphics2D = (Graphics2D) g;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
JLabel A_label = new JLabel("B");
A_label.setLocation(300, 300);
A_label.setForeground(Color.red);
add(A_label);
解决方案
如果你想使用“setLocation”,你的面板布局应该是“null”
public static class MainPanel extends JPanel{
public MainPanel() {
this.setLayout(null);
JLabel A_label = new JLabel("B");
A_label.setBounds(100, 100, 10, 10);//set location & size
//Or
//A_label.setSize(10, 10);
//A_label.setLocation(100, 100);
A_label.setForeground(Color.red);
this.add(A_label);
}
}
推荐阅读
- bash - 在bash中生成一定范围内的mac地址
- database - 使用多台机器制造的零件的关系数据库
- c - 将第一个字符更改为大写
- linux - 数据版本控制 (DVC) 命令不起作用 ---> TypeError: public() got an unexpected keyword argument 'SEP'
- heroku - 在同一个 Procfile 上运行两个程序
- javascript - 将对象数组与 ES6 中的对象进行比较
- python - Pydantic:使用文字验证有区别的联合
- android - 尝试从空对象引用上的字段 'androidx.fragment.app.FragmentManager androidx.fragment.app.Fragment.mFragmentManager' 读取)
- php - 自动配置替换导入的服务
- sql - 当生成选择语句时,它给我奇怪的文本作为 > 选择数据时?