This question already has answers here:
error: incompatible types: unexpected return value Char compare to String
(3 answers)
Void methods cannot return a value
(10 answers)
Closed 3 years ago.
I am trying to convert a clock in and clock out program given by my lecturer at my universtiy to OOP. This is the original source code.
package gui;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JAVASwingForm {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JAVASwingForm window = new JAVASwingForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JAVASwingForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 730, 489);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(228, 28, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblName = new JLabel("Clock In");
lblName.setBounds(65, 31, 100, 14);
frame.getContentPane().add(lblName);
JLabel lblPhone = new JLabel("Clock Out");
lblPhone.setBounds(65, 68, 100, 14);
frame.getContentPane().add(lblPhone);
textField_1 = new JTextField();
textField_1.setBounds(228, 65, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnSubmit = new JButton("Calculate");
btnSubmit.setBounds(65, 200, 89, 23);
frame.getContentPane().add(btnSubmit);
JLabel timeResult = new JLabel("Time Difference will show here");
timeResult.setBounds(65, 115, 200, 14);
frame.getContentPane().add(timeResult);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (textField.getText().isEmpty() || textField_1.getText().isEmpty())
JOptionPane.showMessageDialog(null, "Data Missing");
else {
//Nicholas - implementation and customization starts from here
String time1 = textField.getText();
String time2 = textField_1.getText();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(time1);
date2 = format.parse(time2);
} catch (ParseException e) {
// TODO Auto-generated catch block
timeResult.setText(e.toString());
}
// Nicholas - Substraction from here in miliseconds
long diff = date2.getTime() - date1.getTime();
// Nicholas - convert milisecond to hours and minutes
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
timeResult.setText(diffHours + " hours, and " + diffMinutes + " Minutes");
}
}
});
}
}
And this is my conversion so far.
package gui.form;
public class Backend implements Clock {
public double timelength;
private double TimeIn , TimeOut;
private double calcTime;
public double timelength(){
return calcTime;
}
public Backend(){
}
public double calcTime(){
return( TimeIn - TimeOut);
}
public double getTimelength() {
return timelength;
}
public void setTimelength(double timelength) {
this.timelength = timelength;
}
public double getTimeIn() {
return TimeIn;
}
public void setTimeIn(double TimeIn) {
this.TimeIn = TimeIn;
}
public double getTimeOut() {
return TimeOut;
}
public void setTimeOut(double TimeOut) {
this.TimeOut = TimeOut;
}
#Override
public double setTime() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public double calcTime(double timelength) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
package gui.form;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Form {
private double timelength;
private double TimeIn , TimeOut;
/**
* Creates new form Form
*/
public Form() {
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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
TItxt = new javax.swing.JTextField();
TOtxt = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
LTimetxt = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Time In");
jLabel2.setText("Time Out");
TItxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
TItxtActionPerformed(evt);
}
});
jButton1.setText("Enter");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("Length of Time");
LTimetxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LTimetxtActionPerformed(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()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(29, 29, 29))
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addComponent(jLabel3))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(TOtxt, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
.addComponent(TItxt)
.addComponent(LTimetxt))
.addContainerGap(166, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(TItxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(TOtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(LTimetxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 109, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(21, 21, 21))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
{
TItxt.getText();
TOtxt.getText();
}
return LTimetxt.setText();
// TODO add your handling code here:
}
private void TItxtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void LTimetxtActionPerformed(java.awt.event.ActionEvent 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(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Form.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 Form().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField LTimetxt;
private javax.swing.JTextField TItxt;
private javax.swing.JTextField TOtxt;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration
public double getTimelength() {
return (TimeIn - TimeOut);
}
public void setTimelength(double timelength) {
this.timelength = (TimeIn - TimeOut);
}
public double getTimeIn() {
return TimeIn;
}
public void setTimeIn(double TimeIn) {
this.TItxt = TItxt;
}
public double getTimeOut() {
return TimeOut;
}
public void setTimeOut(double TimeOut) {
this.TOtxt = TOtxt;
}
public JTextField getTItxt() {
return TItxt;
}
public void setTItxt(JTextField TItxt) {
this.TItxt = TItxt;
}
public JTextField getTOtxt() {
return TOtxt;
}
public void setTOtxt(JTextField TOtxt) {
this.TOtxt = TOtxt;
}
public JButton getjButton1() {
return jButton1;
}
public void setjButton1(JButton jButton1) {
this.jButton1 = jButton1;
}
public JLabel getjLabel1() {
return jLabel1;
}
public void setjLabel1(JLabel jLabel1) {
this.jLabel1 = jLabel1;
}
public JLabel getjLabel2() {
return jLabel2;
}
public void setjLabel2(JLabel jLabel2) {
this.jLabel2 = jLabel2;
}
public JTextField getLTimetxt() {
return LTimetxt;
}
public int setLTimetxt(JTextField LTimetxt) {
this.LTimetxt = LTimetxt;
return (int) (TimeIn - TimeOut);
}
private void setVisible(boolean b) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
package gui.form;
public interface Clock {// template of the class
public double setTime(); //method to be implemented at the sub class
public double calcTime(double timelength); //method to be implemented at the sub class
}
package gui.form;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JAVASwingForm {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
Backend backend = new Backend();
Form form = new Form();
}
}
I have set up 2 classes, a main class and a interface, however, I cant seem to get it to work and always seem to hit an error. enter image description here
Your Problem as seen in your Image is that you return a value in a void method.
Related
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 am a newbie in Java, I need changing the background Color of a progress bar, but really I don't know how to do this
I have a progress bar called "barrita"
I am using Linux Ubuntu and Java 8 and I am using the palette of Swing
package loginprogressbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
*
* #author fernando
*/
public class Inicio extends javax.swing.JFrame {
private Timer tiempo;
int contador;
public static final int TWO_SECOND = 2;
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
contador += 1;
barrita.setValue(contador);
if (contador == 100) {
tiempo.stop();
esconder();
Menu1 m1 = new Menu1();
m1.setVisible(true);
m1.setLocationRelativeTo(null);
}
}
}
public void esconder() {
this.setVisible(false);
}
public void activar() {
tiempo.start();
}
public Inicio() {
initComponents();
setLocationRelativeTo(null);
barrita.setVisible(false);
}
public void inicionSesion() {
String usuario = panel2.getText();
String password = (String.valueOf(txtPassword.getText()));
if (usuario.equals("fernando") && password.compareTo("12345") == 0) {
barrita.setVisible(true);
contador = -1;
barrita.setValue(0);
barrita.setStringPainted(true);
tiempo = new Timer(TWO_SECOND, new TimerListener());
activar();
} else {
JOptionPane.showMessageDialog(null, "Error al ingresar usuario o contraseƱa incorrecta");
panel2.setText("");
txtPassword.setText("");
panel2.requestFocus();
}
}
/**
* 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() {
panel1 = new javax.swing.JPanel();
panel2 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtPassword = new javax.swing.JPasswordField();
btnEntrar = new javax.swing.JButton();
barrita = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
panel1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
panel1KeyPressed(evt);
}
});
panel2.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
panel2KeyPressed(evt);
}
});
jLabel1.setText("Nombre");
jLabel2.setText("ContraseƱa");
txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtPasswordKeyPressed(evt);
}
});
btnEntrar.setText("Ingresar");
btnEntrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEntrarActionPerformed(evt);
}
});
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnEntrar)
.addGap(83, 83, 83))
.addGroup(panel1Layout.createSequentialGroup()
.addGap(58, 58, 58)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(barrita, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(panel1Layout.createSequentialGroup()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPassword)
.addComponent(panel2, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
.addGap(113, 113, 113))))
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(panel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(21, 21, 21)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addComponent(barrita, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnEntrar)
.addContainerGap(93, Short.MAX_VALUE))
);
getContentPane().add(panel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
pack();
}// </editor-fold>
private void panel1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
inicionSesion();
}
}
private void btnEntrarActionPerformed(java.awt.event.ActionEvent evt) {
inicionSesion(); // TODO add your handling code here:
}
private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
btnEntrar.requestFocus();
}
}
private void panel2KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
txtPassword.requestFocus();
}
}
/**
* #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(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Inicio.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 Inicio().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JProgressBar barrita;
private javax.swing.JButton btnEntrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel panel1;
private javax.swing.JTextField panel2;
private javax.swing.JPasswordField txtPassword;
// End of variables declaration
}
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 have a program that creates a dynamic amount of jpanels and components based on selection at the start of the program that is user-defined. having said that each jpanel and component is created with a loop making them all the same, and they are then put into a list (the JPanel's are put into a list).
Having said that I have been able to get the jpanel out and then grab the componenets and display them using System.out. but they are in a component object. How can I get the values of the components? Or am I doing this wrong?
Basically I am trying to have the tabs/jpanels based on user-definition automatically generate, which works. Then the user fills out some information and hits "Generate" which is where I then need to iterate through the tabs/jpanels/componenents and put them into the correct object.
Below is a working example of my program in a simplified for, with less tyteps of tabs (I only let the AP tab be created) and less options for the object classes:
There are two object classes APObject is extending Generic Object. MVCE is the start of the main program where it asks you a few user-defined questions which generate the Tabs/Panels. It then goes from InfoGathering.java to DataGathering where it creates the tabs and panels. The GenerateActionPerformed(ActionEvent evt) method is where I am trying to grab the information from the panel components and put them into the APObject or whichever object they need to go into.
MVCE:
public class MVCE extends javax.swing.JFrame {
int numGenerate[];
private javax.swing.JComboBox cb;
/**
* Creates new form MVCE
*/
public MVCE() {
this.numGenerate = new int[3];
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() {
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jLabel1.setText("How many switches?");
jLabel2.setText("APS");
jButton1.setText("Create Button");
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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jButton1))
.addContainerGap(264, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
jLabel1.getAccessibleContext().setAccessibleName("How many switches");
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.setVisible(false);
InfoGathering Info = new InfoGathering(numGenerate);
}
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
cb = (javax.swing.JComboBox)evt.getSource();
String APNumber = (String)cb.getSelectedItem();
//System.out.println(APNumber + "AP Number");
numGenerate[1] = Integer.valueOf(APNumber);
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
cb = (javax.swing.JComboBox)evt.getSource();
String APNumber = (String)cb.getSelectedItem();
//System.out.println(APNumber + "AP Number");
numGenerate[0] = Integer.valueOf(APNumber);
}
/**
* #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(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MVCE.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 MVCE().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration
}
INFOGATHERING:
public class InfoGathering {
//public int infoVariables[];
public InfoGathering(int[] infoVars) {
startInfo(infoVars);
}
private void startInfo(int[] infoVars) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DataGathering(infoVars).setVisible(true);
}
});
}
//End of clss below
}
DATAGATHERING:
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author kmalik
*/
public class DataGathering extends javax.swing.JFrame {
private int infoVariables[];
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel OuterPane;
//SwitchObject SWOb[] = new SwitchObject[30];
//APObject APOb[] = new APObject[30];
//ControllerObject CoOb[] = new ControllerObject[1];
//int devicesArrayCountSW = 0;
//int devicesArrayCountAP = 0;
//int devicesArrayCountCO = 0;
/**
* Creates new form DataGathering
* #param intVars
*/
public DataGathering(int[] intVars) {
infoVariables = Arrays.copyOf(intVars, intVars.length);
initComponents();
initDynamic();
}
/**
* 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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridLayout(1, 0));
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
private void initDynamic() {
OuterPane = new javax.swing.JPanel();
getContentPane().add(OuterPane);
OuterPane.add(jTabbedPane1);
JButton GenerateCode = new JButton("Generate Code");
OuterPane.setLayout(new BoxLayout(OuterPane, BoxLayout.Y_AXIS));
OuterPane.add(GenerateCode);
GenerateCode.addActionListener(new java.awt.event.ActionListener() {
private APObject Aobj;
private JPanel jobj;
private Component Components[];
private Component components;
public void actionPerformed(java.awt.event.ActionEvent evt) {
GenerateActionPerformed(evt);
}
private void GenerateActionPerformed(ActionEvent evt) {
//To change body of generated methods, choose Tools | Templates.
for(int i = 0; apList.size() > i; i++) {
//jobj = (JPanel) jList.get(i);
//System.out.println(jobj
Aobj = apList.get(i);
jobj = jList.get(i);
Components = jobj.getComponents();
System.out.println(Components + " Componenets of first panel");
for (int a=0; a < Components.length; a++) {
components = jobj.getComponent(a);
System.out.println(components);
if (Components[a] instanceof JComboBox) {
}
}
}
}
});
int SwitchCount = 1 , APCount = 1,CoCount = 1;
//String jp;
//need public# of switches, APs and controllers
for(int devicesCount =0;devicesCount < infoVariables.length;devicesCount++) {
if (devicesCount == 2 && infoVariables[devicesCount] == 1) {
createTab(CoCount, devicesCount);
}
for(int b=0; b < infoVariables[devicesCount]; b++) {
if (devicesCount == 0) {
//SWITCHES DYNAMICALLY CREATE
createTab(SwitchCount,devicesCount);
SwitchCount++;
} else if (devicesCount==1) {
//AP DYNAMICALLY CREATE
createTab(APCount,devicesCount);
APCount++;
} //end of full if loop
} //end of for loop
} // end of outer for loop
}
private javax.swing.JTabbedPane jTabbedPane1;
//ArrayList<SwitchObject> swList = new ArrayList<>();
ArrayList<APObject> apList = new ArrayList<>();
//ArrayList<ControllerObject> coList = new ArrayList<>();
ArrayList<JPanel> jList = new ArrayList<>();
private void createTab(int z,int y) {
if (y==0) {
//CREATE SWITCH TAB/PANEL
} else if (y==1) {
JPanel jp = new JPanel();
jTabbedPane1.addTab("AP_"+z,jp);
jp.setName("AP"+z);
APObject APOb = new APObject(jp.getName(), z);
apList.add(APOb);
jList.add(jp);
setLayout(new FlowLayout());
//Add Type of Device Checkbox
String[] apListName = {"APExample1","APExample2"};
JComboBox apListChkBox = new JComboBox(apListName);
jp.add(apListChkBox);
//Add NasID of Device with Label
JLabel apnasIDLabel = new JLabel("AP ID");
String apnasID;
JTextField apnasIDComboBox = new JTextField();
apnasIDComboBox.setColumns(9);
jp.add(apnasIDLabel);
jp.add(apnasIDComboBox);
//SNMP Location
JLabel apLocLabel = new JLabel("Location");
String apLoc;
JTextField apLocComboBox = new JTextField();
apLocComboBox.setColumns(9);
jp.add(apLocLabel);
jp.add(apLocComboBox);
jp.setBorder(BorderFactory.createLineBorder(Color.black));
this.pack();
} else if (y == 2) {
//CREATE CONTROLLER TAB/PANEL
}
}
}
APOBJECT:
public class APObject extends GenericObject {
private int channelScheme;
APObject(String x, int y) {
super(x,y);
}
//ip scheme box/subnet box get/set
//location get/set
//channel scheme get/set
private void setChannelScheme(int x) {
channelScheme = x;
}
private int getChannelScheme() {
return channelScheme;
}
}
GENERICOBJECT:
public class GenericObject {
private int telephone;
private String ipScheme;
private String Location;
public String DName;
public int getTelephone() {
return telephone;
}
protected void setTelephone(int x) {
telephone = x;
}
protected String getipScheme() {
return ipScheme;
}
protected void setipScheme(String x) {
ipScheme = x;
}
protected String getLocation() {
return Location;
}
protected void setLocation(String x) {
Location = x;
}
public GenericObject (String SName, int Tab) {
DName = SName;
int TabNum = Tab;
}
}
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.