I can't get this to work:
public void ru() throws InterruptedException {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
}
private void BtnRoomsMouseEntered(java.awt.event.MouseEvent evt) {
try {
ru();
} catch (InterruptedException ex) {
}
}
Any solutions?
I want a jLabel to show a slide show when a mouse enters a certain button and stays like that as long as the mouse is still in a button. If the mouse happens to exit the button, the jlabel will return to a null state. (no more anything.) Is that possible? Please help. I also tried using for statement but no good. I'm using netbeans by the way.
First thing you need to implement a javax.swing.Timer. Trying to call Thread.sleep() will block the Event Dispatch Thread. See How to use Swing Timers. Here is the basic construct
Timer(int delay, ActionListener listener)
where delay is the time in milliseconds you want delayed and the listener will listen for the Timer ActionEvent fired every delay milliseconds.
So you want something like this
public class MyFrame extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[3];
int index = -1;
public MyFrame() {
initComponents();
icons[0] = new ImageIcon(...);
icons[1] = new ImageIcon(...);
icons[2] = new ImageIcon(...);
timer = new Timer(2000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (index + 1 > 2) {
index = 0;
jLabel3.setIcon(icons[index]);
} else {
index++;
jLabel3.setIcon(icons[index]);
}
}
});
}
}
For your button, you need to use mouseEntered and mouseExited, then you can just call timer.start() or timer.stop()
private void jButton1MouseExited(MouseEvent e) {
timer.stop();
}
private void jButton1MouseEntered(MouseEvent e) {
timer.start();
}
If you don't know how to add the MouseListener just right click on the button from the design view and select Event -> Mouse -> mouseEntered. Do the same for mouseExited. You should see the above methods auto-generated for you.
UPDATE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class ImageViewer extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[5];
int index = -1;
public ImageViewer() {
initComponents();
try {
icons[0] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
icons[1] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
icons[2] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
icons[3] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
icons[4] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE, null, ex);
}
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index + 1 > 4) {
index = 0;
jLabel1.setIcon(icons[index]);
} else {
index++;
jLabel1.setIcon(icons[index]);
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new JButton();
jLabel1 = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
jButton1MouseEntered(evt);
}
public void mouseExited(MouseEvent evt) {
jButton1MouseExited(evt);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(127, 127, 127))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>
private void jButton1MouseEntered(MouseEvent evt) {
timer.start();
}
private void jButton1MouseExited(MouseEvent evt) {
timer.stop();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ImageViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JButton jButton1;
private JLabel jLabel1;
// End of variables declaration
}
You want to add a MouseAdapter to the JLabel and use its mouseEntered() and mouseExited() as follows:
jLabel3.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
} catch(InterruptedException e) {
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
//whatever you mean by "null state"
}
});
Related
I'm trying to implement a JprogressBar to show the data insertion progress.
Basically the user select how many data sources will be imported to database.
With this parameter the main program Start a method to list those parameters and with a foreach loop it calls the insertion Thread and the ProgressBar update Thread.
for (Maquina i : m.listar()) {
//Passing to Import Thread the object with the data and a Date parameter
ImportarDados imp = new ImportarDados(i, jDateInicial.getDate());
//Calling progress bar update Thread with the progressbar itself and progress parameter
BarraDeProgresso bp = new BarraDeProgresso(progresso, progImportacao);
imp.run();
bp.run();
}
The threads kinda work on their own, but the result is not the one I want, cause the data is being imported and the progressbar is being updated, but it is being update to 100% after all data is imported. I need to update the progress bar as long as the import thread finish the importation for each (Maquina i) object.
If it is necessary I can provide the threads code...but i don't know if this calling method can provide the result I want. Searching on the forum i found something about EDT and i think it is the problem that the bar is not being updated. Can you guys help me solving this?
Minimal and Verifiable example:
My code is pretty short. The code generated by netbeans is huge, sry for that.
That code simulate my problem. The windows is refreshed only after the for loop is finished. But the BarraDeProgresso thread is running at the same as and SysOut some info...
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
public class Minimo extends javax.swing.JFrame {
public Minimo() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int progImportacao[] = {0};
progresso.setMaximum(15);
for (int i = 0; i <= 15; i++) {
ImportarDados imp = new ImportarDados(i,lblProgresso);
BarraDeProgresso bp = new BarraDeProgresso(progresso, progImportacao);
imp.run();
bp.run();
progImportacao[0] += 1;
}
}
Component Initialization (Netbeans Generated)
private void initComponents() {
progresso = new javax.swing.JProgressBar();
lblProgresso = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblProgresso.setText("...");
jButton1.setText("IMPORT DATA");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblProgresso)
.addComponent(progresso, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(47, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(191, 191, 191))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addComponent(lblProgresso)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(progresso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37))
);
pack();
}// </editor-fold>
Runnable classes
class BarraDeProgresso implements Runnable {
public JProgressBar jProgressBar1;
public int progresso[];
public BarraDeProgresso(JProgressBar barra, int progresso[]) {
this.jProgressBar1 = barra;
this.progresso = progresso;
}
#Override
public void run() {
try {
Thread.sleep(0);
System.out.println("TBARRA PROG " + progresso[0]);
jProgressBar1.setValue(progresso[0]);
jProgressBar1.repaint();
} catch (InterruptedException e) {
}
}
}
class ImportarDados implements Runnable {
private int pi = 0;
JLabel x;
public ImportarDados(int i, JLabel tag) {
this.pi = i;
this.x = tag;
}
#Override
public void run() {
try {
Thread.sleep(500);
x.setText(Integer.toString(pi)+" /15");
} catch (InterruptedException ex) {
Logger.getLogger(Minimo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Main (Netbeans Generated)
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Minimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Minimo().setVisible(true);
}
});
}
Your current code creates no background thread. Yes you've got Runnables, but you call run() on them, meaning you are calling them on the Swing event thread. When you do this, you block the event thread, effectively freezing your program. Instead, you need to:
Create a true background thread by passing your Runnable into a Thread object's constructor and calling start() on that Thread.
Not mutate Swing components from within these background threads
Or use a SwingWorker as per the Lesson: Concurrency in Swing which will help solve both of the above issues.
For an example of use of a SwingWorker, please see:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Minimo2 extends JPanel {
private static final int EB_GAP = 15;
private static final int PROG_BAR_WDTH = 400;
public static final int MAX_DATA = 15;
private JProgressBar progresso;
private JLabel lblProgresso;
private JButton jButton1;
private Action importDataAction = new ImportDataAction("Import Data");
public Minimo2() {
initComponents();
}
private void initComponents() {
progresso = new JProgressBar(0, MAX_DATA);
lblProgresso = new JLabel(" ");
jButton1 = new JButton(importDataAction);
int progBarHeight = progresso.getPreferredSize().height;
progresso.setPreferredSize(new Dimension(PROG_BAR_WDTH, progBarHeight));
progresso.setStringPainted(true);
JPanel btnPanel = new JPanel();
btnPanel.add(jButton1);
JPanel labelPanel = new JPanel();
labelPanel.add(lblProgresso);
JPanel progressPanel = new JPanel();
progressPanel.add(progresso);
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(btnPanel);
add(Box.createVerticalStrut(EB_GAP));
add(labelPanel);
add(Box.createVerticalStrut(EB_GAP));
add(progressPanel);
}
private class ImportDataAction extends AbstractAction {
public ImportDataAction(String name) {
super(name); // give the button text
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic); // give it a hot key
}
#Override
public void actionPerformed(ActionEvent e) {
setEnabled(false); // disable our button
ImportDataWorker worker = new ImportDataWorker(MAX_DATA);
worker.addPropertyChangeListener(new WorkerListener());
worker.execute();
}
}
private class WorkerListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progValue = (int) evt.getNewValue();
progresso.setValue(progValue);
String text = String.format("%02d/15", progValue);
lblProgresso.setText(text);
} else if ("state".equals(evt.getPropertyName())) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
#SuppressWarnings("rawtypes")
SwingWorker worker = (SwingWorker)evt.getSource();
try {
worker.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
progresso.setValue(MAX_DATA);
String text = String.format("%02d/15", MAX_DATA);
lblProgresso.setText(text);
importDataAction.setEnabled(true);
}
}
}
}
private class ImportDataWorker extends SwingWorker<Void, Void> {
private static final long SLEEP_TIME = 500;
private int max;
public ImportDataWorker(int max) {
this.max = max;
}
#Override
protected Void doInBackground() throws Exception {
for (int i = 0; i < max; i++) {
setProgress(i);
Thread.sleep(SLEEP_TIME);
}
return null;
}
}
private static void createAndShowGui() {
Minimo2 mainPanel = new Minimo2();
JFrame frame = new JFrame("Minimo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
My program has to print messages in the JTextField when the Resume Producers button is pressed, and it needs to delete the messages when the Resume Consumers is pressed.
The thing is that I don't know how to delete the messages when the Resume Consumers is pressed.
Code:
package buffer;
import java.util.ArrayList;
import javax.swing.JTextField;
public class Buffer
{
private String message;
private boolean full=false;
Topass pass = new Topass();
public ArrayList<String> list = new ArrayList<String> ();
JTextField tf;
String content="";
public Buffer(JTextField t1){
tf=t1;
}
public synchronized void put(String message)
{
list.add(message);
}
public synchronized void take(String message)
{
list.remove(message);
}
public synchronized void sendMessage(String msg)
{
while(full && list.size()>=30)
{
try
{
wait();
} catch (InterruptedException ex) { }
}
pass.look();
full=true;
message=msg;
list.add(message);
for(int i=0; i<list.size(); i++){
content=content+list.get(i);
}
tf.setText(content);
notifyAll();
}
public synchronized String receivesMessage()
{
while(!full)
{
try
{
wait();
} catch (InterruptedException ex) { }
}
pass.look();
full=false;
notifyAll();
return message;
}
}
package buffer;
import static java.lang.Thread.sleep;
import javax.swing.JButton;
public class Consumer extends Thread
{
private int numMessages;
private Buffer miBuffer;
private String readers;
public Consumer(String reader, Buffer miBuffer)
{
this.numMessages=numMessages;
this.miBuffer=miBuffer;
this.readers=reader;
}
#Override
public void run()
{
while(true){
try
{
sleep((int)(300+400*Math.random()));
} catch(InterruptedException e){ }
System.out.println(readers + " Has read " + miBuffer.receivesMessage());
}
}
}
package buffer;
import static java.lang.Thread.sleep;
import java.util.ArrayList;
public class Producer extends Thread
{
private String prefix;
private int numMessages;
private Buffer miBuffer;
public Producer(String prefix, int n, Buffer buffer)
{
this.prefix=prefix;
numMessages=n;
miBuffer=buffer;
}
public void run()
{
numMessages = 99;
for(int i=1; i<=numMessages; i++)
{
try
{
sleep((int)(500+400*Math.random()));
} catch(InterruptedException e){ }
miBuffer.sendMessage(prefix+i);
//miBuffer.meter(prefijo+i);
}
}
}
package buffer;
public class Topass
{
private boolean closed=false;
public synchronized void look()
{
while(closed)
{
try
{
wait();
} catch(InterruptedException ie){ }
}
}
public synchronized void open()
{
closed=false;
notifyAll();
}
public synchronized void closed()
{
closed=true;
}
}
package buffer;
import java.awt.Container;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import static jdk.nashorn.internal.objects.ArrayBufferView.buffer;
/**
*
* #author Bogdan
*/
public class DigitalBuffer extends javax.swing.JFrame
{
Buffer buffer;
Producer p;
Consumer c;
Topass paso = new Topass();
/**
* Creates new form BufferGrafico
*/
public DigitalBuffer() {
initComponents();
buffer = new Buffer(t1);
Producer A = new Producer("A",99,buffer);
Producer B = new Producer("B",99,buffer);
Producer C = new Producer("C",99,buffer);
Producer D = new Producer("D",99,buffer);
Consumer Luis = new Consumer("LUIS", buffer);
Consumer Juan = new Consumer("JUAN", buffer);
Consumer Maria = new Consumer("MARIA", buffer);
Consumer Ana = new Consumer ("ANA", buffer);
A.start();
B.start();
C.start();
D.start();
Luis.start();
Juan.start();
Maria.start();
Ana.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
t1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
JButton1 = new javax.swing.JButton();
JButton2 = new javax.swing.JButton();
JButton3 = new javax.swing.JButton();
JButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
t1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t1ActionPerformed(evt);
}
});
jLabel2.setText("Buffer content");
JButton1.setText("Stop Producers");
JButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton1ActionPerformed(evt);
}
});
JButton2.setText("Resume Producers");
JButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton2ActionPerformed(evt);
}
});
JButton3.setText("Stop Consumers");
JButton3.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
JButton3AncestorAdded(evt);
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
JButton3AncestorRemoved(evt);
}
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
});
JButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton3ActionPerformed(evt);
}
});
JButton4.setText("Resume Consumers");
JButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(91, 91, 91)
.addComponent(JButton1)
.addGap(80, 80, 80)
.addComponent(JButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(102, 102, 102))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(104, 104, 104)
.addComponent(JButton3)
.addGap(77, 77, 77)
.addComponent(JButton4)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(70, 70, 70)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addComponent(jLabel1))
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JButton1)
.addComponent(JButton2))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JButton3)
.addComponent(JButton4))
.addContainerGap(64, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void t1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void JButton1ActionPerformed(java.awt.event.ActionEvent evt) {
buffer.pass.closed();
}
private void JButton2ActionPerformed(java.awt.event.ActionEvent evt) {
buffer.pass.open();
}
private void JButton3ActionPerformed(java.awt.event.ActionEvent evt) {
buffer.pass.closed();
}
private void JButton4ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void JButton3AncestorAdded(javax.swing.event.AncestorEvent evt) {
// TODO add your handling code here:
}
private void JButton3AncestorRemoved(javax.swing.event.AncestorEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DigitalBuffer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton JButton1;
private javax.swing.JButton JButton2;
private javax.swing.JButton JButton3;
private javax.swing.JButton JButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField t1;
// End of variables declaration
}
The thing is that i don't know how to delete the messages when the Resume Consumers is pressed
You add an ActionListener to the button. In the ActionListener you reset the text. See the section from the Swing tutorial on How to Us Buttons for more information and examples. Or, there is also a section on How to Write an ActionListener.
You can replace the text in the text field by using:
textField.setText(...);
Example #1 (Requires Java 8+):
button.addActionListener(e -> textField.setText(""));
Example #2:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
In both cases, the textField will need to have been declared as final.
I'm making one jInternalFrame where I'am adding tabs dynamically.
now adding a new TAB I have coded,
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JTabbedPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.basic.BasicInternalFrameUI;
/**
*
* #author santoshg
*/
public class jTAB extends javax.swing.JFrame {
/**
* Creates new form jTAB
*/
JTabbedPane tabList = new JTabbedPane();
int nUserCount = 1;
boolean isDrag = true;
private static int pressedX = 0, pressedY = 0;
JDesktopPane sDesktoppane = new JDesktopPane();
JComponent northPane;
public jTAB() {
this.setUndecorated(true);
initComponents();
drag();
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
public final void drag() {
setContentPane(sDesktoppane);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
jInternalFrame1.addInternalFrameListener(new InternalFrameListener() {
#Override
public void internalFrameOpened(InternalFrameEvent e) {
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
}
#Override
public void internalFrameClosed(InternalFrameEvent e) {
}
#Override
public void internalFrameIconified(InternalFrameEvent e) {
jInternalFrame1.setIconifiable(true);
}
#Override
public void internalFrameDeiconified(InternalFrameEvent e) {
}
#Override
public void internalFrameActivated(InternalFrameEvent e) {
}
#Override
public void internalFrameDeactivated(InternalFrameEvent e) {
}
});
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
`enter code here` setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
if (northPane == null) {
northPane = ((BasicInternalFrameUI) jInternalFrame1.getUI()).getNorthPane();
northPane.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if (isDrag) {
System.out.println("pressedX and pressedY " + pressedX + " " + pressedY);
pressedX = e.getX();
pressedY = e.getY();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
northPane.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (isDrag) {
int draggedObjX = getLocation().x + e.getX() - pressedX;
int draggedObjY = getLocation().y + e.getY() - pressedY;
setLocation(draggedObjX, draggedObjY);
getjInternalFrame().setLocation(0, 0);
}
}
public void mouseMoved(MouseEvent e) {
}
});
}
sDesktoppane.add(jInternalFrame1);
jInternalFrame1.setVisible(true);
jInternalFrame1.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
setSize(jInternalFrame1.getSize().width, jInternalFrame1.getSize().height);
}
});
setSize(jInternalFrame1.getSize());
if (northPane == null) {
setLocation(new Point(pressedX, pressedY));
}
super.setVisible(true);
}
public JInternalFrame getjInternalFrame() {
return jInternalFrame1;
}
public JComponent getNorthPane() {
return northPane;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setMaximizable(true);
jInternalFrame1.setVisible(true);
jButton1.setText("Add TAB");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 512, Short.MAX_VALUE)
.addComponent(jButton1))
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 301, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1, javax.swing.GroupLayout.Alignment.TRAILING)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
tabList.addTab("User " + nUserCount, new ChatWindow("user " + nUserCount).getFrameComponent());
JComponent jif = (JComponent) jInternalFrame1.getContentPane();
jif.setLayout(new BorderLayout());
jif.add(tabList);
nUserCount++;
}//GEN-LAST:event_jButton1ActionPerformed
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new jTAB().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JInternalFrame jInternalFrame1;
// End of variables declaration//GEN-END:variables
}
Where ChatWindow,java is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import javax.swing.JComponent;
/**
*
* #author santoshg
*/
public class ChatWindow extends javax.swing.JFrame {
/**
* Creates new form ChatWindow
*/
public ChatWindow() {
initComponents();
}
public ChatWindow(String userName) {
initComponents();
lblUserName.setText(userName);
}
public JComponent getFrameComponent(){
return jPanel1;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblUserName = new javax.swing.JLabel();
lblAvatar = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
lblUserDept = new javax.swing.JLabel();
lblContactInfo = new javax.swing.JLabel();
lblSendFile = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblUserName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblUserName.setText("UserName");
lblUserName.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
lblAvatar.setText("Avatar");
lblAvatar.setAlignmentX(0.5F);
lblAvatar.setAlignmentY(0.2F);
lblAvatar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lblAvatar.setIconTextGap(2);
lblAvatar.setPreferredSize(new java.awt.Dimension(35, 15));
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(249, 251, 252));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTextArea2.setColumns(20);
jTextArea2.setRows(2);
jTextArea2.setMinimumSize(new java.awt.Dimension(3, 22));
jScrollPane2.setViewportView(jTextArea2);
lblUserDept.setText("Department");
lblContactInfo.setToolTipText("User Info");
lblSendFile.setToolTipText("Send File");
jLabel1.setToolTipText("View History");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
.addComponent(lblUserDept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 355, Short.MAX_VALUE)
.addComponent(lblContactInfo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSendFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblContactInfo)
.addComponent(lblSendFile))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblUserDept))
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JLabel lblAvatar;
private javax.swing.JLabel lblContactInfo;
private javax.swing.JLabel lblSendFile;
private javax.swing.JLabel lblUserDept;
private javax.swing.JLabel lblUserName;
// End of variables declaration//GEN-END:variables
}
Hit the add button twice you'll get 2 TABS not when I maximize it "Add TAB" moved to Middle and Textareas are in top.
I want jTextAtrea1 to expand till the bottom of the page during maximize and restore to actual size during toggle.
I want jTextAtrea1 to expand till the bottom of the page during maximize
Sounds like you should be using a BorderLayout for the panel you add to the tab. Then you add the text area to the BorderLayout.CENTER and the other components to the BorderLayout.NORTH.
It looks like your layout code is generated by an IDE. Don't use the IDE to generate layout code. Do the layout yourself and you will be in full control.
I am working on an application and I want the jpanel to move around inside jframe at run time. here is the code I used
package testing;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ChangePanel extends javax.swing.JFrame {
public ChangePanel() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jPanel1MousePressed(evt);
}
});
jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel1MouseDragged(evt);
}
});
jLabel1.setText("panel to move");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jLabel1)
.addContainerGap(119, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel1)
.addContainerGap(81, Short.MAX_VALUE))
);
getContentPane().add(jPanel1);
jPanel1.setBounds(160, 60, 247, 161);
pack();
}// </editor-fold>
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
MouseAdapter ma = new MouseAdapter() {
int lastX =0, lastY =0;
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
// Move frame by the mouse delta
setLocation(getLocationOnScreen().x + x - lastX,
getLocationOnScreen().y + y - lastY);
lastX = x;
lastY = y;
}
};
}
private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {
MouseAdapter ma = new MouseAdapter() {
int lastX, lastY;
#Override
public void mousePressed(MouseEvent e) {
lastX = e.getXOnScreen();
lastY = e.getYOnScreen();
}};
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChangePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
but is not working
Some time ago, I've written a framework for such tasks. Maybe you find it useful (the library is Open Source):
Tutorial:
http://softsmithy.sourceforge.net/lib/current/docs/tutorial/swing/customizer/index.html
Javadoc:
http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-swing-customizer/index.html
Info about the latest release:
http://puces-blog.blogspot.ch/2013/11/news-from-software-smithy-version-04.html
There's no need to put a MouseAdapter within an already defined Listener. In fact, you're simply declaring one and not using it in any way. Simply keep it inside the dragged event.
Like this. You can adapt it to the calculations you need to do.
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
jPanel1.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
}
I found on the Web code: http://java-sl.com/tip_autoreplace_smiles.html which I edited to my own needs, take a look:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Emotes extends JEditorPane {
public Emotes() {
super();
this.setEditorKit(new StyledEditorKit());
this.initListener();
}
private void replace (String text, StyledDocument doc, ImageIcon icon, int start, String what) throws BadLocationException
{
int i = text.indexOf(what);
while(i >= 0)
{
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start+i).getAttributes());
if (StyleConstants.getIcon(attrs) == null)
{
StyleConstants.setIcon(attrs, icon);
doc.remove(start+i, what.length());
doc.insertString(start+i,what, attrs);
}
i = text.indexOf(what, i+what.length());
}
}
private void initListener() {
getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent event) {
final DocumentEvent e=event;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (e.getDocument() instanceof StyledDocument) {
try {
StyledDocument doc=(StyledDocument)e.getDocument();
int start= Utilities.getRowStart(Emotes.this,Math.max(0,e.getOffset()-1));
int end=Utilities.getWordStart(Emotes.this,e.getOffset()+e.getLength());
String text=doc.getText(start, end-start);
replace(text, doc, createEmoticon("wink.png"), start, ";)");
replace(text, doc, createEmoticon("wink.png"), start, "<wink>");
replace(text, doc, createEmoticon("sad.png"), start, ":(");
replace(text, doc, createEmoticon("sad.png"), start, "<sad>");
replace(text, doc, createEmoticon("smile.png"), start, ":)");
replace(text, doc, createEmoticon("smile.png"), start, "<smile>");
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
}
static ImageIcon createEmoticon(String icon)
{
BufferedImage img = null;
try
{
img = ImageIO.read(new File(icon));
Graphics g = img.getGraphics();
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}catch (IOException ex)
{
}
return new ImageIcon(img);
}
}
which works great. But I created in Netbeans a new GUI (JDialog Window) with JEditorPane on it, where I want to use this feature on JDialog window:
but it doesnt want to work at all. When I type ":)" its not changing in an image.
Just try to run that code:
public class NewJDialog extends javax.swing.JDialog {
/** Creates new form NewJDialog */
public NewJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jEditorPane1 = new Emotes();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jScrollPane1.setViewportView(jEditorPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
And the emotes I use are:
An application is compiled to a .jar file. Normal File I/O then does not take (the current directory varies depending on the call). Take the images out of the jar/class path as:
img = ImageIO.read(Emotes.class.getResourceAsStream(icon));