import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Game4 extends JPanel {
public Game4() {
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D twoD = (Graphics2D) g;
boxes(twoD);
}
public void boxes(Graphics2D twoD) {
twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());
}
}
For some reason, I can't get this code to draw out. I'm not that good with graphics2D so if I could get some help that would be great.
CodePudding user response:
Start by taking a look at Painting in AWT and Swing and Performing Custom Painting for more details on how painting works in Swing.
paint
does a lot of really important work, like setting the default color of the Graphics
context based on the components foreground
color, filling the background, setting the clip, etc.
Unless you're really willing to take over ALL the control, you're best to avoid it. Instead, prefer using paintComponent
.
You may also need to supply some basic sizing hints for the component and in order to be shown on the screen the component will need to be added to some kind of window (ie JFrame
)
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
boxes(g2d);
g2d.dispose();
}
protected void boxes(Graphics2D twoD) {
twoD.drawLine(getWidth() / 3, 0, getWidth() / 3, getHeight());
}
}
}