我用JFrame
和JPanel
制作了一个简单的绘制矩形应用程序
Graphics2D g2d = (Graphics2D)jPanel1.getGraphics();
g2d.setColor(Color.red);
g2d.drawRect(x,y,w,h);
每当我画东西并单击菜单时,重叠的部分就会消失
如何解决?
答案 0 :(得分:2)
正如我在评论中已经说过的,永远不要使用jPanel1.getGraphics()
,而是改写方法paintComponent
。面板重新粉刷时将始终调用此方法。这是一个小例子:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
* <code>PaintExample</code>.
*/
public class PaintExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// correct approach
g.setColor(Color.RED);
g.fillRect(20, 20, Math.max(getWidth() - 200, 0), Math.max(getHeight() - 100, 0));
}
@Override
public Dimension getPreferredSize() {
// required for correct work of JFrame.pack method
return new Dimension(500, 400);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(PaintExample::createAndShowGUI);
}
private static void createAndShowGUI() {
JFrame frm = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu m = new JMenu("File");
m.add("Test menu item 1");
m.add("Test menu item 2");
m.add("Test menu item 3");
menuBar.add(m);
frm.setJMenuBar(menuBar);
frm.add(new PaintExample());
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}