「已注销」 2011-10-10 13:28
浏览 556
已采纳

Swing JPanel重绘 如何控制按钮位置

import java.awt.Graphics;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LayerTest {

public static void main(String[]args){
    JFrame jf = new JFrame("JPANEL 分层");
    jf.setBounds(100, 100, 500, 280);


    JPanel jp = new JPanel(){
        @Override
        protected void paintComponent(Graphics g) {
            // TODO Auto-generated method stub
            super.paintComponent(g);
            URL imgURL = getClass().getResource("/images/login.jpg");
            ImageIcon icon=new ImageIcon(imgURL);
            g.drawImage(icon.getImage(),0,0,getSize().width,getSize().height,this);
        }
    };
    JButton btn = new JButton("Test");
    btn.setLocation(100, 180); [color=red]//按钮位置设置无效,显示在顶部居中[/color] 
         jp.setOpaque(true);
         jp.add(btn);
    jf.getContentPane().add(jp);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    jf.setVisible(true);
}

}

  • 写回答

1条回答 默认 最新

  • fxmabo 2011-10-10 13:49
    关注

    给你的JPanel加一个布局,如:jp.setLayout(new GridBagLayout());
    然后你就可以按照你自己的布局去调整。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题