Java TextArea Update On The Fly - java

I'm working on a program and I'm having problems with printing my results on the TextArea on the fly (similar as you can do with System.out.print("")) and need them to append on the text area. I want to use this as process steper window.
I have tried to call in new Thread and some other stuff, but no success. I'm really stuck here.
Any help would be really appreciated.
Here is the example code. In the StdOut you can see when the code is executed, and at that time it should be also visible in TextArea but it appears on it when the method is complete. It should append the text on TextArea the same time as stdout is executed.
public class Start {
public static void main(String[] args) {
Manager.getInstance();
}
}
public class Manager {
public static Manager instance;
private MyFrame mainFrame;
private Manager(){
mainFrame = MyFrame.newInstance();
mainFrame.setVisible(true);
}
public static Manager getInstance() {
if(instance == null){
instance = new Manager();
}
return instance;
}
public void startMethod() {
for(int i = 0; i < 5000; i++){
doSmething();
if(i == 0){
sendMsg("Start");
}
}
sendMsg("End");
}
private void doSmething() {
try{
Thread.sleep(1);
}
catch (InterruptedException e){
}
}
private void sendMsg(String str){
(new Thread(new MyFrameMsg(mainFrame,str))).start();
mainFrame.setTextArea(str);
System.out.println(str);
}
}
class MyFrameMsg implements Runnable{
private MyFrame mainFrame;
private String str;
public MyFrameMsg(MyFrame _mainComander, String _str) {
mainFrame = _mainComander;
str = _str;
}
#Override
public void run() {
System.out.println(str + " in thread");
mainFrame.setTextArea(str);
}
}
Build with Netbeans
public class MyFrame extends javax.swing.JFrame {
private static MyFrame instance;
public MyFrame(){
initComponents();
instance = this;
}
public static MyFrame newInstance() {
if(instance == null){
new MyFrame();
}
return instance;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textArea.setEditable(false);
textArea.setColumns(20);
textArea.setRows(5);
jScrollPane1.setViewportView(textArea);
startButton.setText("Start");
startButton.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()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(162, 162, 162)
.addComponent(startButton)
.addContainerGap(181, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(98, Short.MAX_VALUE)
.addComponent(startButton)
.addGap(39, 39, 39)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton startButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea textArea;
// End of variables declaration
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Manager.getInstance().startMethod();
}
public void setTextArea(String str) {
textArea.append(str + System.getProperty("line.separator"));
}
}

You have to Thread your startMethod() like this:
public void startMethod() {
new Thread() {
public void run() {
for (int i = 0; i < 5000; i++) {
doSmething();
if (i == 0) {
sendMsg("Start");
}
}
sendMsg("End");
}
}.start();
}
The problem with your design is following:
The AWT-EventQueue fires your ButtonEvent and than creates 5000 Threaded Objects.
These will run and update your TextArea, but the TextArea will only be repainted after the AWT-Eventqueue-Thread is released (after creating all 5000 Objects)
And you should not need to Thread your MyFrameMsg class anymore (except they should do more than an short update in the future)

Related

jProgressBar with Threads for Database data Insertion

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

How to delete text from a JTextField when you press a JButton (JAVA)

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.

Can't update the old JPane to Panel

The main purpose of my small app is to update the Panel, which is in the only one Frame, by pressing 'Enter' button pressed on keyboard.
Here are the classes:
Main - starts the app;
MainFrame - is the Frame with methods to update it;
PanelWithNoThreads - is the class of Panel, which is created while init of the Frame take place;
PanelWithNoFramesContr - is controlling everything what happens with PanelWithNoThreads.
PanelWithThread and PanelWithThreadContr - is the screen and it's controller, quite the same things as the previous pare is.
I'll put the code in the end of this post.
SO, THE PROBlEM IS...
When we start the app, everything works, and PanelWithNoThreads appears.
I press ENTER and after that my Frame shows me white screen...
So, how to solve this problem.
class Main
public class Main {
static MainFrame mainFrame;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
mainFrame = new MainFrame();
}
}
class MainFrame:
public class MainFrame extends JFrame implements KeyListener{
JPanel theMainPanel = new JPanel();
PanelWithThreadContr pwntContr;
static String idOfPanel = "empty_panel";
public MainFrame(){
setSize(800,600);
setExtendedState(MAXIMIZED_BOTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
theMainPanel.setBackground(Color.BLACK);
theMainPanel.setForeground(Color.WHITE);
add(theMainPanel);
System.out.println("LOG/MainFrame : added the empty Panel");
//default change to the Panel with no Threads
PanelWithNoFramesContr ntpc = new PanelWithNoFramesContr();
changeThePane(ntpc.pwnt, ntpc.getId(), ntpc);
}
private void changeThePane(JPanel inputPanel, String id, KeyListener keyListener){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
remove(theMainPanel);
theMainPanel = inputPanel;
add(theMainPanel);
addKeyListener(keyListener);
repaint();
theMainPanel.validate();
theMainPanel.repaint();
theMainPanel.setVisible(true);
}
});
}
public void implementThePane(String id){
if(id.contains("one_thread")){
pwntContr = new PanelWithThreadContr();
changeThePane(pwntContr.pwt, pwntContr.id, pwntContr);
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
class PanelWithNoThreads:
public class PanelWithNoThreads extends javax.swing.JPanel {
/**
* Creates new form PanelWithNoThreads
*/
public PanelWithNoThreads() {
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() {
HelloLabel = new javax.swing.JLabel();
HelloLabel.setFont(new java.awt.Font("Osaka", 0, 48)); // NOI18N
HelloLabel.setText("Hello!!!");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(HelloLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(HelloLabel)
.addContainerGap(164, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel HelloLabel;
// End of variables declaration
public void setColorsToHelloLabel(Color backColor, Color foreColor){
HelloLabel.setBackground(backColor);
HelloLabel.setForeground(foreColor);
}
}
class PanelWithNoThreadsContr:
public class PanelWithNoThreadsContr extends Controller implements KeyListener{
PanelWithNoThreads pwnt = new PanelWithNoThreads();
private String id = "no_threads";
public PanelWithNoThreadsContr() {
//settings
pwnt.setBackground(Color.BLACK);
pwnt.setForeground(Color.WHITE);
pwnt.setColorsToHelloLabel(Color.BLACK, Color.GREEN);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("LOG/no_thread : Pressed 'ENTER'");
if(e.getKeyCode() == KeyEvent.VK_ENTER){
Main.mainFrame.implementThePane("one_thread");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
}
class PanelWithThread:
public class PanelWithThread extends javax.swing.JPanel {
/**
* Creates new form PanelWithThread
*/
public PanelWithThread() {
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() {
threadedLabel = new javax.swing.JLabel();
threadedLabel.setFont(new java.awt.Font("ArcadeClassic", 0, 36)); // NOI18N
threadedLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
threadedLabel.setText("NO_TEXT");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(threadedLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(threadedLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
// Variables declaration - do not modify
public javax.swing.JLabel threadedLabel;
// End of variables declaration
}
class PanelWithThreadContr:
public class PanelWithThreadContr extends Controller implements KeyListener{
PanelWithThread pwt = new PanelWithThread();
String id = "one_thread";
public PanelWithThreadContr() {
System.out.println("LOG/one_thread : creating");
pwt.setBackground(Color.BLACK);
pwt.setForeground(Color.WHITE);
pwt.threadedLabel.setText("*****");
pwt.threadedLabel.setForeground(Color.GREEN);
pwt.threadedLabel.setBackground(Color.BLACK);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
}
}
}
You need to call super () in the constructors of each of your custom JPanels.

How to stop calling a method from another method in java?

I have a calculator code and the problem is:
public void valueCheck(String value,JToggleButton button) {
if(values.size()>2)
{
processValue(value);
button.setSelected(false);
JOptionPane.showMessageDialog(this, "You cant click 3 buttons at the same time..");
}
}
There is a method valueCheck and:
public boolean evenOdd(JToggleButton buton)
{
if(values.size()==2)
{
System.out.println((String)values.get(0));
System.out.println((String)values.get(1));
String number1 = new String(values.get(0));
String number2 = new String(values.get(1));
if(evenNumbers.contains(number1))
{
if(evenNumbers.contains(number2))
{
processValue(number1);
processValue(number2);
}
else if(oddNumbers.contains(number2))
{
buton.setSelected(false);
JOptionPane.showMessageDialog(this, "You cant click an even and an odd number at the same time..");
}
}
else if(oddNumbers.contains(number1))
{
if(oddNumbers.contains(number2))
{
processValue(number1);
processValue(number2);
}
else if(evenNumbers.contains(number2))
{
buton.setSelected(false);
JOptionPane.showMessageDialog(this, "You cant click an even and an odd number at the same time..");
}
}
}
return false;
}
there is a method evenOdd.
My problem is: I dont want valueCheck method to run for evenOdd method.When evenOdd method runs valueCheck must be stopped calling.Is there a event to do this?I want to stop calling valueCheck when evenOdd is running
Here is my whole code.
package tr.com.bites;
import com.sun.org.apache.xml.internal.utils.StopParseException;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
public class CalculatorView_1 extends javax.swing.JFrame {
JToggleButton[] buttons = new JToggleButton[4];
public CalculatorView_1() {
initComponents();
buttons[0]=jToggleButton12;
buttons[1]=jToggleButton11;
buttons[2]=jToggleButton10;
buttons[3]=jToggleButton13;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jToggleButton1 = new javax.swing.JToggleButton();
jToggleButton2 = new javax.swing.JToggleButton();
jToggleButton3 = new javax.swing.JToggleButton();
jToggleButton4 = new javax.swing.JToggleButton();
jToggleButton5 = new javax.swing.JToggleButton();
jToggleButton6 = new javax.swing.JToggleButton();
jToggleButton7 = new javax.swing.JToggleButton();
jToggleButton8 = new javax.swing.JToggleButton();
jToggleButton9 = new javax.swing.JToggleButton();
jToggleButton10 = new javax.swing.JToggleButton();
jToggleButton11 = new javax.swing.JToggleButton();
jToggleButton12 = new javax.swing.JToggleButton();
jToggleButton13 = new javax.swing.JToggleButton();
jToggleButton14 = new javax.swing.JToggleButton();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jToggleButton1.setText("1");
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
jToggleButton2.setText("2");
jToggleButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton2ActionPerformed(evt);
}
});
jToggleButton3.setText("3");
jToggleButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton3ActionPerformed(evt);
}
});
jToggleButton4.setText("5");
jToggleButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton4ActionPerformed(evt);
}
});
jToggleButton5.setText("4");
jToggleButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton5ActionPerformed(evt);
}
});
jToggleButton6.setText("6");
jToggleButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton6ActionPerformed(evt);
}
});
jToggleButton7.setText("8");
jToggleButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton7ActionPerformed(evt);
}
});
jToggleButton8.setText("7");
jToggleButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton8ActionPerformed(evt);
}
});
jToggleButton9.setText("9");
jToggleButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton9ActionPerformed(evt);
}
});
jToggleButton10.setText("*");
jToggleButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton10ActionPerformed(evt);
}
});
jToggleButton11.setText("-");
jToggleButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton11ActionPerformed(evt);
}
});
jToggleButton12.setText("+");
jToggleButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton12ActionPerformed(evt);
}
});
jToggleButton13.setText("/");
jToggleButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton13ActionPerformed(evt);
}
});
jToggleButton14.setText("=");
jToggleButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton14ActionPerformed(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(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToggleButton8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton9))
.addGroup(layout.createSequentialGroup()
.addComponent(jToggleButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton6))
.addGroup(layout.createSequentialGroup()
.addComponent(jToggleButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton3)))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jToggleButton12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(78, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToggleButton12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton10))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jToggleButton1)
.addComponent(jToggleButton2)
.addComponent(jToggleButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jToggleButton5)
.addComponent(jToggleButton4)
.addComponent(jToggleButton6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jToggleButton8)
.addComponent(jToggleButton7)
.addComponent(jToggleButton9))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton13)
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jToggleButton14)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(90, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("1");
valueCheck("1",jToggleButton1);
evenOdd(jToggleButton1);
}
private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("2");
valueCheck("2",jToggleButton2);
evenOdd(jToggleButton2);
}
private void jToggleButton3ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("3");
valueCheck("3",jToggleButton3);
evenOdd(jToggleButton3);
}
private void jToggleButton5ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("4");
valueCheck("4",jToggleButton5);
evenOdd(jToggleButton5);
}
private void jToggleButton4ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("5");
valueCheck("5",jToggleButton4);
evenOdd(jToggleButton4);
}
private void jToggleButton6ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("6");
valueCheck("6",jToggleButton6);
evenOdd(jToggleButton6);
}
private void jToggleButton8ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("7");
valueCheck("7",jToggleButton8);
evenOdd(jToggleButton8);
}
private void jToggleButton7ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("8");
valueCheck("8",jToggleButton7);
evenOdd(jToggleButton7);
}
private void jToggleButton9ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("9");
valueCheck("9",jToggleButton9);
evenOdd(jToggleButton9);
}
private void jToggleButton12ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("+");
for(JToggleButton b: buttons)
b.setSelected(false);
if(values.contains("+"))
jToggleButton12.setSelected(true);
}
private void jToggleButton11ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("-");
for(JToggleButton b: buttons)
b.setSelected(false);
if(values.contains("-"))
jToggleButton11.setSelected(true);
}
private void jToggleButton10ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("*");
for(JToggleButton b: buttons)
b.setSelected(false);
if(values.contains("*"))
jToggleButton10.setSelected(true);
}
private void jToggleButton13ActionPerformed(java.awt.event.ActionEvent evt) {
processValue("/");
for(JToggleButton b: buttons)
b.setSelected(false);
if(values.contains("/"))
jToggleButton13.setSelected(true);
}
private void jToggleButton14ActionPerformed(java.awt.event.ActionEvent evt) {
long total=-1;
int firstNumber=-1;
int secondNumber=-1;
String process=null;
for (String secilenler : values) {
if(secilenler.equals("+"))
process="+";
else if(secilenler.equals("-"))
process="-";
else if(secilenler.equals("*"))
process="*";
else if(secilenler.equals("/"))
process="/";
else
{
if(firstNumber==-1)
firstNumber= Integer.parseInt(secilenler);
else
secondNumber= Integer.parseInt(secilenler);
}
}
if(process.equals("+"))
total=firstNumber+secondNumber;
else if(process.equals("-"))
total=firstNumber-secondNumber;
else if(process.equals("*"))
total=firstNumber*secondNumber;
else
total=firstNumber/secondNumber;
jTextField1.setText(""+total);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new CalculatorView_1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField jTextField1;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JToggleButton jToggleButton10;
private javax.swing.JToggleButton jToggleButton11;
private javax.swing.JToggleButton jToggleButton12;
private javax.swing.JToggleButton jToggleButton13;
private javax.swing.JToggleButton jToggleButton14;
private javax.swing.JToggleButton jToggleButton2;
private javax.swing.JToggleButton jToggleButton3;
private javax.swing.JToggleButton jToggleButton4;
private javax.swing.JToggleButton jToggleButton5;
private javax.swing.JToggleButton jToggleButton6;
private javax.swing.JToggleButton jToggleButton7;
private javax.swing.JToggleButton jToggleButton8;
private javax.swing.JToggleButton jToggleButton9;
// End of variables declaration
private List<String> values = new ArrayList<String>();
private List<String> evenNumbers = new ArrayList<String>();
{
evenNumbers.add("2");
evenNumbers.add("4");
evenNumbers.add("6");
evenNumbers.add("8");
}
private List<String> oddNumbers = new ArrayList<String>();
{
oddNumbers.add("1");
oddNumbers.add("3");
oddNumbers.add("5");
oddNumbers.add("7");
oddNumbers.add("9");
}
public void processValue(String strValue)
{
if(values.contains(strValue))
values.remove(strValue);
else
values.add(strValue);
}
public void valueCheck(String value,JToggleButton button) {
if(values.size()>2)
{
processValue(value);
button.setSelected(false);
JOptionPane.showMessageDialog(this, "You cant click 3 buttons at the same time..");
}
}
public boolean evenOdd(JToggleButton buton)
{
if(values.size()==2)
{
System.out.println((String)values.get(0));
System.out.println((String)values.get(1));
String number1 = new String(values.get(0));
String number2 = new String(values.get(1));
if(evenNumbers.contains(number1))
{
if(evenNumbers.contains(number2))
{
processValue(number1);
processValue(number2);
}
else if(oddNumbers.contains(number2))
{
buton.setSelected(false);
JOptionPane.showMessageDialog(this, "You cant click an even and an odd number at the same time..");
}
}
else if(oddNumbers.contains(number1))
{
if(oddNumbers.contains(number2))
{
processValue(number1);
processValue(number2);
}
else if(evenNumbers.contains(number2))
{
buton.setSelected(false);
JOptionPane.showMessageDialog(this, "You cant click an even and an odd number at the same time..");
}
}
}
return false;
}
}
Your problem is not related to multithreading. Multithreading involves multiple threads, thus the word itself. In your situation, what you want to do can be achieved with simple if-else statement and proper return value from the involved methods.
I see that your method evenOdd() already returns boolean. You can take advantage from that. After displaying your error message in evenOdd(), make it to return false. Then, when the toggle button is pressed, test if evenOdd() returns true then call valueCheck(), else, if it returns false (error message was displayed), do not call it.
if(evenOdd(jToggleButton1))
valueCheck("1", jToggleButton1);
Also, your current method names are confusing. Try playing with the way you name your methods. Methods should be named in such way that when you see it, you already know what it does.

How to wire one pane to another

How do I wire output to paneWithList?
PaneWithList has a listener on its JList so that the selected row is output to the console. How can I direct that output to the JTextPane on output?
Could PaneWithList fire an event which Main picks up? Would PropertyChangeSupport suffice?
Main.java:
package dur.bounceme.net;
import javax.swing.JTabbedPane;
public class Main {
private static JTabbedPane tabs;
private static PaneWithList paneWithList;
private static PaneWithTable paneWithTable;
private static Output output;
public static void main(String[] args) {
tabs = new javax.swing.JTabbedPane();
paneWithList = new PaneWithList();
paneWithTable = new PaneWithTable();
tabs.addTab("list", paneWithList);
tabs.addTab("table", paneWithTable);
tabs.addTab("output", output);
}
}
Here's an example using the observer pattern, also seen here, here and here. Note that it would also be possible to listen to the combo's model.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
/**
* #see http://en.wikipedia.org/wiki/Observer_pattern
* #see https://stackoverflow.com/a/10523401/230513
*/
public class PropertyChangeDemo {
public PropertyChangeDemo() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new ObserverPanel());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PropertyChangeDemo example = new PropertyChangeDemo();
}
});
}
}
class ObserverPanel extends JPanel {
private JLabel title = new JLabel("Value received: ");
private JLabel label = new JLabel("null", JLabel.CENTER);
public ObserverPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObserverPanel"));
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(title);
panel.add(label);
this.add(panel);
ObservedPanel observed = new ObservedPanel();
observed.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(ObservedPanel.PHYSICIST)) {
String value = e.getNewValue().toString();
label.setText(value);
}
}
});
this.add(observed);
}
}
class ObservedPanel extends JPanel {
public static final String PHYSICIST = "Physicist";
private static final String[] items = new String[]{
"Alpher", "Bethe", "Gamow", "Dirac", "Einstein"
};
private JComboBox combo = new JComboBox(items);
private String oldValue;
public ObservedPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObservedPanel"));
combo.addActionListener(new ComboBoxListener());
this.add(combo);
}
private class ComboBoxListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
String newValue = (String) combo.getSelectedItem();
firePropertyChange(PHYSICIST, oldValue, newValue);
oldValue = newValue;
}
}
}
I'd be use JMenu with JMenuItems with contents layed by using CardLayout rather than very complicated JTabbedPane(s)
For my own reference, and for anyone using the Netbeans GUI builder, this works so far as it goes:
The PanelWithList class:
package dur.bounceme.net;
public class PanelWithList extends javax.swing.JPanel {
public PanelWithList() {
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();
jList1 = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jList1KeyReleased(evt);
}
});
jScrollPane1.setViewportView(jList1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(167, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2)
.addComponent(jScrollPane1))
.addContainerGap(166, Short.MAX_VALUE))
);
}// </editor-fold>
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
row();
}
private void jList1KeyReleased(java.awt.event.KeyEvent evt) {
row();
}
// Variables declaration - do not modify
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
private void row() {
Object o = jList1.getSelectedValue();
String s = (String)o;
jTextArea1.setText(s);
this.firePropertyChange("list", -1, 1);
}
}
and Frame.java as a driver:
package dur.bounceme.net;
public class Frame extends javax.swing.JFrame {
public Frame() {
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() {
jTabbedPane1 = new javax.swing.JTabbedPane();
panelWithList1 = new dur.bounceme.net.PanelWithList();
panelWithTable1 = new dur.bounceme.net.PanelWithTable();
newJPanel1 = new dur.bounceme.net.PanelWithCombo();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panelWithList1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
panelWithList1PropertyChange(evt);
}
});
jTabbedPane1.addTab("tab1", panelWithList1);
jTabbedPane1.addTab("tab2", panelWithTable1);
jTabbedPane1.addTab("tab3", newJPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 937, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 555, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void panelWithList1PropertyChange(java.beans.PropertyChangeEvent evt) {
System.out.println("panelWithList1PropertyChange ");
}
/**
* #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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTabbedPane jTabbedPane1;
private dur.bounceme.net.PanelWithCombo newJPanel1;
private dur.bounceme.net.PanelWithList panelWithList1;
private dur.bounceme.net.PanelWithTable panelWithTable1;
// End of variables declaration
}
The key being that panelWithList1PropertyChange is the listener on 'panelWithList' itself.
Because PanelWithList.firePropertyChange("list", -1, 1); cannot send Object nor String that I see, I'm not exactly sure how to get the value selected all the way from the JList up to the JFrame.
Hmm, well the API says yes it can send Objects. Have to check that out.
I think it's necessary to get some info about the model which the JList is using up to the JFrame. However, doesn't that break MVC? Or maybe that's the wrong approach.

Categories