我想要創建一個程序,在桌面上用此屬性繪製線條,用戶可以點擊線條旁邊的桌面圖標。 我創建樣本。我創建透明框架並在此上繪製jWindow。在MouseReleased事件中配置主框架,然後保留所有創建的jwindows。我的代碼創建了許多jwindow,這非常糟糕。對於畫線30釐米程序創建超過400 jwindow,這會導致os非常重。 可以幫助我嗎? (恕我醜的英語)在桌面上畫一條線,點擊可以在線左右
package PKHMain;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class FRMMain extends JFrame implements MouseListener, MouseMotionListener {
public FRMMain() {
this.setUndecorated(true);
this.setSize(Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLayout(null);
this.setBackground(new Color(0, 0, 0, 0));
this.setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
}
public static void main(String[] args) {
new FRMMain();
}
@Override
public void mousePressed(MouseEvent event) {
}
@Override
public void paint(Graphics g) {
repaint();
}
@Override
public void mouseClicked(MouseEvent event) {
}
@Override
public void mouseEntered(MouseEvent event) {
}
@Override
public void mouseExited(MouseEvent event) {
}
@Override
public void mouseReleased(MouseEvent event) {
this.dispose();
}
@Override
public void mouseDragged(MouseEvent event) {
int x = event.getX();
int y = event.getY();
JWindow frame = new JWindow();
frame.setBackground(new Color(0, 0, 0, 0));
frame.setContentPane(new ShapedPane(x, y));
frame.pack();
frame.setLocation(x, y);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
public void mouseMoved(MouseEvent event) {
}
public class ShapedPane extends JPanel {
public int x1;
public int y1;
public ShapedPane(int x, int y) {
setOpaque(false);
setLayout(new GridBagLayout());
x1 = x;
y1 = y;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(5, 5);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHints(hints);
g2.setColor(Color.red);
g2.fill(new Ellipse2D.Double(0, 0, getWidth(), getHeight()));
g2.dispose();
}
}
}
我的問題,很重要的是你是爲什麼原因是油漆()與重繪繪畫(),它可以導致高度處理器消耗或無限循環 – mKorbel
我刪除了paint()方法,並沒有改變任何東西。 –
將形狀列表放到FRMMain類中,並在FRMMain框架的paint方法內繪製這些形狀,並且不要創建任何新窗口。 – Holger