我正在尝试构建一个简单的应用程序,它有一个半透明的框架,它绘制了用户想要的线条。我还添加了监听器来捕捉鼠标事件,并相应地显示这些事件。一切正常,但问题是: 1)窗口不透明 2)它是完全黑色的,线条呈现白色。
任何人都可以 这是代码:
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MouseListen2 extends JFrame implements MouseListener {
String str = "Nothing";
int x[][] = new int[100][2];
int count = 0;
int flag = 1;
boolean draw = false;
MouseListen2() {
super("Line Draw App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
this.addMouseListener(this);
setBackground(new Color(0, 0, 0, 0));
JPanel jp = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Paint gp = new GradientPaint(300, 700, new Color(20, 20, 210, 0), 100, 00, new Color(10, 20, 40, 255));
g2.setPaint(gp);
g2.fillRect(0, 0, getWidth(), getHeight());
}
};
setContentPane(jp);
setVisible(true);
//c.setOpaque(true);
}
public void paint(Graphics g) {
//Graphics g=this.getGraphics();
//super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.clearRect(0, 0, getWidth(), getHeight());
g2.drawString(str, 50, 50);
//initially count=0 hence i<-1 so loop will not automatically run in the beginning
for (int i = 0; i < count - 1; i = i + 2) {
g2.drawLine(x[i][0], x[i][1], x[i + 1][0], x[i + 1][1]);
}
//repaint(); using this here creates an infinite loop as after mouse event paint is called and at the end
//this method is again called using the repaint() and so on the loop continues.
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MouseListen2();
}
});
}
@Override
public void mouseClicked(MouseEvent e) {
str = "clicked";
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
str = "pressed";
repaint();
x[count][0] = e.getX();
x[count][1] = e.getY();
count++;
}
@Override
public void mouseReleased(MouseEvent e) {
str = "released";
draw = true;
x[count][0] = e.getX();
x[count][1] = e.getY();
count++;
//draw();
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
str = "entered";
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
str = "exited";
repaint();
}
}
答案 0 :(得分:3)
必须将MouseListener
添加到JPanel
,因为您已将MouseListener
添加到JFrame
(this.addMouseListener(this);
)
此代码行setContentPane(jp);
将JPanel
添加到BorderLayout.CENTER
JFrame
的{{1}},在这种情况下(不存在任何其他JComponent
JFrame
已添加到JFrame
)将整个/所有可用空间填入mouse event
然后JPanel
只能访问JFrame
,鼠标无法访问RootPane
的{{1}}或ContentPane
删除/评论public void paint(Graphics g)
并将相关代码块移至paintComponent
的{{1}}
答案 1 :(得分:2)