【问题标题】:How do I create a JFrame containing a text box and paint component?如何创建包含文本框和绘制组件的 JFrame?
【发布时间】:2015-11-05 22:26:12
【问题描述】:

我正在尝试创建一个每隔几秒钟绘制 100 条随机线的程序。我想添加一个文本字段,允许用户调整每次刷新之间的时间量。

但是,每当我尝试向我的 JFrame 添加更多组件时,paintComponent 就会完全消失。如何创建带有文本字段和绘图的窗口?

这是我目前所拥有的

{
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.Timer;
    import java.util.*;

    public class Screensaver extends JPanel implements ActionListener {

    public static void main (String[] args){ //Create Canvas
        JFrame one = new JFrame("ScreenSaver");
        one.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Screensaver f = new Screensaver();
        one.add(f);
        one.setSize(600,600);
        one.setVisible(true);
    }

    public void paintComponent (Graphics a){
        super.paintComponent(a);
        this.setBackground(Color.WHITE);
        a.setColor(Color.BLUE); //Outline
        Random rand = new Random();
        Timer time = new Timer(4000, this);
        time.start();
        for(int i =0; i<100; i++){
            int x1 =rand.nextInt(600);
            int y1 =rand.nextInt(600);
            int x2 =rand.nextInt(600);
            int y2 =rand.nextInt(600);
            a.drawLine(x1, y1, x2, y2);
        }
    }

    public void actionPerformed(ActionEvent e) {
        repaint();
    }

}

【问题讨论】:

    标签: java swing jframe jpanel paintcomponent


    【解决方案1】:
    JTextField textField = new JTextField(10);
    one.add(textField, BorderLayout.PAGE_START);
    one.add(f, BorderLayout.CENTER);
    

    框架的默认布局管理器是 BorderLayout,因此您需要将 tomponens 添加到布局的不同区域。阅读 How to Use BorderLayout 上的 Swing 教程中的部分以获取更多信息和示例。本教程还包含其他布局管理器的示例,并将向您展示如何更好地设计您的类。

    本教程还有一个关于Custom Painting 的部分您应该阅读,因为您还应该设置自定义绘画面板的首选大小。

    【讨论】:

    • 非常有帮助。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-09-04
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多