我尝试做一件非常简单的事情。在 Main 类中,我为坐标系绘制了 2 条线。在 userPaint 类中,我从 x1 y1 x2 y2(已初始化)绘制了 1 条线。问题是 3 条线(坐标系和 x1y1x2y2 线)不在同一个窗口/框架中。编译器创建了 2 个窗口...我该如何解决?
主类:
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawLine(20, 80, 20, 200);
g.drawLine(20, 200, 140, 200);
}
public Main(String title){
super(title);
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
Main main = new Main("Graph");
userPaint up = new userPaint();
}
}
用户画图类:
import java.awt.*;
import javax.swing.*;
public class userPaint extends JFrame {
int x1, y1, x2, y2;
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawLine(x1, y1, x2, y2);
}
public userPaint(){
//Gives 4 numbers for points to drawline. Assume that the x1,y1,x2,y2 are given by Scanner.. but im gonna initialize
x1 = 200;
y1 = 200;
x2 = 300;
y2 = 300;
setSize(800, 600);
setVisible(true);
}
}
最佳答案
- 不要直接绘制到
JFrame
,而是绘制到JPanel
,您可以通过以下方式添加JFrame
的内容 PaneJFrame
的add
方法 - (1) 中的绘制应该通过覆盖
paintComponent
方法(而不是paint
方法)来完成。
例如:
public class Painter extends JPanel{
public Painter(){
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(20, 80, 20, 200);
g.drawLine(20, 200, 140, 200);
g.drawLine(x1, y1, x2, y2);
}
}
...
JFrame frame = new JFrame("Title");
frame.add(new Painter());
draw 2 lines for the Coordinate System
您提到了一个坐标系,因此您可能希望用坐标系的值偏移 x1..y2 值,以便绘制的线落在轴的范围内。例如:
g.drawLine(20, 80, 20, 200);//y-axis
g.drawLine(20, 200, 140, 200);//x-axis
g.drawLine(x1 + 20, 200 - y1, x2 + 20, 200 - y2);//offset by coordinate system
以上将 x 值偏移 x 轴的位置,将 y 值偏移 y 轴的位置(负数,因此图未反转)- 假设这些值尚未偏移, 它们的像素位置是相对于轴的边界的。
最后一点:类名应该大写
关于Java 在一帧中绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552884/