Null pointer exception - java

I'm fairly new to StackOverFlow. I have a years experience with Java, but I can't seem to find an the line(s) in this code that triggers the Null pointer exception. Imports are all ready done.
public class BallShooter extends JFrame{
private JFrame ballshooter;
private BallShooter bs;
private MenuPanel mp;
private MainPanel mep;
private GamePanel gp;
private Balls balls;
private CardLayout card;
private int[] leaderboard;
private boolean ballHitWall;
public BallShooter()
{
mep = new MainPanel();
mp = new MenuPanel();
gp = new GamePanel();
ballshooter = new JFrame();
ballshooter.setLocation(0, 0);
ballshooter.setSize(800, 700);
ballshooter.setDefaultCloseOperation(EXIT_ON_CLOSE);
ballshooter.setBackground(Color.GRAY);
ballshooter.setResizable(false);
ballshooter.getContentPane().add(mep);
ballshooter.setVisible(true);
card = (CardLayout)(mep.getLayout());
}
public static void main(String [] args)
{
BallShooter balls = new BallShooter();
}
class MainPanel extends JPanel
{
public MainPanel()
{
setSize(800,700);
setVisible(true);
setBackground(Color.GRAY);
setLayout(new CardLayout());
add(mp); <-- line 52
add(gp);
}
}
class MenuPanel extends JPanel implements ActionListener
{
private JButton startGame;
private JButton leaderboard;
private JButton instructions;
public MenuPanel()
{
setLayout(null);
setSize(800,700);
setBackground(Color.GRAY);
startGame = new JButton("Start the GAME.");
leaderboard = new JButton("Go to LEADERBOARD.");
instructions = new JButton("Instructions.");
startGame.addActionListener(this);
leaderboard.addActionListener(this);
instructions.addActionListener(this);
startGame.setBounds(300,100,200,150);
leaderboard.setBounds(300,250,200,150);
instructions.setBounds(300,400,200,150);
add(startGame);
add(leaderboard);
add(instructions);
}
public void actionPerformed(ActionEvent e) {
String in = e.getActionCommand();
if(in.equals("Start the GAME."))
{
card.next(mep);
}
}
}
class GamePanel extends JPanel implements ActionListener
{
private JButton stats;
private int pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9,pos10,pos11,pos12,pos13,pos14,pos15,pos16,pos17,pos18,pos19,pos20 ;
private boolean onePos,twoPos,threePos,fourPos,fivePos,sixPos,sevenPos,eightPos,ninePos,tenPos,elevenPos,twelvePos,thirteenPos,fourteenPos,fifteenPos,sixteenPos,seventeenPos,eighteenPos,ninteenPos,twentyPos = true;
private int x,y;
public GamePanel()
{
balls = new Balls();
onePos = true;
setSize(800,700);
setBackground(Color.GRAY);
setLayout(null);
if(onePos)
{
pos1 = 1;
x = 100;
y = 100;
balls.setBounds(x,y, 50,50);
gp.add(balls);
}
}
public void actionPerformed(ActionEvent e) {}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
g.drawRect(100, 100, 600, 500);
}
}
class Balls extends JPanel {
private int color;
private int vX, vY;
private int ballW = 50, ballH = 50;
private int x,y;
public Balls()
{
setSize(50,50);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
color = (int)(Math.random()*4+1);
if(color == 1)
{
g.setColor(Color.YELLOW);
g.drawOval(0, 0, ballW, ballH);
}
else if(color == 2)
{
g.setColor(Color.GREEN);
g.drawOval(0, 0, ballW, ballH);
}
else if(color == 3)
{
g.setColor(Color.RED);
g.drawOval(0, 0, ballW, ballH);
}
else if(color == 4)
{
g.setColor(Color.BLUE);
g.drawOval(0, 0, ballW, ballH);
}
}
}
}
I have no idea what's going on. It's just flying over my head. The error:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1097)
at java.awt.Container.add(Container.java:417)
at BallShooter$MainPanel.<init>(BallShooter.java:52)
at BallShooter.<init>(BallShooter.java:24)
at BallShooter.main(BallShooter.java:42)
If anyone could help me with this, that would be greatly appreciated.
EDIT First time posting, so there's an error with the formatting. The class header didn't go into the code section and the last bracket as well.

General rule - when you're reading a stack trace like this, look for the first line that's one of YOUR classes, as opposed to a JDK or library class. In this case, the problem can be found on line 52 of BallShooter.java.
When that line runs, mp is null, so you're trying to add a null to your container, hence the exception.
To fix this, create the other two panels first, and the MainPanel last.

You're initializing the non-static nested class MainPanel, which uses your mp and gp fields from the BallShooter class before they're initialized (see the lines which call #add in the MainPanel constructor). Try calling mep#add after you've created all the menus, or consider something along the lines of an #init method (or even a different hierarchy/design).

Related

How can you adjust the thickness of a line drawn from g.drawLine() method

I am looking to adjust the thickness of the line drawn at line 75 under the "MyPanel" Class you will find in the comments. My overall intent of this program is to draw letters on the screen when buttons are clicked. Thanks
public class Painttest extends JFrame {
private Timer timer;
private JPanel panel1, panel2;
private MyPanel center;
private MyButton stop, A, B;
public Painttest() {
this.setSize(650, 700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
panel1 = new JPanel();
panel2 = new JPanel();
center = new MyPanel();
center.setBackground(Color.cyan);
stop = new MyButton("Stop");
stop.setName("stop button");
A = new MyButton("A");
A.setName("A Button");
B = new MyButton("B");
B.setName("B Button");
panel1.add(A);
panel1.add(B);
panel2.add(stop);
this.add(panel1, BorderLayout.WEST);
this.add(center, BorderLayout.CENTER);
this.add(panel2, BorderLayout.EAST);
timer = new Timer(50, center);
this.setVisible(true);
System.out.println(center.getSize()); // size of center panel
}
public static void main(String[] args) {
new Painttest();
}
///////////////////////////////////////////////////////////////////////
// MyPanel class : This panel will be used to draw on
////////////////////////////////////////////////////////////////////////
private class MyPanel extends JPanel implements ActionListener {
private int startingx, startingy;
private int endingx, endingy;
MyPanel() {
startingx = 110;
startingy = 330;
endingx = startingx ;
endingy = startingy ;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// g.fillOval(startingx, startingy, 30, 30);
g.drawLine(startingx, startingy, endingx,endingy); // draws a single line
}
#Override
public void actionPerformed(ActionEvent e) {
startingx = startingx + 1;
startingy = startingy - 3;
repaint();
}
}
///////////////////////////////////////////////////////////////////////
// MyButton class : When Clicked, I want it to draw something on the MyPanel (center)
////////////////////////////////////////////////////////////////////////
private class MyButton extends JButton implements ActionListener {
String name;
MyButton(String title) {
super(title);
addActionListener(this);
name = "NOT SET";
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed a button " + name);
////////////////////////////////////
// if Statements to control the timer
////////////////////////////////////
// STOP TIMER
if (e.getSource() == stop) {
timer.stop();
}
if(e.getSource() == A){
timer.start();
}
if(e.getSource() == B){
timer.start();
}
}
public void setName(String newname) {
name = newname;
}
public String getName() {
return name;
}
}
}
Modify your paintComponent method something like this:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(6.0F));
// g.fillOval(startingx, startingy, 30, 30);
g2d.drawLine(startingx, startingy, endingx, endingy);
}
You can set various kinds of strokes. A basic stroke is a solid thick line.

Creating simple TicTacToe GUI game

I am trying to create a simple Tic-Tac-Toe game using GUI. I have one button, which shows the player's turn (when pressed the button itself changes its text to 0 or 1 (drawing X or O)).
However I am stuck with a problem here, I have no idea why my test within the MouseListener is applied to every single Jcomponent object (my class TicTacToe extends it) and all of the 9 Panels, which are within GridLayout(3,3) are filled with the same drawing...
Here is my TicTacToe class
public class TicTacToe extends JComponent{
private int ovalOrX = 0;
public TicTacToe(){
super.setPreferredSize(new Dimension(300,300));
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.drawLine(0, 0, getWidth(), 0);//top line
g.drawLine(0, 0, 0, getHeight());//left line
g.drawLine(0, 300, getWidth(), getHeight());//botton line
g.drawLine(getWidth(),getHeight(), getWidth(), 0);//right line
if(ovalOrX == 1){
g.setColor(Color.RED);
g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);
}
if(ovalOrX == 2){
g.setColor(Color.BLUE);
g.drawOval(0,0,100,100);
}
}
public void drawX(){
ovalOrX = 1;
repaint();
}
public void drawCircle(){
ovalOrX = 2;
repaint();
}
}
And here is my JFrame class:
public class TicTacToeFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 300;
private JPanel mainPanel;
private TicTacToe scene;
private TicTacToe s00;
private TicTacToe s01;
private TicTacToe s02;
//finish top raw
private TicTacToe s10;
private TicTacToe s11;
private TicTacToe s12;
//finish middle raw
private TicTacToe s20;
private TicTacToe s21;
private TicTacToe s22;
private int buttonInt = 0;
private JButton OX;
class AddButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
if(buttonInt == 0){
buttonInt++;
}
else if(buttonInt == 1){
buttonInt = 0;
}
OX.setText("Player: " + buttonInt);
}
}
class MyMouseListener extends MouseAdapter{
public void mouseClicked(MouseEvent event){
TicTacToe[] myPanelArray = {s00,s01,s02,s10,s11,s12,s20,s21,s22};
if(buttonInt == 0){
for(int i = 0; i < myPanelArray.length;i++){
if(myPanelArray[i].contains(event.getPoint())){
myPanelArray[i].drawCircle();
}
}
}
}
}
public TicTacToeFrame(){
scene = new TicTacToe();
scene.setPreferredSize(new Dimension(300,300));
add(scene,BorderLayout.CENTER);
OX = new JButton("Player: " + buttonInt);
OX.addActionListener(new AddButtonListener());
add(OX,BorderLayout.NORTH);
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(3,3));
fillScene();
add(mainPanel,BorderLayout.CENTER);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
}
private void fillScene(){
s00 = new TicTacToe();
s00.addMouseListener(new MyMouseListener());
s01 = new TicTacToe();
//s01.addMouseListener(new MyMouseListener());
s02 = new TicTacToe();
s10 = new TicTacToe();
s11 = new TicTacToe();
s12 = new TicTacToe();
s20 = new TicTacToe();
s21 = new TicTacToe();
s22 = new TicTacToe();
//finish bottom raw
mainPanel.add(s00);
mainPanel.add(s01);
mainPanel.add(s02);
mainPanel.add(s10);
mainPanel.add(s11);
mainPanel.add(s12);
mainPanel.add(s20);
mainPanel.add(s21);
mainPanel.add(s22);
}
}
The return value of event.getPoint() is relative to the source component, a TicTacToe in this case, no the entire frame. Therefore, it will always be true for all the TictacToe's since they are all the same size.
Istead, use the Event.getSource() to determine the source object.
Also, it advisable to put all you TicTacToe objects into a TicTacToe[][] instead of listed separately.

Java repaint() not working

I am making a simple program to paint a graph and some points in it. The points should be made with methods while changing coordinates of the g.fillOval but actually its painting only the last point.
Here is the code:
import javax.swing.*;
import java.awt.*;
public class PointGraphWriter extends JPanel
{
JFrame korniza = new JFrame();
private int x;
private int y;
private int length;
private String OX;
private String OY;
private String emri;
private int y_height;
private int x_num;
public PointGraphWriter()
{
int width= 500;
korniza.setSize(width,width);
korniza.setVisible(true);
korniza.setTitle(emri);
korniza.getContentPane().add(this);
}
public void paintComponent(Graphics g)
{
g.drawLine(x,y,x+length,y);
g.drawLine(x,y,x,y-length);
g.drawString(OX,x+length, y+15);
g.drawString(OY,x-15,y-length);
g.drawString("0", x -15,y);
g.drawString("0", x,y+15);
g.fillOval(x_num,y-y_height-2, 4 ,4);
}
public void setTitle(String name)
{
emri= name;
this.repaint();
}
public void setAxes(int x_pos, int y_pos, int axis_length, String x_label, String y_label)
{
x= x_pos;
y=y_pos;
length= axis_length;
OX = x_label;
OY = y_label;
}
public void setPoint1(int height)
{
y_height=height;
x_num = x-2;
this.repaint();
}
public void setPoint2(int height)
{
y_height=height;
x_num = x + length/5-2;
this.repaint();
}
}
and here is the main method:
public class TestPlot
{
public static void main(String[] a)
{
PointGraphWriter e = new PointGraphWriter();
e.setTitle("Graph of y = x*x");
e.setAxes(50, 110, 90, "5", "30");
int scale_factor = 3;
e.setPoint1(0 * scale_factor);
e.setPoint2(1 * scale_factor);
}
}
Please have a look at this example. Something in lines of this, you might have to incorporate in your example, to make it work. Simply use a Collection to store what you have previously painted, and when the new thingy comes along, simply add that thingy to the list, and repaint the whole Collection again. As shown below :
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class RectangleExample {
private DrawingBoard customPanel;
private JButton button;
private Random random;
private java.util.List<Rectangle2D.Double> rectangles;
private ActionListener buttonActions =
new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Rectangle2D.Double rectangle = new Rectangle2D.Double(
(double) random.nextInt(100), (double) random.nextInt(100),
(double) random.nextInt(100), (double) random.nextInt(100));
rectangles.add(rectangle);
customPanel.setValues(rectangles);
}
};
public RectangleExample() {
rectangles = new ArrayList<Rectangle2D.Double>();
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Rectangle Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
customPanel = new DrawingBoard();
contentPane.add(customPanel, BorderLayout.CENTER);
button = new JButton("Create Rectangle");
button.addActionListener(buttonActions);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new RectangleExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class DrawingBoard extends JPanel {
private java.util.List<Rectangle2D.Double> rectangles =
new ArrayList<Rectangle2D.Double>();
public DrawingBoard() {
setOpaque(true);
setBackground(Color.WHITE);
}
public void setValues(java.util.List<Rectangle2D.Double> rectangles) {
this.rectangles = rectangles;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Rectangle2D.Double rectangle : rectangles) {
g.drawRect((int)rectangle.getX(), (int)rectangle.getY(),
(int)rectangle.getWidth(), (int)rectangle.getHeight());
}
System.out.println("WORKING");
}
}
See Custom Painting Approaches for examples of the two common ways to do painting:
Keep a List of the objects to be painted
Paint onto a BufferedImage
The approach you choose will depend on your exact requirement.

GUI that draws a string, rectangle, or oval when a button is pressed

For my assignment, I had to write a program that will either print some text, an oval, or a rectangle depending on which button is pressed at the top of the screen, however; when I press a button nothing happens, how would I fix this? This is my first GUI and I would appreciate any help! I'll end up needing the program to: start out with a rectangle, make whichever shape happens to be on screen stay in the center of the drawing area when the window gets resized, and my ovals and rectangles have to have half the width and height of the display area. I'm taking this one step at a time so I'll try to figure those out once I can actually get a shape on the screen, thanks :-).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class firstGUI extends JFrame
implements ActionListener
{
private boolean showText = false;
private boolean showRect = false;
private boolean showOval = false;
private JButton text;
private JButton oval;
private JButton rectangle;
private JPanel buttonPanel;
public firstGUI()
{
super("First GUI");
setSize(512, 512);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));
text = new JButton("Text");
text.addActionListener(this);
buttonPanel.add(text);
oval = new JButton("Oval");
oval.addActionListener(this);
buttonPanel.add(oval);
rectangle = new JButton("Rectangle");
rectangle.addActionListener(this);
buttonPanel.add(rectangle);
//JComponent drawArea = new JComponent();
drawStuff d = new drawStuff();
Container contentPane = this.getContentPane();
contentPane.add(buttonPanel, BorderLayout.NORTH);
contentPane.add(d);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source == text)
{
showText = true;
}
else if (source == oval)
{
showOval = true;
}
else if (source == rectangle)
{
showRect = true;
}
}
public void draw(Graphics g)
{
if(showText)
{
g.drawString("Hello", 0, 0);
}
else if (showOval)
{
g.drawOval(0, 0, 100, 100);
}
else if (showRect)
{
g.drawRect(0, 0, 100, 100);
}
}
public static void main(String [] args)
{
firstGUI myTest = new firstGUI();
myTest.setVisible(true);
}
}
class drawStuff extends JPanel
{
public void paint(Graphics g)
{
super.paint(g);
}
}
Try this. I added some repaint()s and helped you out with centering the objects being painted. I also changed the draw to paintComponent. This is what you should use when drawing on JComponents
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class firstGUI extends JFrame
implements ActionListener {
private boolean showText = false;
private boolean showRect = true;
private boolean showOval = false;
private JButton text;
private JButton oval;
private JButton rectangle;
private JPanel buttonPanel;
private DrawStuff drawPanel = new DrawStuff();
public firstGUI() {
super("First GUI");
setSize(512, 512);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 3));
text = new JButton("Text");
text.addActionListener(this);
buttonPanel.add(text);
oval = new JButton("Oval");
oval.addActionListener(this);
buttonPanel.add(oval);
rectangle = new JButton("Rectangle");
rectangle.addActionListener(this);
buttonPanel.add(rectangle);
Container contentPane = this.getContentPane();
contentPane.add(buttonPanel, BorderLayout.NORTH);
add(drawPanel);
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == text) {
showText = true;
repaint();
} else if (source == oval) {
showOval = true;
repaint();
} else if (source == rectangle) {
showRect = true;
repaint();
}
}
public static void main(String[] args) {
firstGUI myTest = new firstGUI();
myTest.setVisible(true);
}
class DrawStuff extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (showText) {
g.drawString("Hello", getHeight() / 2, getWidth() / 2);
showText = false;
} else if (showOval) {
g.drawOval(getWidth() / 4, getHeight() / 4, getWidth() / 2, getHeight() / 2);
showOval = false;
} else if (showRect) {
g.drawRect(getWidth() / 4, getHeight() / 4, getWidth() / 2, getHeight() / 2);
showRect = false;
}
}
}
}
You have all the building blocks, but after the button is pressed, the draw() method isn't called. Once you set your state (which item to draw) you need to re-draw()
Take a look at Performing Custom Painting.
Don't override paint but instead use paintComponent.
Take your draw method and move it to your drawStuff class. Call drawStuff from your paintComponent method
Set up some kind of flag (in drawStuff) that determines what should be painted
When you handle the button event, change the state flag on the panel and repaint the panel....
This will require your frame to have a reference to drawStuff
You may also want to take a look at and use Code Conventions for the Java Programming Language

Overlapping AWT lines and Swing JLabels

I have a problem in my application using line primitives and JLables. I try to explain it:
I have to draw a vehicle route using lines to represent roads and JLabels to represent cities. I need the use of JLabels because each JLabel has a Listener that shows a dialog with information about the city.
I redefine paint() method of my main JPanel. In that method I first in invoke the super.paint(), then I draw the lines and finally I add the Labels to the JPanel.
The problem is that the lines overlap the labels regardless the matter the order of painting them. Is there any suggestion?
You can also override paintComponent() or paintChildren() methods of the JPanel.
In the paintChildren() call your lines drawing and then super to draw JLabels.
anothe way should be
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class AddVertexDemo {
public AddVertexDemo() {
}
private static void createAndShowUI() {
JFrame frame = new JFrame("AddVertexDemo");
frame.getContentPane().add(new Gui().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
class DrawingPanel extends JPanel {
private static final int RADIUS = 6;
private static final long serialVersionUID = 1L;
private List<Shape> vertexList = new ArrayList<Shape>();
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (vertexList.size() > 1) {
Shape s0 = vertexList.get(0);
Shape s1 = null;
for (int i = 0; i < vertexList.size(); i++) {
s1 = vertexList.get(i);
drawConnectingLine(g, s0, s1);
s0 = s1;
}
s1 = vertexList.get(0);
//drawConnectingLine(g2, s0, s1);
}
for (Shape shape : vertexList) {
g2.setColor(Color.blue);
g2.fill(shape);
g2.setColor(Color.blue.darker().darker());
g2.draw(shape);
}
}
private void drawConnectingLine(Graphics g, Shape s0, Shape s1) {
Rectangle r0 = s0.getBounds();
Rectangle r1 = s1.getBounds();
int x0 = r0.x + r0.width / 2;
int y0 = r0.y + r0.height / 2;
int x1 = r1.x + r1.width / 2;
int y1 = r1.y + r1.height / 2;
g.drawLine(x0, y0, x1, y1);
}
public void addVertex(Point p) {
int x = p.x - RADIUS;
int y = p.y - RADIUS;
int w = 2 * RADIUS;
int h = w;
vertexList.add(new Ellipse2D.Double(x, y, w, h));
repaint();
}
public void removeVertex(Point p) {
if (vertexList.size() > 0) {
for (int i = vertexList.size() - 1; i >= 0; i--) {
if (vertexList.get(i).contains(p)) {
vertexList.remove(i);
repaint();
return;
}
}
}
}
}
class Gui {
private static final Dimension DRAWING_PANEL_SIZE = new Dimension(600, 500);
private JPanel mainPanel = new JPanel(new BorderLayout());
private DrawingPanel drawingPanel = new DrawingPanel();
private JToggleButton addVertexBtn = new JToggleButton("Add Vertex");
private JToggleButton removeVertexBtn = new JToggleButton("Remove Vertex");
Gui() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(addVertexBtn);
buttonPanel.add(removeVertexBtn);
DrawPanelMouseListener mouseListener = new DrawPanelMouseListener();
mouseListener.setDrawingPanel(drawingPanel);
mouseListener.setGui(this);
drawingPanel.addMouseListener(mouseListener);
drawingPanel.setPreferredSize(DRAWING_PANEL_SIZE);
drawingPanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(drawingPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
public JPanel getMainPanel() {
return mainPanel;
}
public boolean isAddingVertex() {
return addVertexBtn.isSelected();
}
public boolean isRemovingVertex() {
return removeVertexBtn.isSelected();
}
public void setAddingVertex(boolean addingVertex) {
addVertexBtn.setSelected(addingVertex);
}
public void setRemovingVertex(boolean removingVertex) {
removeVertexBtn.setSelected(removingVertex);
}
}
class DrawPanelMouseListener extends MouseAdapter {
private DrawingPanel drawingPanel;
private Gui gui;
public DrawPanelMouseListener() {
}
public void setGui(Gui gui) {
this.gui = gui;
}
public void setDrawingPanel(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
}
#Override
public void mousePressed(MouseEvent me) {
if (gui.isAddingVertex() && gui.isRemovingVertex()) {
gui.setAddingVertex(false);
gui.setRemovingVertex(false);
return;
}
if (gui.isAddingVertex()) {
drawingPanel.addVertex(me.getPoint());
gui.setAddingVertex(false);
}
if (gui.isRemovingVertex()) {
drawingPanel.removeVertex(me.getPoint());
gui.setRemovingVertex(false);
}
}
}
I'm not sure that this is the right way to do this but you can try this:
Create 2 panels. One for drawing lines and another for drawing buildings(labels).
Add both panels in LayeredPane of JFrame. Add panel with line in lower layer then panel with labels.
You can use LayeredPanes in other ways also to solve your problem. Learn more here: How to use Layered Panes in java

Categories

Resources