[英]Creating custom components in Java AWT
I am trying to create a custom component using Java AWT or Swing which will be a rectangle with a number of components inside of it, including other rectangles. 我正在尝试使用Java AWT或Swing创建一个自定义组件,该组件将是一个矩形,其中包含许多组件,包括其他矩形。 Something like this:
像这样:
╔══════╗
║ ┌┐ ║
║ ├┘ ║
║ ║
╚══════╝
And this needs to be a component that I can preferably draw with one instruction. 这需要成为我最好可以用一条指令绘制的组件。 Something like
myFrame.add(new MyComponent())
. 类似于
myFrame.add(new MyComponent())
。
What would you say is the best way to do this? 您说什么是最好的方法? Is there a way I can do this using
Rectangle
, or should I go with JPanel
or something from Swing? 有什么方法可以使用
Rectangle
做到这一点,还是应该使用JPanel
或Swing的东西?
"a number of components" -> JPanel with a layout manager to place each component “大量组件”->具有布局管理器的JPanel来放置每个组件
"draw" -> override paint on component “绘制”->覆盖组件上的绘制
Check the Java Tutorial Swing section. 检查Java Tutorial Swing部分。
I would recomend extending a JPanel
and overriding it's paintComponent()
method. 我建议扩展一个
JPanel
并覆盖它的paintComponent()
方法。 See another answer of mine for some help on that. 请参阅我的另一个答案,以寻求帮助。
Basically, when a rectangle is 'drawn' on your panel, you will want to save it as a member of the Jpanel
. 基本上,当在面板上“绘制”矩形时,您将需要将其保存为
Jpanel
的成员。 Then, in the paintComponent
method, you will just draw all of the rectangles you have saved in your JPanel
. 然后,在
paintComponent
方法中,将只绘制已保存在JPanel
所有矩形。
This is how I would implement a 'draw' method: 这就是我实现“绘制”方法的方式:
List<Rectangle> recs;
List<Stroke> strokes;
List<Color> colors;
public void drawRectangle(Rectangle newR, Stroke stroke, Color c){
recs.add(newR);
strokes.add(stroke);
colors.add(c);
}
And, the paint component will look similar to: 并且,绘画组件将类似于:
protected void paintComponent(Graphics g){
super.paintComponent(g);
for (int i = 0; i < recs.size(); i ++) {
g.setColor(colors.get(i));
g.setStroke(strokes.get(i));
g.drawRectangle(recs);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.