using eclipse sdk - java

I made a program to draw shapes and change their colors. I got the reset button to reset to default shapes and colors but can not get it to clear the shapes from the canvas. How do I do that? Here is my code:
// Color Clear choice box
Choice colorChoice;
// the canvas
DrawCanvas canvas;
/**
* Constructor
*/
public Draw() {
super("Java Draw");
setLayout(new BorderLayout());
// create panel for controls
Panel topPanel = new Panel(new GridLayout(3, 0));
add(topPanel, BorderLayout.NORTH);
// create button control
Panel buttonPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
topPanel.add(buttonPanel);
circle = new Button("Circle");
buttonPanel.add(circle);
roundRec = new Button("Rounded Rectangle");
buttonPanel.add(roundRec);
threeDRec = new Button("3D Rectangle");
buttonPanel.add(threeDRec);
// add button listener
circle.addActionListener(this);
roundRec.addActionListener(this);
threeDRec.addActionListener(this);
Panel buttonPanel1 = new Panel(new FlowLayout(FlowLayout.LEFT));
topPanel.add(buttonPanel1);
lines = new Button("Lines");
buttonPanel1.add(lines);
squares = new Button("Square");
buttonPanel1.add(squares);
ovals = new Button("Ovals");
buttonPanel1.add(ovals);
lines.addActionListener(this);
squares.addActionListener(this);
ovals.addActionListener(this);
// create panel for color choices
Panel colorPanel = new Panel(new FlowLayout(FlowLayout.LEFT));
topPanel.add(colorPanel);
Label label = new Label("Filled Color:");
colorPanel.add(label);
colorChoice = new Choice();
for(int i=0; i<COLOR_NAMES.length; i++) {
colorChoice.add(COLOR_NAMES[i]);
}
colorPanel.add(colorChoice);
colorChoice.addItemListener(this);
// create reset button
Button resetButton = new Button("Reset");
colorPanel.add(resetButton);
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
colorChoice.select(0); // reset color choice box
canvas.setFilledColor(COLORS[0]); // reset color used
canvas.setShape(DrawCanvas.CIRCLE); // reset shape
}
});
// create the canvas
canvas = new DrawCanvas();
add(canvas, BorderLayout.CENTER);
}// end of constructor
/**
* Implementing ActionListener
*/
public void actionPerformed(ActionEvent event) {
if(event.getSource() == circle) { // circle button
canvas.setShape(DrawCanvas.CIRCLE);
}
else if(event.getSource() == roundRec) { // rounded rectangle button
canvas.setShape(DrawCanvas.ROUNDED_RECTANGLE);
}
else if(event.getSource() == threeDRec) { // 3D rectangle button
canvas.setShape(DrawCanvas.RECTANGLE_3D);
}
}
/**
* Implementing ItemListener
*/
public void itemStateChanged(ItemEvent event) {
Color color = COLORS[colorChoice.getSelectedIndex()];
canvas.setFilledColor(color);
}
/**
* the main method
*/
public static void main(String[] argv) {
// Create a frame
Draw frame = new Draw();
frame.setSize(WIDTH, HEIGHT);
frame.setLocation(150, 100);
// add window closing listener
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});
// Show the frame
frame.setVisible(true);
}
}

Assuming a DrawCanvas extends JPanel, you need to call repaint at the end of your reset listener.

Related

How do I delete an image inside a JLabel by right clicking my mouse

I'm working on an Animal Project and I want to improve the project with the MouseListener functions, but I cannot find out how to do this specific bit and I've looked everywhere. Here is my code so you get a good idea at what I'm doing.
Main Class
public class Animals {
public static void main(String[] args) {
JFrame application = new JFrame("Animal Project");
GUI graphicalInterface = new GUI();
application.add(graphicalInterface);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setLocation(200, 200);
application.pack();
application.setVisible(true);
application.setResizable(false);
}
Sub Class
public class GUI extends JPanel implements ActionListener {
private JButton animalOption = new JButton();
private JButton save = new JButton();
private JButton load = new JButton();
private JButton clear = new JButton();
private JPanel buttonPanel;
private JPanel imagePanel;
private ImageIcon bear;
private ImageIcon tiger;
private ImageIcon lion;
private JLabel imageBlock1;
private JLabel imageBlock2;
private JLabel imageBlock3;
private int choice;
private int count = 1;
private JLabel currImageBlock = null;
GUI() {
Border blackline = BorderFactory.createLineBorder(Color.black);
//create button panel
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(100, 230));
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.white);
buttonPanel.setBorder(blackline);
imagePanel = new JPanel(new GridLayout(3, 3));
imagePanel.setPreferredSize(new Dimension(500, 500));
imagePanel.setOpaque(true);
imagePanel.setBackground(Color.white);
imagePanel.setBorder(blackline);
imageBlock1 = new JLabel();
imageBlock1.setPreferredSize(new Dimension(100, 100));
imageBlock1.setOpaque(true);
imageBlock1.setBackground(Color.white);
imageBlock1.setBorder(blackline);
imageBlock2 = new JLabel();
imageBlock2.setPreferredSize(new Dimension(100, 100));
imageBlock2.setOpaque(true);
imageBlock2.setBackground(Color.white);
imageBlock2.setBorder(blackline);
imageBlock3 = new JLabel();
imageBlock3.setPreferredSize(new Dimension(100, 100));
imageBlock3.setOpaque(true);
imageBlock3.setBackground(Color.white);
imageBlock3.setBorder(blackline);
bear = new ImageIcon("Bear.png");
tiger = new ImageIcon("Tiger.png");
lion = new ImageIcon("Lion.png");
animalOption = new JButton();
//add action listener to each button
animalOption.addActionListener(this);
//set button size
animalOption.setPreferredSize(new Dimension(100, 50));
//set text for each button
animalOption.setText("Animal");
animalOption.setToolTipText("press to select your animal");
//add buttons to gui
buttonPanel.add(animalOption);
save = new JButton();
//add action listener to each button
save.addActionListener(this);
//set button size
save.setPreferredSize(new Dimension(100, 50));
//set text for each button
save.setText("Save");
save.setToolTipText("press to save your selection");
//add buttons to gui
buttonPanel.add(save);
load = new JButton();
//add action listener to each button
load.addActionListener(this);
//set button size
load.setPreferredSize(new Dimension(100, 50));
//set text for each button
load.setText("Load");
load.setToolTipText("press to load your selection");
//add buttons to gui
buttonPanel.add(load);
clear = new JButton();
//add action listener to each button
clear.addActionListener(this);
//set button size
clear.setPreferredSize(new Dimension(100, 50));
//set text for each button
clear.setText("Clear");
clear.setToolTipText("press to clear your selection");
//add buttons to gui
buttonPanel.add(clear);
this.add(buttonPanel);
this.add(imagePanel);
imagePanel.add(imageBlock1);
imagePanel.add(imageBlock2);
imagePanel.add(imageBlock3);
}
public void actionPerformed(ActionEvent e) {
if (count == 1) {
currImageBlock = imageBlock1;
} else if (count == 2) {
currImageBlock = imageBlock2;
} else if (count == 3) {
currImageBlock = imageBlock3;
} else if (count > 3 && e.getSource().equals(animalOption)) {
JOptionPane.showMessageDialog(imagePanel, "Your choices have exceeded, please press clear.");
}
if (e.getSource().equals(animalOption) && count < 4) {
choice = selectAnimal();
if (choice == 1) {
currImageBlock.setIcon(bear);
currImageBlock.setToolTipText("This is a bear");
} else if (choice == 2) {
currImageBlock.setIcon(tiger);
currImageBlock.setToolTipText("This is a tiger");
} else if (choice == 3) {
currImageBlock.setIcon(lion);
currImageBlock.setToolTipText("This is a lion");
}
chooseNumber();
count++;
}
if (e.getSource().equals(clear)) {
imageBlock1.setIcon(null);
imageBlock2.setIcon(null);
imageBlock3.setIcon(null);
imageBlock1.revalidate();
imageBlock2.revalidate();
imageBlock3.revalidate();
count = 1;
}
}
static int selectAnimal() {
int animal = 0;
String theAnimal = JOptionPane.showInputDialog("Please enter animal, type 1 for bear, type 2 for tiger, type 3 for lion");
animal = Integer.parseInt(theAnimal);
return animal;
}
And this is what it looks like when I run the code and after I've selected which Animal I want
I have a clear all button where if I click it, it clears all the images in inside the imageBlock Jlabel, however I want to add a feature where if I right click on the specific JLabel the image and all its contents will be deleted inside that specific JLabel. Any help would really be appreciated.
This example code shows how a mouse listener can be used to perform an action (in this case - remove) on an image set as icon within a JLabel. Note a MouseAdapter is used in the code but a MouseListener interface can be implemented with similar result.
Other ways of performing this function:
Select an image label and click a button to remove it.
Open a context or pop-up menu with remove image menu option - when the image label is right-clicked upon.
The example code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ImageLabelAction {
private JLabel imageBlock;
private ImageIcon koala = new ImageIcon("koala.jpg");
public static void main(String [] args) {
new ImageLabelAction().gui();
}
private void gui() {
JFrame frame = new JFrame();
frame.setTitle("Frame with Image Label");
imageBlock = new JLabel();
imageBlock.setPreferredSize(new Dimension(100, 100));
imageBlock.setOpaque(true);
imageBlock.setBackground(Color.white);
imageBlock.setBorder(BorderFactory.createLineBorder(Color.black));
imageBlock.setIcon(koala);
imageBlock.addMouseListener(new PictureRemoveListener());
frame.add(imageBlock);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(250, 250);
frame.setVisible(true);
}
private class PictureRemoveListener extends MouseAdapter {
#Override public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
imageBlock.setIcon(null);
}
}
}
}
You could set a mouse listener to just move it way out of the frame when right clicked. Or you can make a boolean if mouse is clicked set true and only show that object if the boolean is true, so where you set the image from the file only run that code if right mouse button hasn't been clicked
Something like the following pseudo code:
imageBlock1.addMouseListener(new MouseAdapter() {
public void mouseClicked (MouseEvent e) {
// use flags to figure out if it is right mouse click
imageBlock1.setIcon(null);
}
});
Do this for imageBlock2, 3, 4 etc.
It has been a while but something along those lines could do what you are asking.

Move button on JFrame Java

i have a task to make an application wich will do the following:
If I move a mouse the coordinates should be shown on the status bar
If mouse is clicked then the only one button which is on a JPanel should move to coordinates of click
So the problem is that when i do mouse click - it's fine, button moves to coord's of click, but when i start moving mouse the button comes back to the original position
public class Window extends JFrame {
private JLabel statusBar;
private JPanel mainPanel, statusBarPanel;
JButton button;
public Window()
{
super("Window");
setSize(400,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel=new JPanel();
statusBarPanel = new JPanel();
statusBar=new JLabel("Coords: ");
add(statusBarPanel, BorderLayout.SOUTH);
add(mainPanel,BorderLayout.CENTER);
mainPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
statusBarPanel.add(statusBar,BorderLayout.CENTER);
button = new JButton("Default text");
mainPanel.add(button);
MyMouseListener myMouseListener=new MyMouseListener();
mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
statusBar.setText("Coords: ("+e.getX()+":"+e.getY()+")");
}
});
mainPanel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
button.setLocation(e.getX()-button.getWidth()/2,e.getY()-button.getHeight()/2);
}
});
mainPanel.setFocusable(true);
setVisible(true);
}
}
This is one of the rare cases where you don't want your panel to have a layout manager, since you need absolute positioning.
JPanel has a default layout manager which is a FlowLayout, and your call to setLocation will only have a temporary effect until the panel revalidates its content and places things where they were supposed to be initially.
See the following example with comments, it should give you the general idea :
public class Window extends JFrame {
private final JLabel statusBar;
private final JPanel mainPanel, statusBarPanel;
JButton button;
public Window() {
super("Window");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(null);// no layout for absolute positioning
statusBarPanel = new JPanel();
statusBar = new JLabel("Coords: ");
add(statusBarPanel, BorderLayout.SOUTH);
add(mainPanel, BorderLayout.CENTER);
mainPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
statusBarPanel.add(statusBar, BorderLayout.CENTER);
button = new JButton("Default text");
// place the button "manually"
button.setBounds((int) (400 - button.getPreferredSize().getWidth()) / 2, 0,
(int) button.getPreferredSize().getWidth(),
(int) button.getPreferredSize().getHeight());
mainPanel.add(button);
mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(final MouseEvent e) {
super.mouseMoved(e);
statusBar.setText("Coords: (" + e.getX() + ":" + e.getY() + ")");
}
});
mainPanel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent e) {
super.mouseClicked(e);
button.setLocation((int) (e.getX() - button.getPreferredSize().getWidth() / 2),
(int) (e.getY() - button.getPreferredSize().getHeight() / 2));
}
});
mainPanel.setFocusable(true);
setVisible(true);
}
}

Repaint a circle

I want to repaint a circle whenever a button is pressed.
Currently, I have it whenever I press a button, it prints to the console what button I pressed. For example, if I press the "Paint Red" button, I want it to fill the circle with red, and the same with the other colors as well. I'm trying to wrap my head around the whole paint/paintComponent difference.
This is what I have so far...
public class testCircle extends JPanel {
public void paint(Graphics g)
{
setSize(500,500);
int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
g.setColor(randomColor);
g.drawOval(75, 100, 200,200);
g.fillOval(75, 100, 200, 200);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(400, 400);
testCircle circlePanel = new testCircle();
frame.add(circlePanel);
JButton redButton = new JButton("Paint Red");
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Red Button Pressed!");
}
});
JButton blueButton = new JButton("Paint Blue");
blueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Blue Button Pressed!");
}
});
JButton greenButton = new JButton("Paint Green");
greenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Green Button Pressed!");
}
});
redButton.setPreferredSize(new Dimension(100,100));
blueButton.setPreferredSize(new Dimension(100,100));
greenButton.setPreferredSize(new Dimension(100,100));
frame.setLayout(new FlowLayout());
frame.add(redButton);
frame.add(blueButton);
frame.add(greenButton);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Consider these changes to your code:
As discussed here, Swing programs should override paintComponent() instead of overriding paint().
Give your panel an attribute for currentColor.
private Color currentColor;
Let each button's ActionListener set currentColor and invoke repaint().
currentColor = color;
repaint();
Use Action for to encapsulate your program's functionality.
A complete example is examined here.
You don't trigger a "repaint" anywhere in your code. That should work:
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("Red Button Pressed!");
frame.invalidate();
frame.validate();
}
});

How to achieve this functionality?

I have a JPanel object say panel that holds a reference to a JPanel object.
Suppose panel points to panel-1 and on some click (action), it should point to panel-2 and panel-2 must replace panel-1 on the JFrame object frame.
However, it doesn't update. I tried the following, but in vain:
frame.repaint();
panel.revalidate();
I think this code does what you try to do. It has a JPanel that holds either a green JPanel or a red JPanel and a Button to do the flip.
public class Test{
boolean isGreen; // flag that indicates the content
public Test(){
JFrame f = new JFrame ("Test"); // the Frame
f.setLayout (new BorderLayout());
JPanel p = new JPanel(new BorderLayout()); // the content Panel
f.add(p, BorderLayout.CENTER);
JPanel green = new JPanel(); // the green content
green.setBackground(Color.GREEN);
JPanel red = new JPanel(); // the red content
red.setBackground(Color.RED);
p.add(green); // init with green content
isGreen = true;
JButton b = new JButton ("flip"); // the flip button
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.removeAll(); // remove all of old content
if(isGreen){
p.add(red); // set new red content
isGreen = false;
} else {
p.add(green); // set new green content
isGreen = true;
}
p.revalidate(); // invalidate content panel so component tree will be reconstructed
f.repaint(); // repaint the frame so the content change will be seen
}
});
f.add (b, BorderLayout.SOUTH);
f.pack();
f.setSize(250,330);
f.setVisible (true);
}
public static void main (String [] args){
new Test();
}
}

Assistance With KeyEvent

I am making a platformer game for a class project and so far all I have been able to do is add the chicken character to the game. I need to be able to have him move forward on the press of "D" or right arrow. My code is:
public class Main extends JFrame {
public Main(){
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
setSize(1440, 500);
add(new ContentPanel1());
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String arg[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
class coordinate {
public static int x;
public static int y;
}
class ContentPanel1 extends JPanel{
Image back = Toolkit.getDefaultToolkit().getImage("level0.gif");
Image chick = Toolkit.getDefaultToolkit().getImage("chicken.gif");
ContentPanel1() {
MediaTracker mt = new MediaTracker(this);
mt.addImage(back, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
coordinate.x = 20;
coordinate.y = 321;
super.paintComponent(g);
int imwidth = back.getWidth(null);
int imheight = back.getHeight(null);
g.drawImage(back, 1, 1, null);
g.drawImage(chick, coordinate.x, coordinate.y, null);
}
public void MoveDirection(KeyEvent e, Graphics g) {
coordinate.x = 20;
coordinate.y = 321;
super.paintComponent(g);
int key = e.getKeyCode();
if(key == 68) {
coordinate.x += 1;
g.drawImage(chick, coordinate.x, coordinate.y, null);
}
}
}
The main trouble I have been having with my code is the bit at the end with the MoveDirection method. The way I have it going is by adding a new chicken to the frame (This was mainly due to the fact that I was just testing to see if the code worked). Is there a better way to do that too?
Start by taking a look at How to Use Key Bindings
NEVER call super.paintComponent(g); (or paintComponent(g);) directly from outside the context of the paintComponent method, there is a lot more to painting then just painting the component background. See Painting in AWT and Swing and Performing Custom Painting for more details. Instead, simply call repaint when you want to, well, repaint the component.
The use of MediaTracker is out of date and you should be using the ImageIO API instead, which will block automatically while reading the image. See Reading/Loading an Image for more details
Don't use Toolkit.getDefaultToolkit().getScreenSize() in combination with JFrame#setSize, the getScreenSize method does not take into account things like the task bar or dock of some OS's, instead use the JFrame#setExtendedState and pass it JFrame.MAXIMIZED_BOTH
frame.setLocale(null); isn't doing what you think it is

Categories