用 JTextField 值画一条线,我做错了什么?

问题描述

我的代码需要一些帮助。我想画一条线,后记一些其他的形状。我认为一行会是一个好的开始。我正在尝试从 textField 中获取 x 和 y 值,并且它有效。不幸的是,线条本身不会打印/绘画。我做错了什么,如何让这条线出现?

package zadanie;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MyFrame extends JFrame implements ActionListener{
    
    GraphicsClass graph = new GraphicsClass();
    JTextField textField1;
    JTextField textField2;
    JTextField textField3;
    JTextField textField4;
    
    public MyFrame() {
        
        textField1 = new JTextField(20);
        textField1.setBounds(10,20,30,20);
        textField1.addActionListener(this);
        
        textField2 = new JTextField(20);
        textField2.setBounds(50,20);
        textField2.addActionListener(this);
        
        textField3 = new JTextField(20);
        textField3.setBounds(10,50,20);
        textField3.addActionListener(this);
        
        textField4 = new JTextField(20);
        textField4.setBounds(50,20);
        textField4.addActionListener(this);
        
        graph.drawButton = new JButton("Click Me!");
        graph.drawButton.setBounds(0,80,100,40);
        graph.drawButton.addActionListener(this);
        
        this.setSize(500,500);
        this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        this.add(textField1);
        this.add(textField2);
        this.add(textField3);
        this.add(textField4);
        this.add(graph.drawButton);
        this.add(graph);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Todo Auto-generated method stub
        
        int x1 = Integer.parseInt(textField1.getText());
        int x2 = Integer.parseInt(textField2.getText());
        int y1 = Integer.parseInt(textField3.getText());
        int y2 = Integer.parseInt(textField4.getText());

        System.out.println(x1);
        System.out.println(x2);
        System.out.println(y1);
        System.out.println(y2);
        
        graph.setLine(getGraphics(),x1,y1,x2,y2);
        
    }
}
package zadanie;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class GraphicsClass extends JPanel{
    
//  MyFrame frame = new MyFrame();
    
    JButton drawButton = new JButton();
    
    public void paintComponent(Graphics g) {
        
        super.paintComponent(g);
        this.setBackground(Color.BLACK);
        
        Graphics2D g2D = (Graphics2D) g;
        
        g2D.setColor(Color.WHITE);
        g2D.drawLine(50,200,300);
        
        
        
    }

    void setLine(Graphics g,int x1,int y1,int x2,int y2) {
        g.drawLine(x1,y2);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)