java如何绘制桌子
使用Java绘图API绘制桌子
在Java中,可以使用java.awt和javax.swing包中的绘图API来绘制简单的图形,包括桌子。以下是一个示例代码,展示如何绘制一个简单的桌子:
import javax.swing.*;
import java.awt.*;
public class DrawTable extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 设置背景色
setBackground(Color.WHITE);
// 绘制桌面
g.setColor(Color.BROWN);
g.fillRect(100, 100, 200, 20);
// 绘制桌腿
g.fillRect(120, 120, 20, 100);
g.fillRect(260, 120, 20, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Table Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.add(new DrawTable());
frame.setVisible(true);
}
}
绘制更复杂的3D桌子
如果需要绘制更复杂的3D效果桌子,可以使用Graphics2D类:
import javax.swing.*;
import java.awt.*;
public class Draw3DTable extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 绘制桌面(3D效果)
g2d.setColor(new Color(139, 69, 19)); // 棕色
g2d.fill3DRect(100, 100, 200, 20, true);
// 绘制桌腿(3D效果)
g2d.fill3DRect(120, 120, 20, 100, true);
g2d.fill3DRect(260, 120, 20, 100, true);
// 添加阴影效果
g2d.setColor(Color.GRAY);
g2d.drawLine(120, 220, 280, 220);
}
public static void main(String[] args) {
JFrame frame = new JFrame("3D Table Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.add(new Draw3DTable());
frame.setVisible(true);
}
}
使用JavaFX绘制桌子
如果使用JavaFX,可以创建更现代化的图形:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class JavaFXTable extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
// 绘制桌面
Rectangle tableTop = new Rectangle(100, 100, 200, 20);
tableTop.setFill(Color.BROWN);
// 绘制桌腿
Rectangle leg1 = new Rectangle(120, 120, 20, 100);
leg1.setFill(Color.SADDLEBROWN);
Rectangle leg2 = new Rectangle(260, 120, 20, 100);
leg2.setFill(Color.SADDLEBROWN);
pane.getChildren().addAll(tableTop, leg1, leg2);
Scene scene = new Scene(pane, 400, 300);
primaryStage.setTitle("JavaFX Table");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
添加纹理和细节
为了使桌子看起来更真实,可以添加纹理和细节:

// 在Swing中绘制带纹理的桌子
g.setColor(new Color(101, 67, 33)); // 深棕色
g.fillRect(100, 100, 200, 20);
// 添加木纹效果
g.setColor(new Color(139, 69, 19));
for (int i = 0; i < 10; i++) {
g.drawLine(100 + i*20, 100, 100 + i*20, 120);
}
这些代码示例展示了如何在Java中绘制简单的桌子图形,可以根据需要调整颜色、尺寸和样式来创建更复杂的效果。






