Hi I have the following code where I have a start and stop button . when start is pressed canvas starts painting but I cannot press stop button until the start operation is done . I need to stop and resume the paint on the button press . Once the start button is pressed the other buttons cannot be pressed till the canvas is painted.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;
public abstract class JUIApp extends JPanel implements ActionListener {
public static CACanvas cacanvas= null;
public ArrayList<int[]> genL;
public JFrame frame = null;
protected JPanel mainPanel = null;
private JButton btn0 = null;
private JButton btn1 = null;
private JButton btn2 = null;
#SuppressWarnings("rawtypes")
DefaultComboBoxModel rules = null;
#SuppressWarnings("rawtypes")
JComboBox rulesCombo =null;
JScrollPane ruleListScrollPane=null;
JLabel lable=null;
JTextField generation=null;
JLabel gLable=null;
public static String Rule;
public static String Generations;
public boolean isChanged =false;
public int gridCellSize=4;
private static final long serialVersionUID = 1L;
public int genCurrent=0;
public int posCurrent=0;
public int i;
public Color cellColor= null;
public Timer waitTimer;
public static boolean waitFlag;
public static boolean alert1Flag=false;
public boolean stopFlag=false;
public JLabel Alert1=new JLabel();
public int genCheck=0;
//private List<Point> fillCells;
public JUIApp() {
initGUI();
}
public void initGUI() {
//fillCells = new ArrayList<>(25);
frame = new JFrame();
frame.setTitle("Cellular Automata Demo");
frame.setSize(1050, 610);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(getMainPanel(),BorderLayout.NORTH);
frame.setVisible(true);
Toolkit.getDefaultToolkit().setDynamicLayout(false);
cacanvas=new CACanvas();
frame.add(cacanvas);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public JPanel getMainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
//cacanvas=new CACanvas();
btn0 = new JButton("Start");
btn0.addActionListener(this);
//waitTimer = new Timer(1000, this);
mainPanel.add(btn0);
JButton btn2 = new JButton("Stop");
btn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent s)
{
stopFlag=true;
//cacanvas.repaint();
}
});
mainPanel.add(btn2);
btn1 = new JButton("Clear");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
CACanvas.clearFlag=true;
generation.setText("");
alert1Flag=true;
rulesCombo.setSelectedIndex(0);
Alert1.setText("Please enter the number of generations");
Alert1.setBounds(30, 20, 5, 5);
Alert1.setVisible(alert1Flag);
mainPanel.add(Alert1);
cacanvas.repaint();
frame.setSize(1060, 610);
}
});
mainPanel.add(btn1);
lable=new JLabel();
lable.setText("Select Rule :");
mainPanel.add(lable);
rules=new DefaultComboBoxModel();
for (int i=0;i<=100;i++)
{
String p=String.valueOf(i);
rules.addElement(p);
}
rules.addElement("250");
rules.addElement("254");
rulesCombo = new JComboBox(rules);
rulesCombo.setSelectedIndex(0);
ruleListScrollPane = new JScrollPane(rulesCombo);
mainPanel.add(ruleListScrollPane);
//mainPanel.revalidate();
gLable=new JLabel();
gLable.setText("Enter the number of Generations (Max 64)");
generation=new JTextField(2);
mainPanel.add(gLable);
mainPanel.add(generation);
// mainPanel.add(cacanvas);
return mainPanel;
}
public abstract void run();
#Override
public void actionPerformed(ActionEvent arg0) {
Alert1.setVisible(false);
waitFlag=false;
System.out.println("We received an ActionEvent " + arg0);
Generations=generation.getText();
System.out.println(Generations);
Rule = "";
if (rulesCombo.getSelectedIndex() != -1) {
Rule =
(String) rulesCombo.getItemAt
(rulesCombo.getSelectedIndex());
}
System.out.println(Rule);
int rule=Integer.parseInt(Rule);
Hashtable<String,Integer> rules= new Hashtable<String,Integer>();
CARule ruleClass=new CARule();
rules=ruleClass.setRule(rule);
CAGenetationSet sa =new CAGenetationSet(100, false,rules);
genL=new ArrayList<int[]>();
genL=sa.runSteps(Integer.parseInt(Generations));
System.out.println("calling pattern set");
for(int i=0;i<=genL.size()-1;i++)
{
System.out.println("Painting generation :"+i);
if(stopFlag==false)
{
cacanvas.repaint();
}
//genPaint();
//sleep();
int[] newCell=genL.get(i);
for(int r=0;r<newCell.length;r++)
{
if(newCell[r]==1)
{
System.out.println("Generaton is"+i+"CellLife is"+r);
cacanvas.fillCell(i,r);
}
}
}
/*cacanvas.patternSet(genL);
waitFlag=true;
System.out.println("run completed");
// cacanvas.clearFlag=true;
*/
}
public void genPaint()
{
cacanvas.repaint();
}
public void sleep()
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
JUIApp app = new JUIApp() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Run method");
}
};
}
}
Seems like you are using the current Thread on that task, you should create another Thread and add one listeners code to the new Thread.
Related
I've written a test program with making the jButton invisible and visible:
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class Blink
{
private JButton btn;
private static JFrame f;
public static void delay(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
public Blink()
{
f = new JFrame("Blink");
f.setPreferredSize(new Dimension(500, 500));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn = new JButton("Click me and I'll blink!");
f.add(btn);
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
buttonClicked();
}
});
f.pack();
f.setVisible(true);
}
private void buttonClicked()
{
for (int i = 0; i < 5; i++)
{
delay(300);
btn.setVisible(false);
delay(300);
btn.setVisible(true);
}
}
public static void main(String[] args)
{
new Blink();
}
}
Unfortunately, the jButton does not blink. And when the buttonClicked() function is changed, so that the jButton is set invisible 5 times and is not set visible back, the jButton disappears only when the for-loop finishes. How to make the jButton disappear an reappear instantaneously?
You cannot use Thread.sleep method in Swing Thread (all listeners are called in Event Dispatcher Thread - EDT). To achieve blinking you must use javax.swing.Timer class. For more information look here and here
Here is your reworked example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Blink {
private JButton btn;
private JFrame f;
public void delay(int ms, boolean show) {
Timer timer = new Timer(ms, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setVisible(show);
btn.getParent().revalidate();
btn.getParent().repaint();
}
});
timer.setRepeats(false);
timer.start();
}
public Blink() {
f = new JFrame("Blink");
f.setPreferredSize(new Dimension(500, 500));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn = new JButton("Click me and I'll blink!");
f.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
buttonClicked();
}
});
f.pack();
f.setVisible(true);
}
private void buttonClicked() {
for (int i = 1; i <= 10; i += 2) {
delay(300 * i, false);
delay(300 * (i + 1), true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Blink();
}
});
}
}
For some complicated layouts, call setVisible(false) may have side-effects. In this case the CardLayout with your component and an empty panel should be used.
Here is the variant with CardLayout
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Blink {
private static final String BUTTON_CARD = "button";
private static final String EMPTY_CARD = "empty";
private JButton btn;
private JFrame f;
private final CardLayout cardLayout = new CardLayout();
public void delay(int ms, boolean show) {
Timer timer = new Timer(ms, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(btn.getParent(), show ? BUTTON_CARD : EMPTY_CARD);
btn.getParent().revalidate();
btn.getParent().repaint();
}
});
timer.setRepeats(false);
timer.start();
}
public Blink() {
f = new JFrame("Blink");
f.setPreferredSize(new Dimension(500, 500));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(cardLayout);
btn = new JButton("Click me and I'll blink!");
f.add(btn, BUTTON_CARD);
f.add(new JPanel(), EMPTY_CARD);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
buttonClicked();
}
});
f.pack();
f.setVisible(true);
}
private void buttonClicked() {
for (int i = 1; i <= 10; i += 2) {
delay(300 * i, false);
delay(300 * (i + 1), true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Blink();
}
});
}
}
As #Sergiy points out - make sure you're running from the EDT, and don't sleep on the EDT, use a swing timer instead.
To make your jButton appear "invisbile", you can do something like this:
public void setInvisible(jButton jb) {
jb.setOpaque(false);
jb.setContentAreaFilled(false);
jb.setBorderPainted(false);
jb.setText("");
}
// Assuming you have the original text saved in a variable
public void setRevisible(jButton jb) {
jb.setOpaque(true);
jb.setContentAreaFilled(true);
jb.setBorderPainted(true);
jb.setText(originalString);
}
Depending on if you want the button to be clickable when it's invisible, you can also add btn.setEnabled(bool);
So, if I click the button exists in First Frame, then the number would increase in JTextField exists in another Second Frame.
The First Frame contains the JButton and the Second Frame contains the JTextField.
Please Help.
Try below source code:
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class FirstFrame extends JFrame {
private static final long serialVersionUID = 1L;
private SecondFrame secondFrame;
private boolean flag = new Boolean(false);
private volatile Integer number;
#SuppressWarnings("unused")
private SwingWorker<Void, Void> swingWorker;
public FirstFrame() {
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FirstFrame();
}
});
}
private void init() {
setTitle("First Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(2, 1));
setBounds(500, 300, 250, 110);
final JButton increaseBtn = new JButton("Increase Number");
final JButton start = new JButton("Start");
final JButton stop = new JButton("Stop");
stop.setEnabled(false);
JPanel panel = new JPanel();
increaseBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
if (!flag) {
number = secondFrame.getNumber();
secondFrame.setNumber(number + 1);
}
}
});
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
flag = true;
startContinuousIncreasing();
start.setEnabled(false);
stop.setEnabled(true);
increaseBtn.setEnabled(false);
}
});
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
flag = false;
stop.setEnabled(false);
start.setEnabled(true);
increaseBtn.setEnabled(true);
}
});
getContentPane().add(increaseBtn);
getContentPane().add(panel);
panel.add(start);
panel.add(stop);
setVisible(true);
secondFrame = SecondFrame.getSecondFrame();
increaseBtn.requestFocus();
}
private void startContinuousIncreasing() {
swingWorker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
while (flag) {
number = secondFrame.getNumber();
secondFrame.setNumber(number + 1);
}
return null;
}
};
swingWorker.execute();
}
}
class SecondFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static Integer number;
private JTextField textField;
private static SecondFrame secondFrame;
private SecondFrame() {
init();
}
public synchronized static SecondFrame getSecondFrame() {
if (secondFrame == null)
secondFrame = new SecondFrame();
return secondFrame;
}
private void init() {
setTitle("Second Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1, 1));
setBounds(500, 412, 250, 70);
number = new Integer(0);
textField = new JTextField(String.valueOf(number));
textField.setFont(new Font("Dialog", Font.BOLD + Font.ITALIC, 22));
getContentPane().add(textField);
setVisible(true);
}
public synchronized Integer getNumber() {
return number;
}
public synchronized void setNumber(Integer num) {
try {
number = num;
this.textField.setText(String.valueOf(number));
} catch (NumberFormatException nfe) {
number = 0;
this.textField.setText(String.valueOf(number));
}
}
}
I guess you have created a Static variable. Static variables share the value across all instances of a class. That might be one of the answer.
Hopes it answered your questions. Let me know if it's not the answer. Yippee!!
So I'm trying to create a simple test program where the user can enter something into a JTextField, click the "add" JButton, and a JTextArea will add the users string to the the JTextArea (continuously appending with new line).
I added the actionListener for the button and have a stateChanged and an update method, but nothing happens when I click the add button. No errors either. Could someone please point me in the right direction?
Here's my code:
MVCTester (main)
public class MVCTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
MVCController myMVC = new MVCController();
MVCViews myViews = new MVCViews();
myMVC.attach(myViews);
}
}
MVCController
import java.util.ArrayList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCController {
MVCModel model;
ArrayList<ChangeListener> listeners;
public MVCController(){
model = new MVCModel();
listeners = new ArrayList<ChangeListener>();
}
public void update(String input){
model.setInputs(input);
for (ChangeListener l : listeners)
{
l.stateChanged(new ChangeEvent(this));
}
}
public void attach(ChangeListener c)
{
listeners.add(c);
}
}
MVCModel
import java.util.ArrayList;
public class MVCModel {
private ArrayList<String> inputs;
MVCModel(){
inputs = new ArrayList<String>();
}
public ArrayList<String> getInputs(){
return inputs;
}
public void setInputs(String input){
inputs.add(input);
}
}
MVCViews
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCViews implements ChangeListener {
private JTextField input;
private JTextArea echo;
private ArrayList<String> toPrint = new ArrayList<String>();
MVCController controller;
MVCViews(){
controller = new MVCController();
JPanel myPanel = new JPanel();
JButton addButton = new JButton("add");
echo = new JTextArea(10,20);
echo.append("Hello there! \n");
echo.append("Type something below!\n");
myPanel.setLayout(new BorderLayout());
myPanel.add(addButton, BorderLayout.NORTH);
input = new JTextField();
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.NORTH);
frame.add(echo, BorderLayout.CENTER);
frame.add(input, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
controller.update(input.getText());
}
});
frame.pack();
frame.setVisible(true);
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
toPrint = controller.model.getInputs();
for(String s: toPrint){
echo.append(s + "\n");
}
}
}
This is my first time trying to follow MVC format, so there might be issues with the model itself as well. Feel free to point them out. Thank you for your help!
The controller within the GUI is not the same controller that is created in main. Note how many times you call new MVCController() in your code above -- it's twice. Each time you do this, you're creating a new and distinct controller -- not good. Use only one. You've got to pass the one controller into the view. You can figure out how to do this. (hint, a setter or constructor parameter would work).
hint 2: this could work: MVCViews myViews = new MVCViews(myMVC);
one solution:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCTester {
public static void main(String[] args) {
MVCController myMVC = new MVCController();
MVCViews myViews = new MVCViews(myMVC);
myMVC.attach(myViews);
// myViews.setController(myMVC); // or this could do it
}
}
class MVCController {
MVCModel model;
ArrayList<ChangeListener> listeners;
public MVCController() {
model = new MVCModel();
listeners = new ArrayList<ChangeListener>();
}
public void update(String input) {
model.setInputs(input);
for (ChangeListener l : listeners) {
l.stateChanged(new ChangeEvent(this));
}
}
public void attach(ChangeListener c) {
listeners.add(c);
}
}
class MVCModel {
private ArrayList<String> inputs;
MVCModel() {
inputs = new ArrayList<String>();
}
public ArrayList<String> getInputs() {
return inputs;
}
public void setInputs(String input) {
inputs.add(input);
}
}
class MVCViews implements ChangeListener {
private JTextField input;
private JTextArea echo;
private ArrayList<String> toPrint = new ArrayList<String>();
MVCController controller;
MVCViews(final MVCController controller) {
// !! controller = new MVCController();
this.controller = controller;
JPanel myPanel = new JPanel();
JButton addButton = new JButton("add");
echo = new JTextArea(10, 20);
echo.append("Hello there! \n");
echo.append("Type something below!\n");
myPanel.setLayout(new BorderLayout());
myPanel.add(addButton, BorderLayout.NORTH);
input = new JTextField();
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.NORTH);
frame.add(echo, BorderLayout.CENTER);
frame.add(input, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (controller != null) {
controller.update(input.getText());
}
}
});
frame.pack();
frame.setVisible(true);
}
public void setController(MVCController controller) {
this.controller = controller;
}
#Override
public void stateChanged(ChangeEvent e) {
if (controller != null) {
toPrint = controller.model.getInputs();
for (String s : toPrint) {
echo.append(s + "\n");
}
}
}
}
Here is my code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class wind extends JFrame implements ComponentListener, MouseListener
{
JButton button;
JLabel label;
public wind()
{
// initialise instance variables
setTitle("My First Window!");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.addComponentListener(this);
content.addMouseListener(this);
label = new JLabel("My First Window");
content.add(label);
label.addComponentListener(this);
button = new JButton("Click If You Wish To Live!");
button.addMouseListener(this);
content.add(button)
setContentPane(content);
}
public void componentHidden(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Hidden!");
}
public void componentShown(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Shown!");
}
public void componentResized(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Resized!");
}
public void componentMoved(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Moved!");
}
public void mouseExited(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("Exited!");
}
public void mouseEntered(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("Entered!");
}
public void mousePressed(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("pressed at: "+e.getX()+" "+e.getY());
}
public void mouseReleased(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("Released!");
label.setLocation(e.getX(), e.getY());
}
public void mouseClicked(MouseEvent e){}
}
It won't respond to the mouse or window re-sizing, hiding, or moving. Furthermore the button is not being displayed. fixed! I am just starting to learn about Java's JFrame and other graphics so I have no idea what's wrong with my code, although I suspect it has something to do with the way I made the button and added the listeners to the objects. Could someone please explain why it does this, and how to fix it. Thank you in advance!
Your problem is that you are using the wait function not correctly. Try to use the class javax.swing.Timer also known as a Swing Timer for delays in Swing programs, for simple animations and for repetitive actions. For more information see this example on stackoverflow: Java Wait Function
One possible way to add a ActionListener to a JButton:
// You are adding an ActionListener to the button
//Using the method addActionListener and a anonymous inner class
button.addActionListener(new ActionListener() {//anonymous inner class
#Override
public void actionPerformed(ActionEvent arg0)
{
button.setText("Text modified by an event called ActionEvent!");
}
});
I decided to play with similar code and came up with this bit of code that tries to show the state of things in a status bar at the bottom:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
#SuppressWarnings({ "serial"})
// so the compiler won't complain
public class MyWindPanel extends JPanel {
private static final int PREF_W = 1200;
private static final int PREF_H = 600;
private static final String MOUSE_LOCATION = "Mouse Location [%04d, %04d]";
private static final String COMPONENT_STATE = "Component: %-15s";
private static final String TIMER_LABEL = "Elapsed Time: %02d:%02d:%02d:%03d";
private static final int TIMER_DELAY = 20;
private static final String MOUSE_STATE = "Mouse State: %-15s";
public static final String BUTTON_TEXT = "Set MyWindPanel %s";
private JLabel mouseLocation = new JLabel(
String.format(MOUSE_LOCATION, 0, 0));
private JLabel mouseState = new JLabel(String.format(MOUSE_STATE, ""));
private JLabel componentState = new JLabel(
String.format(COMPONENT_STATE, ""));
private JLabel timerLabel = new JLabel(
String.format(TIMER_LABEL, 0, 0, 0, 0));
private long startTime = System.currentTimeMillis();
private Action buttonAction = new MyButtonAction(String.format(BUTTON_TEXT, "Invisible"));
private JPanel statusPanel;
public MyWindPanel() {
setBackground(Color.pink);
Font font = new Font(Font.MONOSPACED, Font.BOLD, 14);
mouseLocation.setFont(font);
mouseState.setFont(font);
componentState.setFont(font);
timerLabel.setFont(font);
statusPanel = new JPanel();
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.LINE_AXIS));
statusPanel.add(mouseLocation);
statusPanel.add(Box.createHorizontalStrut(25));
statusPanel.add(mouseState);
statusPanel.add(Box.createHorizontalStrut(25));
statusPanel.add(componentState);
statusPanel.add(Box.createHorizontalStrut(25));
statusPanel.add(timerLabel);
new Timer(TIMER_DELAY, new TimerListener()).start();
MouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseMotionListener(myMouseAdapter);
addMouseListener(myMouseAdapter);
addComponentListener(new MyComponentListener());
setLayout(new BorderLayout());
// add(statusPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public Action getButtonAction() {
return buttonAction;
}
public JComponent getStatusPanel() {
return statusPanel;
}
private class TimerListener implements ActionListener {
private static final int SECONDS_PER_MIN = 60;
private static final int MSEC_PER_SEC = 1000;
private static final int MIN_PER_HOUR = 60;
#Override
public void actionPerformed(ActionEvent evt) {
if (!MyWindPanel.this.isDisplayable()) {
((Timer) evt.getSource()).stop(); // so timer will stop when program
// over
}
long currentTime = System.currentTimeMillis();
long diff = currentTime - startTime;
int hours = (int) (diff / (MIN_PER_HOUR * SECONDS_PER_MIN * MSEC_PER_SEC));
int minutes = (int) (diff / (SECONDS_PER_MIN * MSEC_PER_SEC))
% MIN_PER_HOUR;
int seconds = (int) ((diff / MSEC_PER_SEC) % SECONDS_PER_MIN);
int mSec = (int) diff % MSEC_PER_SEC;
timerLabel.setText(String.format(TIMER_LABEL, hours, minutes, seconds,
mSec));
}
}
private class MyComponentListener extends ComponentAdapter {
#Override
public void componentHidden(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Hidden"));
}
#Override
public void componentMoved(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Moved"));
}
#Override
public void componentResized(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Resized"));
}
#Override
public void componentShown(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Shown"));
}
}
private class MyButtonAction extends AbstractAction {
public MyButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
boolean visible = MyWindPanel.this.isVisible();
String text = visible ? "Visible" : "Invisible";
((AbstractButton) e.getSource()).setText(String.format(BUTTON_TEXT, text));
MyWindPanel.this.setVisible(!MyWindPanel.this.isVisible());
Window win = SwingUtilities.getWindowAncestor(MyWindPanel.this);
win.revalidate();
win.repaint();
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
mouseLocation.setText(String.format(MOUSE_LOCATION, e.getX(), e.getY()));
}
#Override
public void mouseDragged(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Dragged"));
mouseLocation.setText(String.format(MOUSE_LOCATION, e.getX(), e.getY()));
}
public void mousePressed(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Pressed"));
};
public void mouseReleased(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Released"));
};
public void mouseEntered(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Entered"));
};
public void mouseExited(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Exited"));
};
}
private static void createAndShowGui() {
MyWindPanel mainPanel = new MyWindPanel();
JPanel topPanel = new JPanel();
topPanel.add(new JButton(mainPanel.getButtonAction()));
JFrame frame = new JFrame("MyWind");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.getContentPane().add(topPanel, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel.getStatusPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
this code is only allowing me to reject a string the second time to try to drop in a textArea where there is all ready a string.
public GridLayoutTest() {
JFrame frame = new JFrame("GridLayout test");
connection = getConnection();
try {
statement = (PreparedStatement) connection
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
}
}
catch (SQLException e) {
e.printStackTrace();}
}
So, two things, first...
public void DropTargetTextArea(String string1, String string2) {
Isn't a constructor, it's a method, note the void. This means that it is never getting called. It's also the reason why DropTargetTextArea textArea = new DropTargetTextArea(); works, when you think it shouldn't.
Second, you're not maintaining a reference to the values you pass in to the (want to be) constructor, so you have no means to references them later...
You could try using something like...
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true);
}
And then use something like...
if (values[0].equals(dragContents) || values[1].equals(dragContents)) {
In the drop method.
In your dragEnter, dragOver and dropActionChanged methods you have the oppurtunity to accept or reject the drag action using something like dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); or dtde.rejectDrag();
Updated with test code
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DragAndDropExample {
public static void main(String[] args) {
ImageIcon ii1 = new ImageIcon("C:\\Users\\Desktop\\home.jpg");
ImageIcon ii = new ImageIcon("C:\\Users\\Desktop\\images (2).jpg");
// Create a frame
JFrame frame = new JFrame("test");
JLabel label = new JLabel(ii);
JLabel label1 = new JLabel(ii1);
JPanel panel = new JPanel(new GridLayout(2, 4, 10, 10));
JLabel testLabel = new DraggableLabel("test");
JLabel testingLabel = new DraggableLabel("testing");
panel.add(testLabel);
panel.add(testingLabel);
panel.add(label);
panel.add(label1);
Component textArea = new DropTargetTextArea("test", "testing");
frame.add(textArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class DraggableLabel extends JLabel implements DragGestureListener, DragSourceListener {
DragSource dragSource1;
public DraggableLabel(String text) {
setText(text);
dragSource1 = new DragSource();
dragSource1.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent evt) {
Transferable transferable = new StringSelection(getText());
dragSource1.startDrag(evt, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent evt) {
System.out.println("Drag enter");
}
public void dragOver(DragSourceDragEvent evt) {
System.out.println("Drag over");
}
public void dragExit(DragSourceEvent evt) {
System.out.println("Drag exit");
}
public void dropActionChanged(DragSourceDragEvent evt) {
System.out.println("Drag action changed");
}
public void dragDropEnd(DragSourceDropEvent evt) {
System.out.println("Drag action End");
}
}
public static class DropTargetTextArea extends JLabel implements DropTargetListener {
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void dragEnter(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag enter");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragOver(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag over");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragExit(DropTargetEvent evt) {
System.out.println("Drop exit");
}
public void dropActionChanged(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject dropActionChanged");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void drop(DropTargetDropEvent evt) {
if (!getText().isEmpty()) {
evt.rejectDrop();
} else {
try {
Transferable transferable = evt.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String dragContents = (String) transferable.getTransferData(DataFlavor.stringFlavor);
evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
if (values[0].equals(dragContents) || (values[1]).equals(dragContents)) {
System.out.println("Accept Drop");
setText(getText() + " " + dragContents);
evt.getDropTargetContext().dropComplete(true);
} else {
System.out.println("Reject Drop");
}
}
} catch (IOException e) {
evt.rejectDrop();
evt.dropComplete(false);
} catch (UnsupportedFlavorException e) {
}
}
}
}
}