public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g ; 
        Paint oldPaint = g2.getPaint() ; 
        if(isEntered){
        if (getModel().isArmed()) {
            g2.setColor(bacClick);

        } else
            g2.setColor(bacNormal);


        GradientPaint p = new GradientPaint(0,0,
                new Color(0xFFFFFF), 0, 2, bacNormal);
        g2.setPaint(p) ; 
        g2.fillRoundRect(0, 0, getWidth()- 1, getHeight() /2+10, 5, 5);
        GradientPaint pInigel = new GradientPaint(0,getHeight()/2-10,bacNormal,0,getHeight(),new Color(0xFFFFFF)) ; 
        g2.setPaint(pInigel) ; 
        g2.fillRoundRect(0, getHeight()/2-5, getWidth()- 1, getHeight(), 5, 5);
        }
        g2.setFont(new Font("方正舒体", 0, 30));
        if (getModel().isArmed()) {
            g2.setColor(bacNormal);

        } else
            if(isEntered)
                g2.setColor(Color.YELLOW) ; 
            else
            g2.setColor(foreGround);

        g2.drawString(text,1, getHeight()/ 2 + 9);
        g2.setPaint(oldPaint) ; 
        super.paintComponent(g);
    }

初学java,里面很多都是照着网上写的。单独加入到JFrame是显示正常,可是一加入到JPanel中背景只能显示左上部分,文字显示正常


1个回答

需要设置JPanel的布局。

修改的main函数

public static void main(String[] args) {
    JFrame jfm = new JFrame("");
    jfm.setSize(200, 200);
    jfm.setLocation(new Point(400, 400));
    JPanel jp = new JPanel();
    jp.setLayout(new GridLayout());
    XJButton x = new XJButton("尝试");
    x.setOpaque(false);
    jp.add(x);

    jfm.getContentPane().add(jp);

    jfm.setVisible(true);
    jfm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}