适当的事件后图形不显示

时间:2018-01-23 20:29:39

标签: java user-interface events

所以,我一直在研究GUI和事件处理,我制作了这段代码。

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

class drawing extends JComponent {
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.draw(new Rectangle(100, 100, 100, 100));
    }
}

class TwoButtons {

    public static void main(String[] args) {
        TwoButtons two = new TwoButtons();
        two.go();
    }
    JButton button1 = new JButton("button 1");
    JButton button2 = new JButton("button 2");
    drawing D = new drawing();

    JFrame frame = new JFrame("title");
    void go() {

        button1.addActionListener(new button1Action());

        button2.addActionListener(new button2Action());

        frame.add(BorderLayout.SOUTH, button1);
        frame.add(BorderLayout.NORTH, button2);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(900, 900);
        frame.setVisible(true);
    }

    class button1Action implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            frame.add(D);
        }
    }

    class button2Action implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            button2.setText("action 2");
        }
    }
}

因此,此代码在SOUTH生成两个按钮,另一个在JFrame的NORTH生成。

用户点击button1后应立即显示正方形,但在点击button1button2之后显示正方形(首先button1然后{{ 1}})。

为什么会这样?以及如何解决它?

1 个答案:

答案 0 :(得分:2)

Swing很懒散。动态更新UI时,您需要在希望它执行和更新传递时指示它,例如......

class button1Action implements ActionListener {
    public void actionPerformed(ActionEvent ev) {
        frame.add(D);
        frame.revalidate();
        frame.repaint();
    }
}

这会在D添加到框架

后触发布局和绘制过程