I thought i added my main code in this program but it did not recognize. Am I missing it? I get the error paint.Paintbrush class wasn't found in PaintBrush project. I'm not sure where I can include the main class in the beginning without getting an error being returned. Thank you for any advice or help given.
package PaintBrush;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
/**
*
* #author Olive
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Paintbrush extends Applet implements MouseListener,
MouseMotionListener,
ActionListener
{
// component declarations
Button blackButton;
Button redButton;
Button greenButton;
Button blueButton;
Button penButton;
Button lineButton;
Button eraserButton;
Button clearButton;
Button squareButton;
Button ovalButton;
Button fillSquareButton;
Button fillOvalButton;
Label colourTitle;
Label colourDisplay;
Label toolTitle;
Label toolDisplay;
// required variables to store settings
Color currentColour;
int toolType;
// variables to store interim coordinates
int oldX = -1;
int oldY = -1;
public void init()
{
// create all the buttons
blackButton = new Button("Black");
redButton = new Button("Red");
greenButton = new Button("Green");
blueButton = new Button("Blue");
penButton = new Button("Pen");
lineButton = new Button("Line");
eraserButton = new Button("Eraser");
clearButton = new Button("Clear");
squareButton = new Button("Square");
ovalButton = new Button("Oval");
fillSquareButton = new Button("F Square");
fillOvalButton = new Button("F Oval");
// add action listners for all the buttons
blackButton.addActionListener(this);
redButton.addActionListener(this);
greenButton.addActionListener(this);
blueButton.addActionListener(this);
penButton.addActionListener(this);
lineButton.addActionListener(this);
eraserButton.addActionListener(this);
clearButton.addActionListener(this);
squareButton.addActionListener(this);
ovalButton.addActionListener(this);
fillSquareButton.addActionListener(this);
fillOvalButton.addActionListener(this);
// create the button bar panel
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(6, 2));
buttonPanel.add(blackButton);
buttonPanel.add(redButton);
buttonPanel.add(greenButton);
buttonPanel.add(blueButton);
buttonPanel.add(penButton);
buttonPanel.add(lineButton);
buttonPanel.add(eraserButton);
buttonPanel.add(clearButton);
buttonPanel.add(squareButton);
buttonPanel.add(ovalButton);
buttonPanel.add(fillSquareButton);
buttonPanel.add(fillOvalButton);
// create the status bar panel
colourTitle = new Label("Colour: ");
currentColour = Color.black;
colourDisplay = new Label("Black");
toolTitle = new Label(" Selected Tool: ");
toolType = 0;
toolDisplay = new Label("Pen (Scribble)");
Panel statusPanel = new Panel();
statusPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
statusPanel.add(colourTitle);
statusPanel.add(colourDisplay);
statusPanel.add(toolTitle);
statusPanel.add(toolDisplay);
// arrange final panels in a border layout
this.setLayout(new BorderLayout());
this.add(buttonPanel, BorderLayout.WEST);
this.add(statusPanel, BorderLayout.NORTH);
// add mouse listners to applet
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
// event handling for when an action occurs (in this case, whenever
// a button is pressed)
public void actionPerformed(ActionEvent e)
{
// get the local graphics page to draw on
Graphics page = this.getGraphics();
// red button pressed: set the current colour to red
// and update the status display
if (e.getSource().equals(redButton))
{
currentColour = Color.red;
colourDisplay.setText("Red");
}
// blue button pressed: set the current colour to blue
// and update the status display
if (e.getSource().equals(blueButton))
{
currentColour = Color.blue;
colourDisplay.setText("Blue");
}
// green button pressed: set the current colour to green
// and update the status display
if (e.getSource().equals(greenButton))
{
currentColour = Color.green;
colourDisplay.setText("Green");
}
// black button pressed: set the current colour to black
// and update the status display
if (e.getSource().equals(blackButton))
{
currentColour = Color.black;
colourDisplay.setText("Black");
}
// pen button pressed: set the selected tool to '0'
// and update the status display
if (e.getSource().equals(penButton))
{
toolType = 0;
toolDisplay.setText("Pen (Scribble)");
}
// eraser button pressed: set the selected tool to '1'
// and update the status display
if (e.getSource().equals(eraserButton))
{
toolType = 1;
toolDisplay.setText("Eraser");
}
// square button pressed: set the selected tool to '2'
// and update the status display
if (e.getSource().equals(squareButton))
{
toolType = 2;
toolDisplay.setText("Square");
}
// oval button pressed: set the selected tool to '3'
// and update the status display
if (e.getSource().equals(ovalButton))
{
toolType = 3;
toolDisplay.setText("Oval");
}
// filled square button pressed: set the selected tool to '4'
// and update the status display
if (e.getSource().equals(fillSquareButton))
{
toolType = 4;
toolDisplay.setText("Filled Square");
}
// filled oval button pressed: set the selected tool to '5'
// and update the status display
if (e.getSource().equals(fillOvalButton))
{
toolType = 5;
toolDisplay.setText("Filled Oval");
}
// clear button pressed: get the size of the applet and draw
// a clearing rectangle over it, to clear the screen
if (e.getSource().equals(clearButton))
{
Dimension size = this.getSize();
page.clearRect(0, 0, size.width, size.height);
}
// line button pressed: set the selected tool to '6'
// and update the status display
if (e.getSource().equals(lineButton))
{
toolType = 6;
toolDisplay.setText("Line");
}
}
// event handling for when the mouse button is first pressed
public void mousePressed(MouseEvent e)
{
// store the coordinates for future reference
oldX = e.getX();
oldY = e.getY();
}
// event handling for when the mouse is dragged with the button
// held down
public void mouseDragged(MouseEvent e)
{
Graphics page = this.getGraphics();
// scribble tool: draw a line from the old coordinates to the
// new ones
if (toolType == 0)
{
page.setColor(currentColour);
page.drawLine(oldX, oldY, e.getX(), e.getY());
oldX = e.getX();
oldY = e.getY();
}
// eraser tool: clear a small rectangles' worth at the specified
// coordinate
if (toolType == 1)
{
page.clearRect(e.getX(), e.getY(), 10, 10);
page.setColor(currentColour);
}
}
// resolve method: used to swap two numbers around so the
// smaller is always in element 0, and the larger in element
// 1, of the returned array
public int[] resolve(int newC, int oldC)
{
int start, end;
if (newC < oldC)
{
start = newC;
end = oldC;
}
else
{
start = oldC;
end = newC;
}
int[] blah = {start, end};
return blah;
}
// event handling for when the mouse button is released
public void mouseReleased(MouseEvent e)
{
// get the applet's Graphics page
Graphics page = this.getGraphics();
// resolve the coordinates so that the smaller of the x and y
// coordinates can be picked out easily
int newX = e.getX();
int newY = e.getY();
int[] x = resolve(newX, oldX);
int[] y = resolve(newY, oldY);
// tool type 2: draw a rectangle
if (toolType == 2)
{
page.setColor(currentColour);
page.drawRect(x[0], y[0], (x[1] - x[0]), (y[1] - y[0]));
}
// tool type 3: draw an oval
if (toolType == 3)
{
page.setColor(currentColour);
page.drawOval(x[0], y[0], (x[1] - x[0]), (y[1] - y[0]));
}
// tool type 4: draw a filled rectangle
if (toolType == 4)
{
page.setColor(currentColour);
page.fillRect(x[0], y[0], (x[1] - x[0]), (y[1] - y[0]));
}
// tool type 5: draw a filled oval
if (toolType == 5)
{
page.setColor(currentColour);
page.fillOval(x[0], y[0], (x[1] - x[0]), (y[1] - y[0]));
}
// tool type 6: draw the line
if (toolType == 6)
{
page.setColor(currentColour);
page.drawLine(oldX, oldY, newX, newY);
}
}
// unused methods from listener interfaces
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
}
It looks like you're referencing the Paintbrush class in the paint package but the Paintbrush class itself declares package PaintBrush. You didn't show how you're telling NetBeans what applet to run. But try changing the package statement to package paint and see if that works.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Avoiding NullPointerException in Java
(66 answers)
Closed 1 year ago.
I am working on a paint app project and am working on an "undo" function. I have created an undrawHandler ActionEvent method to handle this and when I run my code my whole canvas is cleared instead of removing the last shape in the array list and I am getting an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "Circle.draw(javafx.scene.canvas.GraphicsContext)" because "this.shape" is null
Here is my code:
import javafx.application.Application;
import javafx.css.Size;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.control.TextField;
import javafx.scene.text.*;
import java.util.ArrayList;
public class PaintApp extends Application {
// TODO: Instance Variables for View Components and Model
private ArrayList<GeometricObject> shapes;
private GraphicsContext gc;
private TextField rField;
private TextField gField;
private TextField bField;
private TextField brushSize;
boolean drawCircle = true;
private ActionEvent e;
private Circle shape;
// TODO: Private Event Handlers and Helper Methods
private void mouseEventHandler(MouseEvent me) {
int red = 0;
int blue = 0;
int green = 0;
int size = 10;
String col;
// location for drawing
double x = me.getX();
double y = me.getY();
// color for drawing
try {
red = Integer.parseInt(rField.getText());
blue = Integer.parseInt(bField.getText());
green = Integer.parseInt(gField.getText());
size = Integer.parseInt(brushSize.getText());
// Check all these values are between 0 and 255 - if not update error label
}catch(NumberFormatException e)
{
// Update error label on screen to notify user of problem
return; // exit the method, don't keep going
}
// going to draw
GeometricObject shape;
if (drawCircle)
shape = new Circle(x,y, Color.rgb(red, green, blue), size);
else
shape = new Square(x,y, Color.rgb(red, green, blue), size);
shape.draw(gc);
shapes.add(shape); // add the shape to my arraylist to keep track of order drawn
}
private void undrawHandler(ActionEvent e)
{
int index = shapes.size() - 1; // remove the last item from the arraylist
shapes.remove(index);
gc.setFill(Color.WHITE);
gc.fillRect(0,0,800,400); // redraw the white rectangle ( the background)
// redraw the canvas with everything else
// redraw all shapes in the arrayList (loop)
if (!shapes.isEmpty())
{
shape.draw(gc);
}
}
/**
* This is where you create your components and the model and add event
* handlers.
*
* #param stage The main stage
* #throws Exception
*/
#Override
public void start(Stage stage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 800, 500); // set the size here
stage.setTitle("FX GUI Template"); // set the window title here
stage.setScene(scene);
// TODO: Add your GUI-building code here
// 1. Create the model
shapes = new ArrayList<>();
// 2. Create the GUI components
Canvas c = new Canvas(800,400); // used for Mouse events
gc = c.getGraphicsContext2D();
rField = new TextField();
gField = new TextField();
bField = new TextField();
brushSize = new TextField();
Label col = new Label("Color:");
Label size = new Label("Size:");
Button draw = new Button("Draw");
Button undraw = new Button("UnDraw");
Button circle = new Button("Circle");
circle.setOnMousePressed((event) -> {
drawCircle = true;
});
Button square = new Button("Square");
square.setOnMousePressed((event) -> {
drawCircle = false;
});
undraw.setOnMousePressed((event) -> {
undrawHandler(e);
});
// 3. Add components to the root
root.getChildren().addAll(rField, gField, bField,col,draw, circle, square,brushSize,size,undraw, c);
// 4. Configure the components (colors, fonts, size, location)
circle.relocate(10,430);
square.relocate(65,430);
rField.relocate(465,430);
rField.setPrefWidth(50);
bField.relocate(515,430);
bField.setPrefWidth(50);
gField.relocate(565,430);
gField.setPrefWidth(50);
size.relocate(340,430);
brushSize.relocate(370,430);
brushSize.setPrefWidth(50);
col.relocate(430,430);
draw.relocate(625,430);
undraw.relocate(675,430);
// 5. Add Event Handlers and do final setup
gc.setFill(Color.WHITE);
gc.fillRect(0,0,800,400);
c.addEventHandler(MouseEvent.MOUSE_PRESSED, this::mouseEventHandler);
c.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::mouseEventHandler);
// 6. Show the stage
stage.show();
}
/**
* Make no changes here.
*
* #param args unused
*/
public static void main(String[] args) {
launch(args);
}
}
I'm wondering why my applet isn't running. I'm using netbeans, and the program works fine with no errors, but I can't seem to get the applet screen to appear to test all the functions of my program.I was wondering if someone can point out what I am doing wrong in starting my applet up. I haven't done to many things with applets, so I'm quite curious why it isn't upping and running for me. I really didn't want to post the full code of my program, but I've no idea if there's an error in my code, or I'm just not doing the right thing to actually start the applet or something.
I do not get any errors while running my program, that applet simply does not appear and run in itself. Otherwise I get no errors from neatbeans while running my program.
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.FlowLayout;
public class Program7 extends JApplet implements ActionListener, ItemListener
{
//static varaibles
private static int GuiHeight = 90;
private static int Square = 50;
//gui varaibles
private JRadioButton drawSquare;
private JRadioButton mess;
private JTextField messageFeild;
private JCheckBox color;
private JButton button;
private JComboBox location;
//modable global varaibles
private int width, height, drawX, drawY;
private Color drawColor;
private String draw;
#Override
public void init()
{
//creating the panels
JPanel drawChoice;
JPanel drawSet;
//setting group onject to link certain buttons together
ButtonGroup ObjGroup;
//setting layout to make things look nice
setLayout(new FlowLayout());
//ibtializing other varaibles
width = 0;
height = 0;
drawX = 0;
drawY= 0;
drawColor = Color.BLACK;
draw = "";
//intialzing the gui interface
drawSquare = new JRadioButton("Draw a Square!");
mess = new JRadioButton("Write a Message!");
location = new JComboBox(new String[]{"", "Random Pick", "Top Left"});
color = new JCheckBox("Draw in Color!");
button = new JButton("Draw it!");
//linking the buttons together
ObjGroup = new ButtonGroup();
ObjGroup.add(drawSquare);
ObjGroup.add(mess);
//adding event handlers to the buttons
location.addItem(this);
button.addActionListener(this);
color.addItemListener(this);
drawSquare.addActionListener(this);
mess.addActionListener(this);
messageFeild = new JTextField(20);
//adding to the first paels
drawChoice = new JPanel();
drawChoice.add(drawSquare);
drawChoice.add(mess);
drawChoice.add(messageFeild);
//adding to the applet
add(drawChoice);
//adding to the second panel
drawSet = new JPanel();
drawSet.add(new JLabel("Select where to draw!"));
drawSet.add(location);
drawSet.add(color);
drawSet.add(button);
//adding to the applet
add(drawSet);
}
#Override
public void paint(Graphics g)
{
//calling super constructor
super.paint(g);
//getting width
width = getWidth();
height = getHeight();
//setting graphics color
g.setColor(drawColor);
if (location.getSelectedItem() != "")
{
//ifstatement checking for inputs
if(draw == "Square"||draw == "square"||draw == "SQUARE")
{
//creating rectange
g.fillRect(drawX, drawY, width, height);
}
if(draw == "Message"|| draw == "MESSAGE"||draw == "message")
{
//writing message
g.drawString(messageFeild.getText(), drawX, drawY);
}
}
}
#Override
public void actionPerformed(ActionEvent e)
{
//repainting
repaint();
}
#Override
public void itemStateChanged(ItemEvent e)
{
//if statement checking for the various changes being made by the user in the pograms interface
//if statement check checking to see if there's a square or to write a message
if (e.getSource() == drawSquare && e.getStateChange() == ItemEvent.SELECTED)
{
draw = "Square";
messageFeild.setEnabled(false);
}
if (e.getSource() == mess && e.getStateChange() == ItemEvent.SELECTED)
{
draw = "Message";
messageFeild.setEnabled(true);
}
//if statement set checking for locational input
if (e.getSource() == location)
{
if(location.getSelectedItem() == "Random Pick")
{
drawX=(int)(Math.random()*(width+1));
drawY=(int)(GuiHeight+ Math.random()*(height-GuiHeight+1));
}
if(location.getSelectedItem() == "Top Left")
{
drawX=0;
drawY=GuiHeight;
}
}
//if statement to check for color change
if(e.getSource()==color && e.getStateChange()==ItemEvent.SELECTED)
{
drawColor = Color.GREEN;
}
if(e.getSource()==color && e.getStateChange()==ItemEvent.DESELECTED)
{
drawColor = Color.BLACK;
}
}
public static void main(String[] args) {
}
}
This question already has an answer here:
How do I make my JWindow window always stay focused
(1 answer)
Closed 7 years ago.
First of all i don't know good english.
I want to make a window and have 2 labels and 2 fields. One label for x-coordinate and 1 for y-coordinate.Fields will show the x-y coordinates.
Coordinates are from mouse from full screen (meaning outside from window).
I prefer to be on clicking but i have read from other answers and questions that this will not act as we want (because it loses focus).So i tried not to be on clicking
I want help with my code because it has 2 problems-mistakes:
1) window can't close
2)when mouse is not moving fields take the same coordinates forever and i want take 1 time the coordinates and don't take the same until it moves.
here is the full code:
package mouseClick;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MouseEventDemo extends Frame implements MouseListener {
// Private variables
private TextField tfMouseX; // mouse-click-x
private TextField tfMouseY; // mouse-click-y
// Constructor
public MouseEventDemo() {
//handle the close-window button.
WindowDestroyer listener =new WindowDestroyer();
addWindowListener(listener);
setLayout(new FlowLayout()); // sets layout
// Label
add(new Label("X-Click: ")); // adds component
// TextField
tfMouseX = new TextField(10); // 10 columns
tfMouseX.setEditable(false); // read-only
add(tfMouseX); // adds component
// Label
add(new Label("Y-Click: ")); // adds component
// TextField
tfMouseY = new TextField(10);
tfMouseY.setEditable(false); // read-only
add(tfMouseY); // adds component
// fires the MouseEvent
addMouseListener(this);
setTitle("MouseEvent Demo"); // sets title
setSize(350, 100); // sets initial size
setVisible(true); // shows
}
public static void main(String[] args) {
new MouseEventDemo();
}
// MouseEvent handlers
public void mouseClicked(MouseEvent e) {
while (true){
tfMouseX.setText(Integer.toString(xmouse()));
tfMouseY.setText(Integer.toString(ymouse()));
}
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public class WindowDestroyer extends WindowAdapter {
public void windowClosing (WindowEvent e) {
System.exit(0);
}
}
public int xmouse() {
Point simiox = MouseInfo.getPointerInfo().getLocation();
int x= (int) simiox.getX();
return x;
}
public int ymouse() {
Point simioy = MouseInfo.getPointerInfo().getLocation();
int y=(int) simioy.getY();
return y;
}
}
in order to close the window, use
windowVariable.seDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
where windowVariable is the variable for you JFrame
EDIT:
For returning the value only once, try using a for loop and a hasMoved boolean. For instance,
for (int i = 0; i < 1; i++){
tfMouseX.setText(Integer.toString(xmouse()));
if (hasMoved == true)
i = -1;
}
then do the same for the y.
this basically checks to see if the mouse has moved, and if it has not, it will set the label only once. If it has, it will update the label.
I am writing a Main-menu + Network traffic monitor. My system runs Linux Cinnamon Mint.
The problem is that the application's title always appears over the menu.
When I click over the iconized window, JFrame opens and the JPopoupMenu appears over it.
While the mouse pointer is inside the panel, the title hovers above the iconized window, as it should, but when I move it over the menu it doesn't disappear.
The mouse pointer wasn't captured but it was inside the panel (over the iconized window) in the left picture and over the menu in the right one.
If I do the same, but without showing the menu (JFrame's window with the same size as the menu), the title only appears when the mouse pointer is inside the panel.
I have tried different components for 'popupMenu.setInvoker(Component)' but in the few cases where the problem disappears the menu loses focus.
Thank you beforehand for your help.
Here is a SSCCE (Main.java) that I cobbled together so you can test the code:
// To run: javac Main.java; java Main
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.WindowConstants;
/**
*
* #author Manuel Iglesias Alonso glesialo#gmail.com
*/
public class Main extends JFrame {
private final MainMenu mainMenu;
private boolean menuPopupEnabled;
public Main(ImageIcon icon, File rootMenuDirectory) {
super();
menuPopupEnabled = false;
setIconImage(icon.getImage());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowDeiconified(WindowEvent e) {
super.windowDeiconified(e);
if (menuPopupEnabled) {
mainMenu.popup(MouseInfo.getPointerInfo().getLocation());
}
}
});
mainMenu = new MainMenu(this, rootMenuDirectory);
pack(); // Before setPreferredSize: smaller window size.
setPreferredSize(new Dimension(0, 0)); // Window is always hidden behind menu, the smaller the better.
setVisible(true);
}
private class MainMenu {
private final int panelHeight = 25;
private final int iconizedWindowWidthPanelHeightRatio = 5; // Iconized window's width / Iconized window' height
private final JFrame frame;
private final File rootMenuDirectory;
private final Rectangle graphicsBounds;
private PopupMenuInFrame popupMenu;
private class PopupMenuInFrame extends JPopupMenu {
#Override
protected void firePopupMenuWillBecomeInvisible() {
super.firePopupMenuWillBecomeInvisible();
frame.setExtendedState(JFrame.ICONIFIED);
}
}
/**
*
* #param rootMenuDirectory Directory where menu files are to be found.
*/
public MainMenu(JFrame frame, File rootMenuDirectory) {
this.frame = frame;
this.rootMenuDirectory = rootMenuDirectory;
graphicsBounds = frame.getGraphicsConfiguration().getBounds();
}
private void newMenu() {
popupMenu = new PopupMenuInFrame();
JMenuItem menuItem = new JMenuItem("1st popup menu item");
menuItem.setToolTipText("1st ToolTip");
popupMenu.add(menuItem);
menuItem = new JMenuItem("2nd popup menu item");
menuItem.setToolTipText("2nd popup menu item ToolTip");
popupMenu.add(menuItem);
menuItem = new JMenuItem("3rd A popup menu item");
menuItem.setToolTipText("menu item ToolTip");
popupMenu.add(menuItem);
menuItem = new JMenuItem("4th popup menu item");
menuItem.setToolTipText("4th popup menu item menu item ToolTip");
popupMenu.add(menuItem);
menuItem = new JMenuItem("5th popup menu item");
menuItem.setToolTipText("ToolTip");
popupMenu.add(menuItem);
menuItem = new JMenuItem("6th popup menu item");
menuItem.setToolTipText("popup menu item menu item ToolTip");
popupMenu.add(menuItem);
}
public void popup(Point mousePointerPosition) {
Point menuPosition;
newMenu();
popupMenu.setInvoker(frame.getContentPane());
menuPosition = new Point(mousePointerPosition.x, mousePointerPosition.y);
if (mousePointerPosition.x < iconizedWindowWidthPanelHeightRatio * panelHeight) { //If pointer near leftmost border (within width of iconized window).
if (mousePointerPosition.y < (panelHeight + 1)
|| mousePointerPosition.y > (graphicsBounds.height - panelHeight - 1)) { //If pointer inside a top or bottom panel
menuPosition.x = 1; // Position: near left border.
}
}
if (mousePointerPosition.y < (panelHeight + 1)) { //If pointer inside a top panel (within panel's height + 1)
menuPosition.y = panelHeight + 1; //Menu's top edge just below the panel's lower edge.
} else {
if (mousePointerPosition.y > (graphicsBounds.height - panelHeight - 1)) { //If pointer inside a bottom panel (within panel's height + 1)
menuPosition.y = graphicsBounds.height - popupMenu.getPreferredSize().height - panelHeight - 1; //Menu's lower edge just above the panel's upper edge.
}
}
frame.setLocation(menuPosition.x + 5, menuPosition.y + 5); // + 5 to make sure window is hidden behind popupMenu.
popupMenu.setLocation(menuPosition.x, menuPosition.y);
popupMenu.setVisible(true);
}
}
public static void main(String[] args) {
final ImageIcon icon;
final File rootMenuDirectory;
icon = new ImageIcon();
rootMenuDirectory = new File("");
Main frame = new Main(icon, rootMenuDirectory);
frame.setTitle("Test title");
try {
Thread.sleep(500);
} catch (Exception e) {
}
if (!GraphicsEnvironment.isHeadless()) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setExtendedState(JFrame.ICONIFIED); // Start iconified. If setExtendedState used out of run(), window's events are blocked.
frame.menuPopupEnabled = true; // Menu can pop from now on.
}
});
} else {
System.exit(1);
}
}
}
PS: I have modified the SSCCE adding tool-tips to the menu items. There is another problem: Sometimes (while moving the mouse pointer, up and down, over the menu items) the tool-tips do not appear complete:
Nobody helps? :-(
I have almost finished the application. I have added an extra menu item, 'MainMenu: About', so that that item is the only part covered by the damn vindow title (title disappears once the menu operates: submenus, tooltips...). The problem with incomplete tooltips also happens with oracle' tutorial examples (if I add tooltips) so it has nothing to do with my code.
Here is a picture of the running menu (It will move to just over the iconized window when it is on the far left of the panel: first startup application):
The application sends an 'sticky' hint to the Window Manager and the window appears in all workspaces.
I was given this code by my professor and it should run as is.
I compile it and get the following error.
java.lang.NullPointerException
at WholePanel.<init>(WholePanel.java:59)
at Assignment7.init(Assignment7.java:19)
at sun.applet.AppletPanel.run(AppletPanel.java:435)
at java.lang.Thread.run(Thread.java:744)
I have no idea why this is happening. Here are my classes.
I compiled and ran the code, got the error, tried commenting some things out and still nothing. I have programmed some previous applets and they run fine.
Assignment7
import javax.swing.*;
public class Assignment7 extends JApplet
{
public void init()
{
// create a WholePanel object and add it to the applet
WholePanel wholePanel = new WholePanel();
getContentPane().add(wholePanel);
//set applet size to 400 X 400
setSize (400, 400);
}
}
Whole Panel
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
public class WholePanel extends JPanel
{
private Color currentColor;
private CanvasPanel canvas;
private JPanel primary, buttonPanel, leftPanel;
private JButton erase, undo;
private ArrayList rectList, tempList;
private JRadioButton[] colorRButtons;
private Color[] colors;
private int x1, y1, x2, y2, x3, y3;
private boolean mouseDragged = false;
//Constructor to instantiate components
public WholePanel()
{
//default color to draw rectangles is black
currentColor = Color.black;
rectList = new ArrayList();
//create buttons
//create radio buttons for 5 colors
//black will be chosen by default
colorRButtons = new JRadioButton[5];
colorRButtons[0] = new JRadioButton("black", true);
//store 5 colors in an array
//group radio buttons so that when one is selected,
//others will be unselected.
ButtonGroup group = new ButtonGroup();
for (int i=0; i<colorRButtons.length; i++)
group.add(colorRButtons[i]);
//add ColorListener to radio buttons
ColorListener listener = new ColorListener();
for (int i=0; i<colorRButtons.length; i++)
colorRButtons[i].addActionListener(listener);
//primary panel contains all radiobuttons
primary = new JPanel(new GridLayout(5,1));
for (int i=0; i<colorRButtons.length; i++)
primary.add(colorRButtons[i]);
//canvas panel is where rectangles will be drawn, thus
//it will be listening to a mouse.
canvas = new CanvasPanel();
canvas.setBackground(Color.white);
canvas.addMouseListener(new PointListener());
canvas.addMouseMotionListener(new PointListener());
JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, canvas);
setLayout(new BorderLayout());
add(sp);
}
//ButtonListener defined actions to take in case "Create",
//"Undo", or "Erase" is chosed.
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
}
} // end of ButtonListener
// listener class to set the color chosen by a user using
// the radio buttons.
private class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == colorRButtons[0])
currentColor = colors[0];
else if (event.getSource() == colorRButtons[1])
currentColor = colors[1];
else if (event.getSource() == colorRButtons[2])
currentColor = colors[2];
else if (event.getSource() == colorRButtons[3])
currentColor = colors[3];
else if (event.getSource() == colorRButtons[4])
currentColor = colors[4];
}
}
//CanvasPanel is the panel where rectangles will be drawn
private class CanvasPanel extends JPanel
{
//this method draws all rectangles specified by a user
public void paintComponent(Graphics page)
{
super.paintComponent(page);
//draw all rectangles
for (int i=0; i < rectList.size(); i++)
{
// ((Rect) rectList.get(i)).draw(page);
}
//draw an outline of the rectangle that is currently being drawn.
if (mouseDragged == true)
{
page.setColor(currentColor);
//Assume that a user will move a mouse only to left and down from
//the first point that was pushed.
page.drawRect(x1, y1, x3-x1, y3-y1);
}
}
} //end of CanvasPanel class
// listener class that listens to the mouse
public class PointListener implements MouseListener, MouseMotionListener
{
//in case that a user presses using a mouse,
//record the point where it was pressed.
public void mousePressed (MouseEvent event)
{
//after "create" button is pushed.
}
//mouseReleased method takes the point where a mouse is released,
//using the point and the pressed point to create a rectangle,
//add it to the ArrayList "rectList", and call paintComponent method.
public void mouseReleased (MouseEvent event)
{
}
//mouseDragged method takes the point where a mouse is dragged
//and call paintComponent nethod
public void mouseDragged(MouseEvent event)
{
canvas.repaint();
}
public void mouseClicked (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseMoved(MouseEvent event) {}
} // end of PointListener
} // end of Whole Panel Class
It seems you create only one colorRButtons, but trying to use all five.
So in colorRButtons[0] is not null, but all others are null and using of addActionListener for them is impossible.
In this loop
for (int i=0; i<colorRButtons.length; i++)
colorRButtons[i].addActionListener(listener);
you are accessing an array of colorRButtons, but only the first one
colorRButtons[0] = new JRadioButton("black", true);
has been created.