JComponent setSize() 和 setLocation() 不起作用



我正在尝试设置一个容器 JComponent,它绘制一个带有虚线边框的矩形。问题是 setLocation(( 和 setSize(( 不起作用。我尝试了一些东西,比如super.setSize((和super.setPrefferedSize((。

对于任何上下文,我都会将其添加到具有FlowLayout的JPanel中。JFrame的宽度为500,高度为300。这是在Linux上运行的,以防操作系统很重要。

public class RectangleContainer extends JComponent{
int x = 0;
int y = 0;
int length = 50;
int dashLength = 10;
RectangleContainer(){
super();
setSize(60, 60);
setPreferredSize(new Dimension(60, 60)); //length+dashLength
}
// @Override
// public void setSize(int width, int height){
//     this.length = (width > height) ? height:width;
//     super.setSize(length+dashLength, length+dashLength);
//     super.setPreferredSize(new Dimension(length+dashLength, length+dashLength));
//     revalidate();
// }
//TODO: add dashLength or not?
@Override
public Dimension getSize(){
return new Dimension(length+dashLength, length+dashLength);
}
@Override
public void setLocation(int x, int y){
super.setLocation(x, y);
// System.out.println(String.format("X: %d", x));
// System.out.println(String.format("Y: %d", y));
// this.x = x;
// this.y = y;
// //super.setSize(length+dashLength+x, length+dashLength+y);
// //super.setPreferredSize(new Dimension(length+dashLength+x, length+dashLength+y));
// //repaint();
// revalidate();
}
@Override
public Point getLocation(){
return new Point(this.x, this.y);
}
//Code altered, but mainly from http://www.java2s.com/Code/Java/2D-Graphics-GUI/Dashedstroke.htm
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.white);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, dashLength, new float[]{dashLength}, 0.0f));
g2.setPaint(Color.black);
Rectangle r = new Rectangle(x, y, length, length);
g2.draw(r);
}
}

如果您尝试完成的只是在特定位置创建一个带有虚线边框的组件,那么我希望此示例将帮助您入门

public class DashTest
{
public static void main(String args[])
{
JFrame frame=new JFrame("Dash Test");

frame.setContentPane(new JPanel(null)); /*A panel with no layout as the main container*/

JButton button=new JButton("Dashed Button");

button.setBorder(BorderFactory.createDashedBorder(Color.red));
/*swing comes inbuilt with custom borders*/


button.setBounds(100,100,150,30);/*set the x,y,width,height of the button works only if you have no layout set as shown above*/

frame.add(button);

frame.setSize(500,500);

frame.setVisible(true);
}
}    

出于您的目的,没有必要仅仅为了使用边框而将您的组件子类化为 JComponent,但是如果您试图在组件中做更多花哨的事情而不仅仅是边框,那么您必须覆盖该组件绘制组件方法

class MyComponent extends JComponent
{  
MyComponent ()
{
super();

setBorder(BorderFactory.createDashedBorder(Color.red));/*keep the red border*/
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);/*NEVER FORGET THIS*/
Graphics2D g2d=(Graphics2D)g;
/*do more creative stuff now with graphics*/
}
}

最新更新