java如何画横线
在Java中绘制横线的方法
在Java中,可以通过多种方式绘制横线,具体取决于使用的技术栈。以下是几种常见的方法:
使用Swing绘制横线
在Swing中,可以通过重写paintComponent方法,使用Graphics类的drawLine方法绘制横线。

import javax.swing.*;
import java.awt.*;
public class DrawLineExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(50, 100, 250, 100); // 从(50,100)到(250,100)绘制横线
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Line Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.add(new DrawLineExample());
frame.setVisible(true);
}
}
使用JavaFX绘制横线
在JavaFX中,可以使用Line类来绘制横线。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class DrawLineExampleFX extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Line line = new Line(50, 100, 250, 100); // 从(50,100)到(250,100)绘制横线
pane.getChildren().add(line);
Scene scene = new Scene(pane, 300, 200);
primaryStage.setScene(scene);
primaryStage.setTitle("Draw Line Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
使用AWT绘制横线
在AWT中,可以通过重写paint方法,使用Graphics类的drawLine方法绘制横线。
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class DrawLineExampleAWT extends Frame {
public DrawLineExampleAWT() {
setSize(300, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
public void paint(Graphics g) {
g.drawLine(50, 100, 250, 100); // 从(50,100)到(250,100)绘制横线
}
public static void main(String[] args) {
DrawLineExampleAWT frame = new DrawLineExampleAWT();
frame.setVisible(true);
}
}
使用HTML标签在Java Web应用中绘制横线
在Java Web应用中,可以通过HTML的<hr>标签绘制横线。
<hr style="width: 200px; margin-left: 50px;">
以上方法涵盖了从桌面应用到Web应用的不同场景,可以根据具体需求选择合适的方式。






