[英]repaint method for Jcomponents draws a white rectangle when I use setBounds
[英]How do I modify the setBounds method for JComponents?
我希望创建一种可以帮助我加快GUI设计速度的方法。 我使用setBounds
时间最长。 现在,我会选择FlowLayout或GridLayout,但我不喜欢依赖它们。
基本上,我正在考虑像placeAbove
这样的方法,它将JComponent置于另一个JComponent之上。 它的参数将是参考点JComponent和它们彼此距离的整数。 我目前在以下方面取得了成功:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BoundBender extends JFrame {
public BoundBender() {
Container c = getContentPane();
c.setLayout(null);
JLabel l1 = new JLabel("Reference Point");
JLabel l2 = new JLabel("Above Label");
JLabel l3 = new JLabel("Below Label");
JLabel l4 = new JLabel("Before Label");
JLabel l5 = new JLabel("After Label");
c.add(l1);
l1.setBounds(170, 170, 100, 20);
c.add(l2);
placeAbove(l1, 0, l2);
c.add(l3);
placeBelow(l1, 10, l3);
c.add(l4);
placeBefore(l1, 20, l4);
c.add(l5);
placeAfter(l1, 30, l5);
setVisible(true);
setSize(500, 500);
}
public static void main (String args[]) {
BoundBender bb = new BoundBender();
bb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void placeAbove(JComponent j, int a, JComponent k) {
int x= j.getX();
int y= j.getY();
int w= j.getWidth();
int h= j.getHeight();
y=(y-h)-a;
k.setBounds(x, y, w, h);
}
public static void placeBelow(JComponent j, int a, JComponent k) {
int x= j.getX();
int y= j.getY();
int w= j.getWidth();
int h= j.getHeight();
y=y+h+a;
k.setBounds(x, y, w, h);
}
public static void placeBefore(JComponent j, int a, JComponent k) {
int x= j.getX();
int y= j.getY();
int w= j.getWidth();
int h= j.getHeight();
x=(x-w)-a;
k.setBounds(x, y, w, h);
}
public static void placeAfter(JComponent j, int a, JComponent k) {
int x= j.getX();
int y= j.getY();
int w= j.getWidth();
int h= j.getHeight();
x=x+w+a;
k.setBounds(x, y, w, h);
}
}
但是,我想让它像l2.placeAbove(l1, 0)
一样简单,因为第三个参数感觉效率低下。 那有什么建议吗? 请使用可理解的术语。
然后使用其返回值。 而不是void
返回一个Rectangle
实例。 它看起来像:
public static Rectangle placeAbove(JComponent j, int a) {
int x= j.getX();
int y= j.getY();
int w= j.getWidth();
int h= j.getHeight();
y=(y-h)-a;
//return our new bounds projected in a Rectangle Object
return new Rectangle(x, y, w, h);
}
然后用例将设置边界矩形:
k.setBounds(placeAbove(j, a));
这样,您可以使用从JComponent中的java.awt.Component
继承的setBounds(Rectangle r)
。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.