gpt4 book ai didi

java - 图形被 Swing 组件切断

转载 作者:行者123 更新时间:2023-12-01 18:35:31 26 4
gpt4 key购买 nike

我正在尝试编写一个程序,用户可以输入 3 个点的 x 和 y 值,然后将绘制这 3 个点。然而,文本字段和按钮(我认为)导致图形被切断。

窗口类

import java.awt.FlowLayout;

import javax.swing.JFrame;
public class Window {
public static void main(String[] args) {
Points frame = new Points();
frame.setSize(640, 480);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new FlowLayout());


}
}

积分等级

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

public class Points extends JFrame{
private JTextField x1;
private JTextField y1;
private JTextField x2;
private JTextField y2;
private JTextField x3;
private JTextField y3;
private JButton button;
private JLabel label;
static int nx1=0, nx2=0, nx3=0, ny1=0, ny2=0, ny3=0;


public Points(){

x1 = new JTextField("0", 2);
y1 = new JTextField("0", 2);
x2 = new JTextField("0", 2);
y2 = new JTextField("0",2);
x3 = new JTextField("0", 2);
y3 = new JTextField("0", 2);
button = new JButton("Submit");
label = new JLabel();

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String sx1=x1.getText();String sx2=x2.getText();String sx3 = x3.getText();
String sy1 = y1.getText();String sy2 = y2.getText(); String sy3 = y3.getText();

nx1 = Integer.parseInt(sx1);
nx2 = Integer.parseInt(sx2);
nx3 = Integer.parseInt(sx3);
ny1 = Integer.parseInt(sy1);
ny2 = Integer.parseInt(sy2);
ny3 = Integer.parseInt(sy3);


}
});

add(x1);
add(y1);
add(x2);
add(y2);
add(x3);
add(y3);
add(button);
add(new Panel());

}
}

面板类

import java.awt.*;

import javax.swing.*;

public class Panel extends JPanel{

public void paint(Graphics g){
System.out.println(Points.nx1);
g.drawRect(Points.nx1, Points.ny1, 5,5);
g.drawRect(Points.nx2, Points.ny2, 5,5);
g.drawRect(Points.nx3, Points.ny3, 5,5);
repaint();
}
}

最佳答案

使用paintComponent(Graphics g)作为swing组件,并在构造函数本身内设置面板的布局。添加所有组件后,您将调用 setLayout 方法。

关于java - 图形被 Swing 组件切断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22200653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com