JMenuBar repaints my JPanel - java

I am programming a small paint application, the problem is, when I clic on my Menu and then move the mouse out and clic on the panel to continiue painting, the panel erases everything I painted and changes the background too ... here's my code :
Frame's Code :
public class Ardoise extends JFrame {
private JMenuBar menu = new JMenuBar();
private JToolBar toolbar = new JToolBar();
private JMenu file = new JMenu("Fichier");
private JMenu edit = new JMenu("Edition");
private JMenu about = new JMenu("About");
private JMenu shape = new JMenu("Forme du curseur");
private JMenu color = new JMenu("Couleur du curseur");
private JMenuItem clear = new JMenuItem("Effacer");
private JMenuItem quit = new JMenuItem("Quitter");
private JMenuItem rond = new JMenuItem("Rond");
private JMenuItem carre = new JMenuItem("Carre");
private JMenuItem rouge = new JMenuItem("Rouge");
private JMenuItem bleu = new JMenuItem("Bleu");
private JMenuItem noir = new JMenuItem("Noir");
private JButton rougeButton = new JButton(new ImageIcon("rouge.jpg"));
private JButton bleuButton = new JButton(new ImageIcon("bleu.jpg"));
private JButton noirButton = new JButton(new ImageIcon("noir.jpg"));
private JButton formecarreeButton = new JButton(new ImageIcon("formecarree.png"));
private JButton formerondeButton = new JButton(new ImageIcon("formeronde.png"));
private JPanel container = new JPanel();
private Panneau pan = new Panneau();
private ColorListener cListener = new ColorListener();
public Ardoise(){
this.setTitle("Paint");
this.setSize(700,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
initComposants();
this.setVisible(true);
}
private void initComposants(){
file.add(clear);
file.addSeparator();
file.add(quit);
file.setMnemonic('F');
clear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,KeyEvent.CTRL_DOWN_MASK));
quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,KeyEvent.CTRL_DOWN_MASK));
shape.add(rond);
shape.add(carre);
color.add(rouge);
color.add(bleu);
color.add(noir);
edit.add(shape);
edit.add(color);
edit.setMnemonic('E');
menu.add(file);
menu.add(edit);
toolbar.add(formecarreeButton);
toolbar.add(formerondeButton);
toolbar.addSeparator();
toolbar.add(noirButton);
toolbar.add(rougeButton);
toolbar.add(bleuButton);
pan.addMouseMotionListener(new PaintListener1());
pan.addMouseListener(new PaintListener2());
clear.addActionListener(new ClearListener());
rougeButton.addActionListener(cListener);
bleuButton.addActionListener(cListener);
noirButton.addActionListener(cListener);
container.setLayout(new BorderLayout());
container.add(toolbar,BorderLayout.NORTH);
container.add(pan,BorderLayout.CENTER);
this.setContentPane(container);
this.setJMenuBar(menu);
}
class PaintListener1 implements MouseMotionListener{
public void mouseDragged(MouseEvent e) {
pan.setx(e.getX());
pan.sety(e.getY());
pan.repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class PaintListener2 implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
pan.setx(e.getX());
pan.sety(e.getY());
pan.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
class ClearListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
pan.setClean(true);
pan.repaint();
}
}
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource() == rougeButton)
pan.setColor(Color.red);
if(e.getSource() == bleuButton)
pan.setColor(Color.blue);
if(e.getSource() == noirButton)
pan.setColor(Color.black);
}
}
}
Panel's Code :
public class Panneau extends JPanel{
private int mousex=0,mousey=0;
private boolean clean=true;;
private Color color= Color.black;
public void paintComponent(Graphics g){
g.setColor(color);
draw(g);
if(clean){
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
clean=false;
}
}
private void draw(Graphics g){
g.fillOval(mousex, mousey, 10, 10);
}
public void setx(int x){
this.mousex=x;
}
public void sety(int y){
this.mousey=y;
}
public void setClean(boolean c){
this.clean = c;
}
public void setColor(Color c){
this.color=c;
}
}

the panel erases everything I painted and changes the background too ... here's my code :
You need to keep track of everything that has been painted and then repaint everything again.
See Custom Painting Approaches for the two common ways to do this:
Use a ArrayList to keep track of objects painted
Use a BufferedImage

Related

Add JLabel to MouseListener

1st time poster here!
I am working on a Java Photo Viewer Gallery.
I want to add all Labels from an ArrayList to a MouseListener. So I can go and open the picture the user clicked at in a new big window.
I have a file chooser where the user can select i number of pictures. I scaled them and put them in a:
ArrayList scaled = new ArrayList();
Error: The method addMouseListener(MouseListener) in the type Component is not applicable for the arguments (new ActionListener(){})
I tried to use
for (int i=0; i< scaled.size(); i++){
panel.add(new JLabel(new ImageIcon (scaled.get(i))));
JLabel l = new JLabel(new ImageIcon(scaled.get(i)));
l.addMouseListener(this); //<- Compiler Error
}
The complete Code is:
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.List;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class ImageViewer {
public static void main(String[] args) {
JFrame frame = new ImageViewerFrame();
frame.setTitle("PhotoViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class ImageViewerFrame extends JFrame implements MouseListener{
JLabel label;
JFileChooser chooser;
JMenuBar menubar;
JMenu menu;
JMenuItem menuitem;
JPanel panel = new JPanel();
// JLabel l1= new JLabel("First");
// JLabel l2= new JLabel("Second");
// JLabel l3= new JLabel("Third");
// JLabel l4= new JLabel("Fourth");
public ArrayList<File> images = new ArrayList <File>();
public ImageViewerFrame() {
setSize(500,500);
panel.setLayout(new GridLayout(0,5));
label = new JLabel();
add(label);
add(panel);
JButton test = new JButton ("TEST");
test.addMouseListener(this);
panel.add(test);
panel.setVisible(true);
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setMultiSelectionEnabled(true);
menubar = new JMenuBar();
setJMenuBar(menubar);
menu = new JMenu("File");
menubar.add(menu);
menuitem = new JMenuItem("Open");
menu.add(menuitem);
ArrayList<ImageIcon> AL = new ArrayList<ImageIcon>();
ArrayList<Image> scaled = new ArrayList<Image>();
menuitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
int result = chooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION) {
//label.setIcon(new ImageIcon(name));
File[] f = chooser.getSelectedFiles();
for(int i=0; i< f.length; i++)
{
images.add(f[i]);
ImageIcon imageicon = new ImageIcon(f[i].toString());
AL.add(imageicon);
}
for (ImageIcon x : AL){
System.out.println(x);
Image image = x.getImage();
Image newimg = image.getScaledInstance(120,120, java.awt.Image.SCALE_SMOOTH);
scaled.add(newimg);
}
for (int i=0; i< scaled.size(); i++){
panel.add(new JLabel(new ImageIcon (scaled.get(i))));
JLabel l = new JLabel(new ImageIcon(scaled.get(i)));
l.addMouseListener(this);
}
}
}
});
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
It wont let me add the JLabel l to the MouseListener
First of all you don't add a label to a MouseListener. You add a MouseListener to the label. You didn't implement the MouseListener interface so you get the compile error. You need to implement all the methods (mousePressed, mouseReleased ...).
Read the section from the Swing tutorial on How to Write a MouseListener for working examples.
Also, once you get the MouseListener working you don't need to create two labels. The basic code might be something like:
JLabel l = new JLabel(new ImageIcon(scaled.get(i)));
label.addMouseListener(this); //<- Compiler Error
panel.add( label );
Finally, you may want to consider using a JList to display the Icons. It is more efficient because it just renders the images. Then you can use a ListSelectionListener to do processing when an image is selected. Read the section from the Swing tutorial on How to Use Lists for more information.
I would use an array to store all the mouse information.
Example :
public class MyApp extends JFrame implements MouseListener, MouseWheelListener {
public int[] mouse=new int[5];
public void mousePressed(MouseEvent m) {
if (m.getButton() == m.BUTTON1) {
mouse[2]=1;
}
if (m.getButton() == m.BUTTON2) {
mouse[3]=1;
}
if (m.getButton() == m.BUTTON3) {
mouse[4]=1;
}
}
public void mouseClicked(MouseEvent m) {
if (m.getButton() == m.BUTTON1) {
mouse[2]=3;
}
if (m.getButton() == m.BUTTON2) {
mouse[3]=3;
}
if (m.getButton() == m.BUTTON3) {
mouse[4]=3;
}
}
public void mouseReleased(MouseEvent m) {
if (m.getButton() == m.BUTTON1) {
mouse[2]=2;
}
if (m.getButton() == m.BUTTON2) {
mouse[3]=2;
}
if (m.getButton() == m.BUTTON3) {
mouse[4]=2;
}
}
public void mouseEntered(MouseEvent m) {
}
public void mouseExited(MouseEvent m) {
}
public void mouseWheelMoved(MouseWheelEvent w) {
mouse[3]=w.getWheelRotation();
}
public MyApp() {
super("MyApp");
//Do your stuff here...
//...
//...
setTitle("Image Picker");
requestFocus();
addMouseListener(this);
addMouseWheelListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1400,1000);
setResizable(true);
setVisible(true);
int gc=0;
Rectangle r;
while (true){
try {
Thread.sleep(33);
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
r=getComponents()[0].getBounds();
gc=gc+1;
if (gc==500) {
System.gc();
gc=0;
}
mouse[0]=MouseInfo.getPointerInfo().getLocation().x-getComponents()[0].getLocationOnScreen().x;
mouse[1]=MouseInfo.getPointerInfo().getLocation().y-getComponents()[0].getLocationOnScreen().y;
//Display labels
}
}
public static void main(String args[]){
new MyApp();
}
}
The mouse array will be :
mouse[0] - mouse x pos
mouse[1] - mouse y pos
mouse[2] - left mouse button
mouse[3] - middle mouse button
mouse[4] - right mouse button
mouse[5] - mouse wheel rotation, 0 if none, else -n to n
And it should be easy to check if a point (the mouse) is over a rectangle (the label). If you dont know how to get the positions of the labels, simply use this code :
Rectangle r=getComponents()[1+n].getBounds();
//r.x, r.y, r.width, r.height
Hope it helps you !

Hovering button causes window to close

I'm developing a program that's meant to open a mode-less window whenever I hover some specific component. I'm not going into details that are not necessary but basically I have a mouse listener that opens a JFrame and shows a picture. The problem is, I also want to have a button that's meant to change the picture, but whenever I hover the button, the window closes and I have no idea why.
Here's the code:
Listener call:
public class ImageAction extends FocusOwnerAction{
/**
* The user interface controller
*/
protected UIController uiController;
public ImageAction(UIController uiController) {
this.uiController = uiController;
}
public void actionPerformed(ActionEvent event) {
MouseHoverController mouse = new MouseHoverController(focusOwner, this.focusOwner.getSpreadsheet());
mouse.addMouseHoverEvent();
}
...
public class MouseHoverController {
private final JTable table;
private final Spreadsheet spread;
public MouseHoverController(JTable table, Spreadsheet spread) {
this.table = table;
this.spread = spread;
}
public void addMouseHoverEvent() {
MouseHoverEvent mouseEvent = new MouseHoverEvent(spread);
table.addMouseMotionListener((MouseMotionListener) mouseEvent);
}
}
...
public class MouseHoverEvent extends MouseMotionAdapter {
private Spreadsheet spreadsheet;
public MouseHoverEvent(Spreadsheet spreadsheet) {
this.spreadsheet = spreadsheet;
}
#Override
public void mouseMoved(MouseEvent e) {
final JTable aTable = (JTable) e.getSource();
int itsRow = aTable.rowAtPoint(e.getPoint());
int itsColumn = aTable.columnAtPoint(e.getPoint());
Cell c = this.spreadsheet.getCell(itsColumn, itsRow);
ImageCell choosedCell = (ImageCell) c.getExtension(ImageExtension.NAME);
if (choosedCell.hasImages()) {
aTable.removeMouseMotionListener(this);
final JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2,1));
ImageIcon img = new ImageIcon("path.png");
Image im = img.getImage();
Image newimg = im.getScaledInstance(400, 500, java.awt.Image.SCALE_SMOOTH);
ImageIcon imgResizable = new ImageIcon(newimg);
JLabel image = new JLabel(imgResizable);
JPanel picPanel = new JPanel();
picPanel.add(image);
frame.add(picPanel);
JButton b1 = new JButton("Next");
frame.add(b1);
frame.setSize(400, 500);
// here's the part where I center the jframe on screen
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.addMouseListener(new MouseListener() {
public void mouseExited(MouseEvent e) {
frame.dispose();
MouseHoverEvent mouseEvent = new MouseHoverEvent(spreadsheet);
aTable.addMouseMotionListener((MouseMotionListener) mouseEvent);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
});
}
}
}

Why Won't the Java Component JPanel won't disapear?

I was trying to set up something with the JMenu where you can switch between "pages" (JPanels) but I ran into an issue where one would not disappear after trying a few methods online. What is the error I am making?
code:
public class Window {
public static boolean NewTerrainCamPos = false;
public static String textVal;
public static String textVal2;
public static String resiveTex;
public static String resiveTex2;
public static final int Width = 1000;
public static final int Height = 720;
public static final int FPS_CAP = 120;
private static long lastFrameTime;
private static float delta;
public void createDisplay(){
ContextAttribs attribs = new ContextAttribs(3,2).withForwardCompatible(true).withProfileCore(true);
try {
Canvas openglSurface = new Canvas();
JFrame frame = new JFrame();
JPanel game = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
//..............Menu Bar...............
JMenuBar menuBar = new JMenuBar();
JMenu terrain = new JMenu("Terrain");
JMenu Home = new JMenu("Home");
menuBar.add(Home);
menuBar.add(terrain);
JMenuItem newTerrain = new JMenuItem("add Terrain");
JMenuItem editTerrain = new JMenuItem("Edit Terrain");
JMenuItem editTexture = new JMenuItem("Edit Texture");
terrain.add(newTerrain);
terrain.add(editTerrain);
terrain.add(editTexture);
frame.setJMenuBar(menuBar);
//......................................................
newTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewTerrainCamPos = true;
JFrame frame2 = new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
//...............................
GridLayout experimentLayout = new GridLayout(3,2);
frame2.setLayout(experimentLayout);
//.....................................
JLabel xCord = new JLabel("XCoords: ");
JLabel zCord = new JLabel("ZCoords: ");
JTextField text = new JTextField();
JTextField text2 = new JTextField();
resiveTex2 = text2.getText();
text.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
text2.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
JButton createTerrain = new JButton("CreateTerrain");
createTerrain.addActionListener(new ActionListener(){
TIDF terrainFileID;
public void actionPerformed(ActionEvent a){
NewTerrainCamPos = false;
textVal = text.getText();
textVal2 = text2.getText();
TIDF load = new TIDF();
load.terrainIDFile();
}
});
frame2.add(xCord);
frame2.add(text);
frame2.add(zCord);
frame2.add(text2);
frame2.add(createTerrain);
}
});
editTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame frame3 = new JFrame();
frame3.setVisible(true);
frame3.setSize(300, 300);
//......................................
GridLayout experimentLayout = new GridLayout(3,2);
frame3.setLayout(experimentLayout);
//......................................
JButton select = new JButton("Select");
String terrainLocList[] =
{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
JList list = new JList(terrainLocList);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setVisibleRowCount(-1);
frame3.add(list);
frame3.add(select);
}
});
editTexture.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.remove(MainPage());
frame.add(TextureEditor());
frame.revalidate();
}
});
//.........................................
frame.add(MainPage());
frame.add(game);
frame.setSize(1200, 1200);
frame.setVisible(true);
game.add(openglSurface);
game.setBounds(0, 266, 1000, 720);
openglSurface.setSize(1000, 720);
Display.setParent(openglSurface);
Display.setDisplayMode(new DisplayMode(Width, Height));
Display.create(new PixelFormat(), attribs);
frame.setTitle("Game editor 0.3");
} catch (LWJGLException e) {
e.printStackTrace();
}
GL11.glViewport(0, 0, Width, Height);
lastFrameTime = getCurrentTime();
}
public Component MainPage(){
JPanel Main = new JPanel();
Main.setBounds(400, 0, 500, 200);
Label Welcome = new Label("Welcome to: Game Editor Version 0.3");
Welcome.setFont(new Font("Monotype Corsiva",10,22));
Main.add(Welcome);
return Main;
}
public Component TextureEditor(){
JPanel TextureLayoutLook = new JPanel();
TextureLayoutLook.setBounds(60, 0, 200, 200);
Label editorVersion = new Label("Terrain Texture Editor: 0.1");
TextureLayoutLook.add(editorVersion);
return TextureLayoutLook;
}
public static boolean Returnboolean(){
return NewTerrainCamPos;
}
public static String getTex1() {
return textVal;
}
public static String getTex2(){
return textVal2;
}
public static String getTexupdate(){
return resiveTex;
}
public static String getTexupdate2(){
return resiveTex2;
}
public static void updateDisplay(){
Display.sync(FPS_CAP);
Display.update();
long currentFrameTime = getCurrentTime();
delta = (currentFrameTime - lastFrameTime)/1000f;
lastFrameTime = currentFrameTime;
}
public static float getFrameTimeSeconds(){
return delta;
}
public static void closeDisplay(){
Display.destroy();
}
private static long getCurrentTime(){
return Sys.getTime()*1000/Sys.getTimerResolution();
}
}
frame.add(MainPage());
This line builds a brand new "main page" JPanel, and adds it the the JFrame.
frame.remove(MainPage());
This line of code creates a brand new "main page" JPanel, which has never been added to the JFrame, and attempts to remove it.
This new panel can't be removed, because it was never added. You need to retain a reference to the original panel, and remove that.
JPanel main_page = MainPage();
frame.add(main_page);
//...
frame.remove(main_page);
Note: This main_page could be re-added at a future time without needing to recreate it. Just call frame.add(main_page); again. But really, you want to use the card layout manager.

ActionListener is only counting left mouse click

I learned this code from some tutorial but it only counts left mouse clicks. I try with MouseListener but it kept counting while the timer came to 0. And with ActionListener it isn't counting the right mouse clicks. Any suggestions? Maybe its a foolish question but I'm new here.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class game extends JFrame
{
private static final int SwingConstants=0;
Timer timer;
int timercounter;
int clickcounter;
JLabel directions,entertime,clicklabel,timeleft,label;
JButton startbutton,clickbutton;
JTextField tf;
JMenuBar menubar;
JMenu file,help;
JMenuItem reset,exit,mhelp;
JFrame frame=new JFrame();
public game()
{
Container pane=this.getContentPane();
pane.setLayout(new GridLayout(3,1,2,2));
menubar=new JMenuBar();
setJMenuBar(menubar);
file=new JMenu("File");
menubar.add(file);
help=new JMenu("Help");
menubar.add(help);
reset=new JMenuItem("Reset");
file.add(reset);
exit=new JMenuItem("Quit");
file.add(exit);
mhelp=new JMenuItem("More Help!!");
help.add(mhelp);
ResetClass rc=new ResetClass();
reset.addActionListener(rc);
ExitClass ec=new ExitClass();
exit.addActionListener(ec);
MhelpClass mc=new MhelpClass();
mhelp.addActionListener(mc);
JPanel top=new JPanel();
top.setLayout(new GridLayout(1,1));
directions=new JLabel("Enter time & press <Click Here> REPEATEDLY!!");
top.add(directions);
pane.add(top);
JPanel middle=new JPanel();
middle.setLayout(new GridLayout(1,3));
entertime=new JLabel("Enter Time (sec):");
middle.add(entertime);
tf=new JTextField();
middle.add(tf);
startbutton=new JButton("Click Here");
middle.add(startbutton);
pane.add(middle);
JPanel bottom=new JPanel();
bottom.setLayout(new GridLayout(1,3));
clickbutton=new JButton("Click Here!");
clickbutton.setEnabled(false);
bottom.add(clickbutton);
clicklabel=new JLabel("Clicks: 0");
bottom.add(clicklabel);
timeleft=new JLabel("Time left: ?");
bottom.add(timeleft);
pane.add(bottom);
StartButtonClass sbc=new StartButtonClass();
startbutton.addActionListener(sbc);
ClickButtonClass cbc=new ClickButtonClass();
clickbutton.addActionListener(cbc);
}
public class StartButtonClass implements ActionListener
{
#Override
public void actionPerformed(ActionEvent sbc)
{
try
{
int timeCount=(int)(Double.parseDouble(tf.getText()));
if(timeCount<=0)
{
tf.setText("Positive number!");
//startbutton.setEnabled(false);
}
else
{
timeleft.setText("Time left: "+timeCount);
TimeClass tc=new TimeClass(timeCount);
timer=new Timer(1000,tc);
timer.start();
startbutton.setEnabled(false);
clickbutton.setEnabled(true);
}
}
catch(NumberFormatException ex)
{
tf.setText("Number only!");
}
}
}
public class ClickButtonClass implements MouseListener
{
public void mouseReleased(MouseEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
#Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e)
{
// TODO Auto-generated method stub
}
}
public class TimeClass implements ActionListener
{
int timerCounter;
public TimeClass(int timerCounter)
{
this.timerCounter=timerCounter;
}
public void actionPerformed(ActionEvent tc)
{
timerCounter--;
if(timerCounter>=1)
{
timeleft.setText("Time left: "+timerCounter);
}
else
{
timer.stop();
timeleft.setText("Done!");
clickbutton.setEnabled(false);
Toolkit.getDefaultToolkit().beep();
}
}
}
public class ResetClass implements ActionListener
{
public void actionPerformed(ActionEvent rc)
{
clickbutton.setEnabled(false);
startbutton.setEnabled(true);
clickcounter=0;
clicklabel.setText("Clicks: 0");
tf.setText("");
timeleft.setText("Time left: ?");
}
}
public class ExitClass implements ActionListener
{
public void actionPerformed(ActionEvent ec)
{
System.exit(0);
}
}
public class MhelpClass implements ActionListener
{
public void actionPerformed(ActionEvent mc)
{
JOptionPane.showMessageDialog(null, "Read the Readme file carefully!!", "Help!!", JOptionPane.PLAIN_MESSAGE);
}
}
}
Use this it will let you see right mouse clicks
class MyMouseListener implements MouseListener{
#Override
public void mouseReleased(MouseEvent arg0) {
if(SwingUtilities.isRightMouseButton(arg0)&&clickButton.isEnabled()){
//my code
}
}

How to dynamically remove a JPanel?

I have a a GUI looks as follow.
I want to dynamically add/remove a panel. I use ArrayList to keep trace of JPanel objects.
And now I could add panel dynamically, but when I want to delete a panel, I could not get its attribute so that I can not remove it.
Here is my code:
public class Main implements ActionListener{
private List <myPanel> mpList;
private JPanel btnPanel;
private JButton jbtAdd,jbtDelete;
private JFrame jf;
private JPanel jp;
private JScrollPane js;
private myPanel mp;
private static int size=0;
private int selectedId=-1;
//private
public Main(){
mpList=new ArrayList<myPanel>();
btnPanel=new JPanel();
jbtAdd=new JButton("addJpanel");
jbtDelete=new JButton("delJpanel");
btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT,1,1));
btnPanel.add(jbtAdd);
btnPanel.add(jbtDelete);
jf=new JFrame("hello");
jp=new JPanel();
js=new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//jp.setLayout(new FlowLayout(FlowLayout.LEFT,1,1));
jf.setLayout(new BorderLayout(10,10));
jp.setLayout(new GridLayout(0,1,1,1));
jp.setPreferredSize(new Dimension(500, 82*6));
for(int i=0;i<6;i++){
myPanel mp=new myPanel();
//mp.setSize(400, 82);
//mp.setBounds(0,82*i,480,82);
mp.getFileTypeIconLabel().setText(String.valueOf(i));
mp.setIndexId(size);
size++;
mpList.add(0,mp);
mp.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(2==e.getClickCount()){
System.out.println("indexInd is"+mpList.get(0).getIndexId());
//System.out.println(index);
mpList.get(0).setBackground(Color.yellow);
}
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}});
jp.add(mpList.get(0));
}
js.setViewportView(jp);
jf.setSize(600, 500);
jf.add(btnPanel,BorderLayout.NORTH);
jf.add(js);
jbtAdd.addActionListener(this);
jbtDelete.addActionListener(this);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new Main();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==jbtAdd){
addMyPanel();
}
else if(e.getSource()==jbtDelete){
delMyPanel();
}
}
public void addMyPanel(){
System.out.println("ok");
mp=new myPanel();
mp.getFileTypeIconLabel().setText(String.valueOf(mpList.size()));
mp.setIndexId(size);
System.out.println(size);
size++;
mpList.add(0, mp);
mp.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(2==e.getClickCount()){
System.out.println("indexInd is"+mpList.get(0).getIndexId());
//System.out.println(index);
mpList.get(0).setBackground(Color.yellow);
}
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}});
jp.add(mpList.get(0));
jp.setPreferredSize(new Dimension(500, 82*mpList.size()));
//jp.validate();
js.validate();
//jp.repaint();
js.repaint();
}
public void delMyPanel(){
selectedId=getIndexOfMyPanelById();
if(selectedId>=0){
int indexId=getIndexOfMyPanelById();
jp.remove(mpList.get(indexId));
mpList.remove(indexId);
jp.setPreferredSize(new Dimension(500,82*mpList.size()));
jp.repaint();
}
}
protected int getIndexOfMyPanelById(){
Iterator<myPanel> it=mpList.iterator();
for(int id=0;it.hasNext();id++){
myPanel mp;
mp=it.next();
if(mp.isSelected()){
return id;
}
}
return -1;
}
}
Here is code of myPanel
class myPanel extends JPanel{
private static final long serialVersionUID = 1L;
private JProgressBar downloadProgress;
private JLabel fileTypeIconLabel,fileNameLabel,downloadInfoLabel,freeLabel;
private int indexId;
private boolean isSelected=false;
protected myPanel(){
setLayout(null);
downloadProgress=new JProgressBar(0,100);
fileTypeIconLabel=new JLabel("test");
fileNameLabel=new JLabel("fileNameLabel");
downloadInfoLabel=new JLabel("downloadInfoLabel");
freeLabel=new JLabel("freeLabel");
downloadProgress.setBounds(80, 44, 400, 18);
downloadProgress.setStringPainted(true);
//downloadProgress.setString("88%");
fileTypeIconLabel.setBounds(0, 0, 80, 80);
fileTypeIconLabel.setBackground(Color.cyan);
fileTypeIconLabel.setOpaque(true);
fileNameLabel.setBounds(80,0,400,22);
fileNameLabel.setBackground(Color.black);
fileNameLabel.setOpaque(true);
downloadInfoLabel.setBounds(80, 22, 400, 22);
downloadInfoLabel.setBackground(Color.red);
downloadInfoLabel.setOpaque(true);
//downloadProgress.setValue(50);
freeLabel.setBounds(80, 62, 400, 18);
freeLabel.setBackground(Color.lightGray);
freeLabel.setOpaque(true);
add(downloadProgress);
add(fileTypeIconLabel);
add(fileNameLabel);
add(downloadInfoLabel);
add(freeLabel);
}
protected JLabel getFileTypeIconLabel() {
return fileTypeIconLabel;
}
protected int getIndexId() {
return indexId;
}
protected void setIndexId(int indexId) {
this.indexId = indexId;
}
protected boolean isSelected() {
return isSelected;
}
protected void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
For many components in one space, use a CardLayout as seen in this short example.
Tips
jp.setPreferredSize(new Dimension(500, 82*6));
See Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (Yes.)
downloadProgress.setBounds(80, 44, 400, 18);
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Edit 1
As an aside, the screen-shot screams JList with custom renderer to me. E.G.
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class DymanicDownloadList {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout(2, 2));
public void initGUI() {
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
JToolBar tb = new JToolBar();
gui.add(tb, BorderLayout.PAGE_START);
final DefaultListModel<Download> listModel =
new DefaultListModel<Download>();
final JList<Download> list = new JList<Download>(listModel);
list.setCellRenderer(new DownloadListCellRenderer());
list.setVisibleRowCount(3);
gui.add(new JScrollPane(list), BorderLayout.CENTER);
Action add = new AbstractAction("Add Download") {
#Override
public void actionPerformed(ActionEvent e) {
listModel.addElement(new Download());
}
};
Action delete = new AbstractAction("Delete Download") {
#Override
public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
if (index < 0) {
JOptionPane.showMessageDialog(
list,
"Select a download to delete!",
"Select Download",
JOptionPane.ERROR_MESSAGE);
} else {
listModel.removeElementAt(index);
}
}
};
tb.add(add);
tb.addSeparator();
tb.add(delete);
for (int ii = 0; ii < 2; ii++) {
listModel.addElement(new Download());
}
}
public JComponent getGUI() {
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
DymanicDownloadList ddl = new DymanicDownloadList();
ddl.initGUI();
JFrame f = new JFrame("Dynamic LIST");
f.add(ddl.getGUI());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See https://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
class Download {
Download() {
}
}
class DownloadListCellRenderer extends DefaultListCellRenderer {
JPanel downloadPanel = new JPanel(new BorderLayout(10, 10));
JPanel labelStack = new JPanel(new GridLayout(0, 1, 2, 2));
JLabel number = new JLabel("", SwingConstants.CENTER);
JLabel source = new JLabel("File Name Label", SwingConstants.CENTER);
JLabel info = new JLabel("Download Info Label", SwingConstants.CENTER);
JLabel free = new JLabel("Free Label", SwingConstants.CENTER);
JProgressBar progress = new JProgressBar() {
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(400,d.height);
}
};
DownloadListCellRenderer() {
downloadPanel.add(labelStack, BorderLayout.CENTER);
labelStack.setOpaque(false);
number.setFont(number.getFont().deriveFont(40f));
labelStack.add(source);
labelStack.add(info);
labelStack.add(progress);
labelStack.add(free);
downloadPanel.add(labelStack, BorderLayout.CENTER);
downloadPanel.add(number, BorderLayout.LINE_START);
}
#Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel l = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
downloadPanel.setBackground(l.getBackground());
number.setText("" + (index + 1));
return downloadPanel;
}
}

Categories