[英]Graphics not working in Java
I am trying to mess around with some graphics in java, however i can't get it to work. 我试图弄乱Java中的某些图形,但是我无法使其正常工作。 The JFrame comes up with the button i created, but the JFrame is just gray with no red line that i want it to draw. JFrame带有我创建的按钮,但是JFrame只是灰色,没有我要绘制的红线。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Shapes extends JFrame implements ActionListener{
JButton button = new JButton("click");
public Shapes() {
setVisible(true);
setSize(500, 500);
button.addActionListener(this);
button.setSize(20, 20);
setLayout(new FlowLayout());
add(button);
repaint();
}
public static void main(String[] args){
Shapes s = new Shapes();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.drawLine(5, 10, 10, 20);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button){
repaint();
}
}
}
Two things: 两件事情:
1). 1)。 You don't really want to do custom painting on a top-level container such as a JFrame
. 您实际上并不想在诸如JFrame
类的顶级容器上进行自定义绘制。 Instead you want to use a JPanel
相反,您想使用一个JPanel
class Panel extends JPanel
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.drawLine(5, 10, 10, 20);
}
}
And add it to your JFrame
: add(new Panel());
并将其添加到您的JFrame
: add(new Panel());
(Or create an object if you want). (或根据需要创建一个对象)。
2). 2)。 setVisible(true);
should be the very last thing that you do while setting up your window. 应该是设置窗口时要做的最后一件事。 So change your constructor: 因此,更改您的构造函数:
public Shapes() {
setSize(500, 500);
button.addActionListener(this);
button.setSize(20, 20);
setLayout(new FlowLayout());
add(button);
add(new Panel()) // added from part 1
repaint();
setVisible(true);
}
For more information go through the "performing custom painting tutorials." 有关更多信息,请阅读“执行自定义绘画教程”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.