[英]repaint causes component overflow
我希望这次可以正确使用问题函数。 从昨天到现在,我一直对一个问题感到困惑。 我使用Google搜索询问Java老师,但没有解决我的问题。
当我使用repaint
,成形的JPanel
的子组件将超出其显示区域。 如下图所示,
这就是我想要的效果
但是当我使用重绘时,某些东西会改变。
一开始该按钮似乎不正确。
但有时按钮会恢复正常
这些是我的代码。 我使用重绘是因为我检查的信息告诉我可以使用它。 重绘以实现动画效果。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.RoundRectangle2D;
class GPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.clip(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), getWidth(), getHeight()));
g2d.setPaint(Color.BLUE);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
public class MainComponentOverflow {
public static void main(String[] args) {
JFrame frame = new JFrame();
// This is a panel with a shape
GPanel panel = new GPanel();
// This one is the effect I am looking for, the rectangle is displayed in the Panel.
//panel.add(new Normal());
// The following two will have problems, the rectangle will be displayed outside the Panel
//panel.add(new Problem1());
panel.add(new Problem2());
//panel.add(new JButton("This will also cause problems, but it may also display properly when I resize the window."));
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class Normal extends JPanel {
public Normal() {
setPreferredSize(new Dimension(500, 500));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
class Problem1 extends JPanel implements ActionListener {
public Problem1() {
Timer timer = new Timer(16, this);
timer.start();
setPreferredSize(new Dimension(500, 500));
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
class Problem2 extends JPanel implements ActionListener {
public Problem2() {
Timer timer = new Timer(16, this);
timer.start();
setPreferredSize(new Dimension(500, 500));
}
@Override
public void actionPerformed(ActionEvent e) {
setBackground(new Color((float) Math.random(), (float)Math.random(), (float)Math.random()));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
}
首先绘制框架时,将在GPanel
设置剪辑,然后在Problem1
使用相同的剪辑Problem1
进行绘制,因此它将起作用。
然而,当你重绘Problem1
, GPanel
不会重新绘制第一,所以剪辑未设置,并没有剪辑限制Problem1
。
如果重绘父级GPanel
而不是重Problem1
GPanel
,它将解决您的问题。
另一个解决方案是将片段也放置在Problem1
。
请注意,您可以使用Ellipse2D
替换RoundRect2D
,因为它用来绘制椭圆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.