Gau*_*tam 3 java swing resize jpanel repaint
我有一个JPanel,我在上面画了四个矩形.随机选择这些矩形中的每一个的颜色.仅当用户单击特定矩形时,颜色才会更改.
问题是,当用户调整窗口大小时,JPanel上的所有内容都会重复"重新绘制".这导致矩形快速改变颜色.
理想情况下,在调整大小时,我需要矩形的颜色保持不变.否则,我还可以使用一个解决方案,在完成调整大小后,JPanel只重画一次.
您对我如何实现这一点有什么一般性的想法吗?如果ComponentListener中有onStartResize和onFinishResize回调方法,我觉得这样会容易得多.
谢谢!
你可能错误地得到绘画逻辑(猜测当然,没有看到任何代码:)看起来你正在改变paintComponent方法中的颜色.这违反了一般规则:在绘画时不要改变组件的任何状态.
相反,在单击之前,请考虑具有固定颜色的矩形,然后更改颜色并重新绘制.调整大小不会在任何地方发挥作用.
此示例可用于说明@kleopatra引用的违规行为.在调整组件大小时,事件调度机制可以repaint()帮助您调用.如果你改变你正在渲染的状态,比如说paintComponent(),你会看到它快速循环.在下面的示例中,底部行在调整大小时闪烁,而顶行保持不变.
附录:AnimationTest是一个相关的例子,利用这种效果来执行动画ComponentAdapter.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** @https://stackoverflow.com/questions/7735774 */
public class ResizeMe extends JPanel {
private static final int N = 4;
private static final int SIZE = 100;
private static final Random rnd = new Random();
private final List<JLabel> list = new ArrayList<JLabel>();
private boolean randomize;
public ResizeMe(boolean randomize) {
this.randomize = randomize;
this.setLayout(new GridLayout(1, 0));
for (int i = 0; i < N; i++) {
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(SIZE, SIZE));
label.setOpaque(true);
list.add(label);
this.add(label);
}
initColors();
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
System.out.println(e);
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (randomize) {
initColors();
}
}
private void initColors() {
for (JLabel label : list) {
label.setBackground(new Color(rnd.nextInt()));
}
}
private static void display() {
JFrame f = new JFrame("ResizeMe");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
f.add(new ResizeMe(false), BorderLayout.NORTH);
f.add(new ResizeMe(true), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
display();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6549 次 |
| 最近记录: |