gpt4 book ai didi

java - 按下按钮时如何绘制垂直线?

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:54 25 4
gpt4 key购买 nike

当我按下 Java Swing 中的组件时,无法画线。我怎样才能做到这一点?我已经使用过paint方法,我的问题是当程序自动执行paint方法调用时,paint方法中将存在DrawLine()方法,那么除了paint方法之外,还有什么方法可以获取线条?

请给点建议。

下面的代码我已经尝试过,它显示行,但我想在单击组件时显示行。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class ReferenceLink1 extends JFrame
{
JLabel l1;
JLabel l2;
JPanel p1;

ReferenceLink1()
{
p1 = new JPanel();
p1.setLayout(null);
p1.setBackground(Color.ORANGE);
p1.setOpaque(true);
p1.setBounds(0,0,300,400);

setLayout(null);
l1 = new JLabel();
l1.setText("l1");
l1.setBounds(20, 40, 100, 40);
l1.setHorizontalAlignment(SwingConstants.CENTER);
l1.setBackground(Color.GREEN);
l1.setOpaque(true);

l2 = new JLabel(); ;
l2.setText("l2");
l2.setBounds(20, 100,100,40);
l2.setBackground(Color.BLUE);
l2.setHorizontalAlignment(SwingConstants.CENTER);
l2.setOpaque(true);

p1.add(l1);
p1.add(l2);
add(p1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBounds(0,0,400,400);
}

public void paint(Graphics g)
{
super.paint(g);
g.drawLine(77,110,77,130);
}

public static void main(String args[])
{
ReferenceLink1 rf = new ReferenceLink1();
}
}

最佳答案

class Surface extends JPanel {

private void doDrawing(Graphics g) {

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.blue);

Dimension size = getSize();
Insets insets = getInsets();

int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;

Random r = new Random();

for (int i = 0; i < 1000; i++) {

int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
g2d.drawLine(x, y, x, y);
}
}

@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
doDrawing(g);
}
}

public class Points extends JFrame {

public Points() {

initUI();
}

private void initUI() {

setTitle("Points");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

add(new Surface());

setSize(350, 250);
setLocationRelativeTo(null);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {

Points ps = new Points();
ps.setVisible(true);
}
});
}
}

关于java - 按下按钮时如何绘制垂直线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27986098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com