Is it possible in Java (using the awt library) to draw diagonal lines, and other shapes, with smooth lines? That is, without visible pixel squares. The image shows that the diagonal lines go like a ladder, but it is necessary that they be "smooth". That is, is it possible to draw exactly (smooth, vector) lines in Java and, if possible, how to do it? enter image description here

    1 answer 1

    In this case, you need to inherit from the Component class and override the paint (Graphics g) method as follows:

    public void paint(Graphics g) { //сглаТиваниС: Π΄Π΅Π»Π°Π΅Ρ‚ Π³Ρ€Π°Ρ„ΠΈΠΊΡƒ Π² Swing Π±ΠΎΠ»Π΅Π΅ красивой Graphics2D g2 = (Graphics2D) g; //ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΡƒΠ΅ΠΌ Graphics Π² Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); //сглаТиваниС g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } 

    This will make Swing graphics more attractive, without ladders and pixel squares.

    Just do not forget to "attach" the class that draws the components to the frame itself.

    Suppose you can do this in the constructor:

     public class FrameCreator extends Component{ JFrame frame; //ΠΊΠΎΠ΄... public FrameCreator(){ frame = new JFrame(); //ΠΊΠΎΠ΄... frame.add(this); //позволяСт ΠΏΡ€ΠΈΠΊΡ€Π΅ΠΏΠΈΡ‚ΡŒ Π½Π° Ρ„Ρ€Π΅ΠΉΠΌ класс, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ рисуСт элСмСнты } } 
    • This method has already been tried, but with it smoothing is not perfect. "Ladder" is still visible. The only difference is that the boundaries of the steps have become duller. - Nikolai
    • one
      Well, it seems to me that for Swing this is already the limit. The library was written a long time ago, and if you want something more powerful, then use javaFX (this library is already loaded in IntelijIdea). - SlandShow