我想drawLine(0,0,getWidth(), getHeight())在JavaFX中做.我不只是想把数字放在我的行中.以下是JFrame和JavaFX的代码.
package project;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class main extends JPanel{
public static void main(String args[])
{
JFrame myWindow = new JFrame("Isometric Grid");
main myPanel = new main(); //myPanel is just a name
myWindow.setSize(400,400);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.add(myPanel);
myWindow.setVisible(true);
}
//this method will override main and create a custom graphic
public void paintComponent(Graphics myPen) //change
{
super.paintComponent(myPen);
this.setBackground(Color.BLACK);
myPen.setColor(Color.blue);
myPen.drawLine(0, 0, getWidth(), getHeight());
}
}
Run Code Online (Sandbox Code Playgroud)
我不想这样做:
package JavaFXApplication14;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class JavaFXApplication14 extends Application {
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Line ln = new Line(0,0,480,480);
ln.setStrokeWidth(1);
root.getChildren().add(ln);
Scene scene = new Scene(root, 480, 480, Color.SKYBLUE);
primaryStage.setTitle("Stuff");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
我有的其他问题是如何做getHeight(); 在JavaFX中的for循环中:
for(int y = 0; y < getHeight(); y = y + 100)
Run Code Online (Sandbox Code Playgroud)
是否有可能做这样的事情:
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 480, 480, Color.SKYBLUE);
primaryStage.setTitle("Stuff");
primaryStage.setScene(scene);
primaryStage.show();
int x = (int) scene.getWidth();
int y = (int) scene.getHeight();
Line ln = new Line(0, 0, x, y); //480s dont matter
ln.setStrokeWidth(1);
root.getChildren().add(ln);
}
Run Code Online (Sandbox Code Playgroud)
你做同样的事情,除了场景的宽度和高度.您无法使用该组,因为它会自行调整大小以包含该行.另一个技巧是绑定宽度和高度,以便您可以调整舞台大小.因此,在声明场景后,添加以下两行.
Scene scene = new Scene(root, 480, 480, Color.SKYBLUE);
ln.endXProperty().bind(scene.widthProperty());
ln.endYProperty().bind(scene.heightProperty());
Run Code Online (Sandbox Code Playgroud)
如果你不想让它受到约束,那就是它 ln.setEndX(scene.getWidth());
对于矩形,
for(int y = 0; y < scene.getHeight(); y += 20) {
//Rectangle(double x, double y, double width, double height)
Rectangle rect = new Rectangle(20, y, 10, 10);
//default is black fill but you can chamge it;
rect.setFill(Color.RED);
//or in css, same as this
rect.setStyle("-fx-fill: purple;");
//then add it to the Group
root.getChildren().add(rect);
}
Run Code Online (Sandbox Code Playgroud)