drawing line on jpanel
I want to draw a line on my jpanel. I'm not sure how to do it. I want to draw it on pane2.
public Component createComponents(){
GridBagConstraints c =
new GridBagConstraints();
GridBagLayout gridbag =new GridBagLayout();
JPanel pane =new JPanel(gridbag);
pane.setPreferredSize(new Dimension(280,300));
JPanel pane2 =new JPanel();
pane2.setPreferredSize(new Dimension(200,200));
pane2.setBackground(Color.BLACK);
//****** I want to draw a line here onto pane2 ******//
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(pane2, c);
pane.add(pane2);
JButton button =new JButton("Advance");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(this);
button.setMaximumSize(new Dimension(20,10));
label.setLabelFor(button);
button.setAlignmentY(Button.BOTTOM_ALIGNMENT);
c.insets =new Insets(15, 0, 0, 0);
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(button, c);
pane.add(button);
pane.add(label);
pane.setBorder(BorderFactory.createEmptyBorder(
10,//top
10,//left
10,//bottom
10)//right
);
return pane;
}
> I kinda figured I had to do that. But I just don't
> understand how to fit it into my code. I wrote a
> seperate method and it did nothing.
You can't just add a separate paintComponent method like that. You will need to override the paintComponent method of your panel, like so:
JPanel panelWithRedLine = new JPanel() {
// Override the panel's paintComponent method:
protected void paintComponent(Graphics g) {
super.paintComponent(g); // also, you need to call super.paintComponent here, not super.paint
g.setColor(Color.RED);
g.drawLine(0,0,20,20);
}
}
If you do this often you might want to create a new panel class that you can reuse:
public class PanelWithColoredLine extends JPanel {
private Point p1;
private Point p2;
private Color color;
public PanelWithColoredLine(Point p1, Point p2, Color color) {
this.p1 = p1;
this.p2 = p2;
this.color = color;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
JPanel panel = new PanelWithColoredLine(new Point(0, 0), new Point(20, 20), Color.RED);
....
Its me again. I've worked some more on this program and got a bit further and got hung up once again. I'm getting a NullPointerException and I can't figure out why.
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
System.out.println("cells: " + cells[0]);
pane2.calculateCells(cells);
}
The last line is giving me a nullpointerexception. Pane2 is created globally at the start of the class. Cells is an array of cells(class i created) which I created and filled before this ever happened. Pane2 is a PanelWithLines which extends JPanel. If any of you could figure out why this is happening it would be much appreciated.
Thank you
Mike