Swing仅在调整大小后绘制

时间:2017-06-08 00:59:05

标签: java swing

程序应该在单击按钮后再画两次线,但只有在单击并然后调整窗口大小后才会这样做。我不知道发生了什么,我觉得这很容易。

你能告诉我怎么解决这个问题?

import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Random;
import java.util.Stack;

class MyButtonPanel extends JPanel {

public static final int HEIGHT = 800;
public static final int WIDTH = 800;
private JButton greenButton;
private JPanel buttonPanel;
Stack<Point> points;
int X = 25;
int Y = 25;

public MyButtonPanel() {
    greenButton = new GreenButton();
    points = new Stack<Point>();

    buttonPanel = this;

    setLayout(new FlowLayout());
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    add(greenButton);

}

class GreenButton extends JButton implements ActionListener
{
    GreenButton() {
        super("LongerLine");
        addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //points.push(new Point(0,0));
        X = 2 * X;
        Y = 2 * Y;
        validate();
    }

}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    //g2d.setColor(Color.WHITE);
    //g2d.fillRect(0, 0, WIDTH, HEIGHT);
    g2d.setColor(Color.BLACK);
    //drawLines(g2d);
    Line2D lin = new Line2D.Double(0,0, X, Y);
    g2d.draw(lin);
}

private void drawLines(Graphics2D g2d) {
    //Line2D lin = new Line2D.Float(100, 100, 250, 260);
    //g2d.draw(lin);
    double x1, y1, x2, y2;
    /*
    for(Point point: points) {
        x1 = (double) point.getX();
        y1 = (double) point.getY();
        Line2D line = new Line2D.Double(x1,y1,200,200);
        g2d.draw(line);
    }
    */
}




}

public class MyActionFrame extends JFrame {

public MyActionFrame() {
    super("Test akcji");

    JPanel buttonPanel = new MyButtonPanel();
    add(buttonPanel);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
    //setResizable(false);
}




public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new MyActionFrame();
        }
    });
}
}

1 个答案:

答案 0 :(得分:2)

当需要重新制作容器的布局时,通常在添加或删除组件时,调用此validate();或更好的revalidate();,而不是您正在做或想要的。相反,您想要调用repaint(),这表示该组件已被绘制。