【发布时间】:2015-05-14 11:53:21
【问题描述】:
我正在创建一种绘画应用程序。用户可以通过按下/拖动鼠标在 JPanel 中移动一个圆圈。
我的JMenus 中有一个JCheckBoxMenuItem:
JCheckBoxMenuItem checkitem = new JCheckBoxMenuItem("Draw mode",false);
- 未激活时,只能移动圆圈(通过拖/按),前一个圆圈将被删除。
- 激活时,圆圈只能移动,但前一个圆圈不会在鼠标拖/按时被删除(这与绘画程序的工作方式相同)
我的代码的缩短版本:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class GUI extends JFrame implements MouseListener, MouseMotionListener, ActionListener, ItemListener
{
JPanel mainPan, colorPan;
Color color = Color.BLACK;
JCheckBoxMenuItem checkitem;
boolean clear = true;
public GUI(String header)
{
maker();
mainPan.addMouseListener(this);
mainPan.addMouseMotionListener(this);
add(mainPan , BorderLayout.CENTER);
add(colorPan, BorderLayout.PAGE_END);
}
public void maker()
{
colorPan = new JPanel();
colorPan.setLayout(new GridLayout(1, 0));
mainPan = new JPanel(){
@Override
public void paintComponent(Graphics g)
{
//g.setColor(Color.WHITE);
//g.fillRect(0,0,getWidth(),getHeight());
if(clear)
super.paintComponent(g); //Do the same thing as above(Clear JPanel)
g.setColor(color);
g.fillOval(x,y,50,50); //x and y are integer variables that I use in my full program
}
};
checkitem = new JCheckBoxMenuItem("Draw mode",false);
//After adding this to a JMenu,
checkitem.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
clear = false;
}
else
{
clear = true;
}
}
}
下面的截图显示了我的完整程序的输出:
colorPan 是 JPanel,里面装满了不同颜色的 JButton。最上面是mainPan。
目前,“绘图模式”无法按预期工作。我一直认为super.paintComponent(g); 是在调用repaint() 时清除/重置屏幕的那个。但我删除了它,看到程序的行为方式相同,我感到非常惊讶。
基本上,我的问题就在这里:
if(clear)
super.paintComponent(g);
我需要防止在调用repaint() 时清除所有内容。我如何实现我想要的?
【问题讨论】:
-
引用了一个完整的例子here。
-
我不明白。你能在这里发布答案吗?
标签: java swing graphics jpanel