How to dynamically remove a JPanel? - java

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;
}
}

Related

My actionPerformed method(Java) is not working and I have no clue why

Here is my whole program, don't wonder about the words I am using, I am German.
Down from l. 95 to l. 103 is the action performed method, (I only did the System.out.println() to see wether it is working or not).
I wrote other programs, where I never had any such problems, and I tried so many things, but I did not find the problem, maybe it is a total simple one...
So I would appreciate it if you help me!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameFrame implements ActionListener {
String wochentag;
int itag = 0;
int imonat = 0;
int ijahrhundert = 0;
int ijahr = 0;
String stag;
String smonat;
String sjahr;
String sJahrhundert;
boolean rechnen = false;
JFrame frame = new JFrame();
JButton start = new JButton("Wochentag errechnen");
JButton update = new JButton("Datum anzeigen");
JPanel alles = new JPanel();
JLabel Tag = new JLabel("Tag");
JLabel Monat = new JLabel("Monat");
JLabel Jahr = new JLabel("Jahr");
JLabel Jahrhundert = new JLabel("Jahrhundert");
JTextField Datum = new JTextField(" Welchen Wochentag hatte der --.--.---- ");
JTextField Output = new JTextField(" Dieser Tag war ein ------tag");
JTextField tag = new JTextField();
JTextField monat = new JTextField();
JTextField jahr = new JTextField();
JTextField jahrhundert = new JTextField();
GameFrame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.getContentPane().setBackground(Color.WHITE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
frame.setFocusable(false);
frame.setResizable(false);
alles.setBounds(0,0,500,500);
Datum.setBounds(75,40,280,40);
Datum.setEditable(false);
Tag.setBounds(175,100,45,25);
Monat.setBounds(175,150,55,25);
Jahr.setBounds(175,200,50,25);
Jahrhundert.setBounds(175,250,75,25);
Output.setBounds(118,400,202,40);
Output.setEditable(false);
tag.setBounds(250,100,75,25);
tag.setEditable(true);
monat.setBounds(250,150,75,25);
jahr.setBounds(250,200,75,25);
jahrhundert.setBounds(250,250,75,25);
start.setBounds(165,350,170,25);
start.setFocusable(false);
update.setBounds(175,300,150,25);
update.setFocusable(false);
frame.add(alles);
alles.add(Datum);
alles.add(Tag);
alles.add(Monat);
alles.add(Jahr);
alles.add(Jahrhundert);
alles.add(Output);
alles.add(tag);
alles.add(monat);
alles.add(jahr);
alles.add(jahrhundert);
alles.add(start);
alles.add(update);
}
public static void main(String[] args) {
GameFrame gameframe = new GameFrame();
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == update){
stag = tag.getText();
tag.setText("");
System.out.println(stag);
}
}
}
As the guys mentioned in the comments, you have not added the listener to your component (update button). If you are using a button, you might consider using a MouseListener instead
public class GameFrame implements MouseListener {
JButton update = new JButton("Datum anzeigen");
GameFrame()
{
//other code
update.addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
If you want to have multiple listeners for your separate buttons you can also create them within your constructor
update.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
System.out.println("Start button wurde geklickt");
}
};
start.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
System.out.println("Update button wurde geklickt");
}
};

How to Change Default Inputs for JComboBox and JButton

How do I make the Enter key trigger a JComboBox or JButton in a GUI rather than having to hit the Space key? I have an assortment of text fields and check boxes with buttons and combo boxes in between. I'd like to avoid having to switch between hitting space and enter and rather only have to hit enter for all components.
package koning.personal.dungeonsanddragons;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test {
JFrame window = new JFrame("testGUI");
JPanel windowPanel = new JPanel();
public static JLabel labelSize;
public static JComboBox<String> comboSize;
public static JLabel labelButton;
public static JButton buttonButton;
public test () {
super();
labelSize = new JLabel("Monster Size:");
String[] sizeChoices = { "None", "Tiny", "Small", "Medium", "Large", "Huge", "Colossal"};
comboSize = new JComboBox<String>(sizeChoices);
comboSize.setToolTipText("The creature's size.");
labelButton = new JLabel("Button:");
buttonButton = new JButton();
windowPanel.setLayout(new FlowLayout());
windowPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
windowPanel.add(labelSize);
windowPanel.add(comboSize);
windowPanel.add(labelButton);
windowPanel.add(buttonButton);
windowPanel.setVisible(true);
window.setSize(500, 500);
window.setLayout(new FlowLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.add(windowPanel);
comboSize.addActionListener(handler);
buttonButton.addActionListener(handler);
}
ActionHandler handler = new ActionHandler();
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent eventFocus){
if (eventFocus.getSource() == comboSize){
buttonButton.requestFocusInWindow();
}
if (eventFocus.getSource() == buttonButton){
comboSize.requestFocusInWindow();
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args) {
test GUITest = new test();
}
}
You can add a KeyListener and execute doClick
JButton btn = new JButton();
btn.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
btn.doClick();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});
If the goal is to have something happen when the enter button is pressed (pressed once and something happens with all the components) then you can add a KeyListener to the JFrame:
JFrame frame = new JFrame("Examplpe");
//here you create and add the components to the frame
and then you can add a KeyListener:
frame.addKeyListener(new KeyListener(
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode == KeyEvent.VK_ENTER){//this is the if block I'm refering to in the following explanation
//do something with all the components
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {}
}
and then when you press Enter, the code inside the if block will be executed.
Hope this helps :)

Get selected value from JTable to another JFrame

Hello This is my first class where I created a JTable in JFrame.
public class code_selection extends JFrame implements MouseListener {
public JTable table;
private Color myback=new Color(0,85,170);
public int v,row,col;
public int h,str1;
public JScrollPane jsp;
public JPanel jp;
private int red=10;
private int green=125;
private int blue=10;
private Color mygreen=new Color(red,green,blue);
conn co=new conn();
public String str;
public String st2[]={"NAME","CODE"} ;
public String st3[][]={{"navneet","321"},
{"hehehe","123"},
{"hehehe","456"},
{"hehehe","789"}};
public code_selection()
{
setSize(620,400);
setTitle("Navneet Software Solutions");
Container contentPane=getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(mygreen);
setLocationRelativeTo(null);
setUndecorated(true);
table=new JTable(st3,st2);
table.setBackground(Color.WHITE);
table.setForeground(Color.BLACK);
table.setGridColor(Color.BLACK);
table.setBounds(0, 0, 400, 500);
table.addMouseListener(this);
v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
jsp=new JScrollPane(table,v,h);
jsp.setBounds(10,10,600,380);
add(jsp);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
try {
row=table.getSelectedRow();
col=0;
str=table.getModel().getValueAt(row, col).toString();
col=1;
str1=Integer.parseInt(table.getModel().getValueAt(row, col).toString());
dispose();
}
catch(Exception e)
{
System.out.println(e);
}
}
#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
}
}
This is my second class where I created frame with text field and button.
When I click on the button my table frame open.
public class amt_deposit extends JPanel implements MouseListener {
private ImageIcon i1,i2,i3,i4;
private JLabel l1,l2,l3,l4,l5,l6;
public JTextField t2,t3;
private JButton b1,b2,b3;
private DatePicker datePicker=new DatePicker();
private Color myback=new Color(0,85,170);
public int st;
conn con1=new conn();
public amt_deposit() {
try {
setLayout(null);
setBackground(myback);
i1=new ImageIcon("images/deposit.png");
l1=new JLabel(i1);
l1.setBounds(10,10,70,85);
l2=new JLabel("Amount Deposit");
l2.setBounds(83, 50, 200, 50);
l2.setForeground(Color.WHITE);
l2.setFont(new Font("arial",Font.BOLD,21));
l2.setBackground(myback);
l2.setOpaque(true);
l5=new JLabel("Date :- ");
l5.setBounds(100,150,100,50);
l5.setForeground(Color.WHITE);
l5.setFont(new Font("arial",Font.BOLD,16));
l5.setBackground(myback);
l5.setOpaque(true);
datePicker.setBounds(230,163,165,23);
datePicker.setText("Select");
l3=new JLabel("Patient Code :- ");
l3.setBounds(100,200,130,50);
l3.setForeground(Color.WHITE);
l3.setFont(new Font("arial",Font.BOLD,16));
l3.setBackground(myback);
l3.setOpaque(true);
b3=new JButton("...");
b3.setBounds(370, 213, 30, 25);
//b3.addActionListener(this);
b3.addMouseListener(this);
//b3.setBackground(myback);
//b3.setOpaque(true);
t2=new JTextField();
t2.setBounds(230,213,140,25);
t2.addMouseListener(this);
l4=new JLabel("Amount :- ");
l4.setBounds(100,250,100,50);
l4.setForeground(Color.WHITE);
l4.setFont(new Font("arial",Font.BOLD,16));
l4.setBackground(myback);
l4.setOpaque(true);
t3=new JTextField();
t3.setBounds(230,263,140,25);
i2=new ImageIcon("images/ok2.png");
b1=new JButton(i2);
b1.setBounds(80,360,110,40);
b1.setBackground(myback);
b1.setOpaque(true);
i3=new ImageIcon("images/cancel2.png");
b2=new JButton(i3);
b2.setBounds(220,360,110,40);
b2.setBackground(myback);
b2.setOpaque(true);
i4=new ImageIcon("images/owl.png");
l6=new JLabel(i4);
l6.setBounds(800,30,200,120);
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
add(datePicker);
add(t2);
add(t3);
add(b1);
add(b2);
add(l6);
add(b3);
setVisible(true);
}
catch(Exception e)
{
System.out.println("Error in amt_deposit "+e);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
try {
code_selection cs=new code_selection();
st=cs.table.getRowCount();
String str5=cs.table.getModel().getValueAt(st, 0).toString();
String str6=cs.table.getModel().getValueAt(st, 1).toString();
System.out.println(str5+str6);
t2.setText(str5);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
When I click on button then my frame open in which I created a table.
I want to get selected value from the table and set on the text field which is on another frame.
I am using right procedure and correct methods but still I am getting error.
java.lang.ArrayIndexOutOfBoundsException:-1
Could you please help me? Could you please tell me where I am wrong?
For your information I am able to get value from the table on same frame on which table is located but I am not able to get selected value from table from frame to another frame.

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
}
}

JMenuBar repaints my JPanel

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

Categories