java component创建_用Java创建一个简单的自定义JComponent?

我想开始为工作中的项目构建自己的自定义JComponent.我在下面有一个简单的例子,它应该只是在屏幕上创建一个球. (我在互联网上发现了大部分内容),但确实提供了一个不错的起点.我的问题是为什么这段代码不能以我的形式显示球?我做错了什么?

那么应该为自定义JComponent提供的所有基本方法是什么?

码:

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.GridBagLayout;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class testBall {

public static void main(String[] args) {

new testBall();

}

public testBall() {

JPanel testPane = new JPanel();

testPane.setBackground(Color.white);

testPane.setLayout(new GridBagLayout());

testPane.add(new MyBall(30,30,10));

JFrame frame = new JFrame("Testing");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new BorderLayout());

frame.add(testPane);

frame.pack();

frame.setSize(500, 300);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

}

class MyBall extends JComponent

{

private static final long serialVersionUID = 1L;

public MyBall() { }

public MyBall(int x, int y, int diameter)

{

super();

this.setLocation(x, y);

this.setSize(diameter, diameter);

}

public void paintComponent(Graphics g)

{

super.paintComponent(g);

g.setColor(Color.red);

g.fillOval(0, 0, 100, 100);

}

}

在哪里可以找到应该在JComponent类中重写的所有方法的列表? (我知道有些应该总是包含在JComponent中.)

如果我在一个类中创建这个组件的实例并且需要更改圆的颜色,那么我只是从那个类中调用repaint()方法吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值