简体   繁体   中英

Swing draws only after resizing

Program should draw the line twice longer after clicking the button, but it only does that after clicking AND THEN resizing the window. I don't know what is happening, i thought this is gonna be easy.

Could you tell me how can I fix it?

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();
        }
    });
}
}

This validate(); , or better revalidate(); is called when a container's layout needs to be re-done, often when components are added or removed, and is not what you're doing or desiring. Instead you want to call repaint() which suggests that the component be painted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM