Reputation: 197
I am trying to create a simple drawing program which contains a toolbar and a drawing area. The program's main window is a JFrame. I have added a JToolBar and a JPanel (drawingPanel) on which to draw. However, the line is not drawn on drawingPanel but behind it (I can see the line when I remove drawingPanel - just comment out CreateDrawingPanel();
). How can I draw the line on drawingPanel?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class UserInterface extends JPanel
{
static JFrame frame;
static JPanel drawingPanel;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
CreateFrame();
}
});
}
private static void CreateFrame()
{
frame = new JFrame("Interface");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.add(new UserInterface());
}
public UserInterface()
{
setLayout(new BorderLayout());
CreateToolBar();
CreateDrawingPanel();
repaint();
}
private void CreateToolBar()
{
JToolBar toolbar = new JToolBar(JToolBar.VERTICAL);
JButton button = new JButton("Some button");
toolbar.add(button);
add(toolbar, BorderLayout.WEST);
toolbar.setBackground(Color.black);
toolbar.setFloatable(false);
}
private void CreateDrawingPanel()
{
drawingPanel = new JPanel();
add(drawingPanel, BorderLayout.CENTER);
drawingPanel.setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawLine(100, 100, 120, 500);
}
}
Upvotes: 1
Views: 1339
Reputation: 16294
All your drawing is on the UserInterface
object, as this is where you override paintComponent()
.
Remove the paintComponent()
override, and change the createDrawingPanel()
:
private void CreateDrawingPanel()
{
drawingPanel = new JPanel(){
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawLine(100, 100, 120, 500);
}
};
add(drawingPanel, BorderLayout.CENTER);
drawingPanel.setBackground(Color.white);
}
Upvotes: 2
Reputation: 106
You could either define your drawingPanel like this:
drawingPanel = new JPanel(){
protected void paintComponent(Graphics g){
//Your draw Code
}
};
or you could create a class that inherits from JPanel:
public class DrawingPanel extends JPanel{
public DrawingPanel(){
//...
}
protected void paintComponent(Graphics g){
//Your draw Code
}
}
and use it like this:
drawingPanel = new DrawingPanel();
Upvotes: 2