Related
I am new in java and trying to create a dashboard where I have N number of sensors and now i wants to show values of Humidity and temperature of each sensor in a separate panels . So firstly i have created N number of panels containing a JSlider and JThermometer for Humidity and temperature each. Now in a loop it reads the lines of outputs from arduino and i am trying to provide that values to that thermometers and sliders .
But i am not able to differentiate that output for which panel it is goin to set . even when i tried to set values to them it is not working at all.
Kindly give any idea how can i implement.
Thank you for help.
Java version - 18.0.1.1
IDE - Apache netbeans 14
static JTextField txtTemp, txtMois;
static JLabel lblTemp, lblMois;
static JSlider slider1, slider2;
static JThermometer th1, th2 ;
static JPanel JP1, JP ;
public void interfaces(){
///Here number of panels is 2
if(count1 > 0){
for(int i = 0 ; i<=count1 ; i++){
JP1 = myPanel(i,0,0);
add(JP1);
}
}
setVisible(true);
setTitle("Temperature and Humidity");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(1200,800);
getContentPane().setBackground(Color.lightGray);
setMinimumSize(new Dimension(350,450));
setLayout(null);
SerialPort[] AvailablePorts = SerialPort.getCommPorts();
SerialPort currPort = AvailablePorts[0];
for (SerialPort S : AvailablePorts) {
System.out.println("\n " + S.toString());
currPort = S;
}
int BaudRate = 9600;
int DataBits = 8;
int StopBits = SerialPort.ONE_STOP_BIT;
int Parity = SerialPort.NO_PARITY;
System.out.println("\n " + currPort.getSystemPortName());
currPort.setComPortParameters(BaudRate,
DataBits,
StopBits,
Parity);
currPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,
1000,
0);
currPort.openPort();
if (currPort.isOpen())
{
System.out.println("is Open ");
} else {
System.out.println(" Port not open ");
}
try {
while (true) {
try{input = new BufferedReader(new InputStreamReader(currPort.getInputStream()));
String Line1 = input.readLine();
int count = 0;
String[] Data = Line1.split(" ");
for(int i = 0; i < Data.length; i++){
count +=1;
String[] Final_data = Data[i].split(",");
double temp, mois;
try{ temp = Double.parseDouble(Final_data[0]);
mois = Double.parseDouble(Final_data[1]);
System.out.println("Temparature : " + temp);
System.out.println("Humidity : " + mois);
th1.setValue(temp);
th2.setValue(mois);
slider1.setValue((int) temp);
slider2.setValue((int) mois);
txtTemp.setText(String.valueOf(temp));
txtMois.setText(String.valueOf(mois));
}
catch(NumberFormatException e){
System.out.println(e.toString());
}
}
}
catch(SerialPortTimeoutException ex){
System.out.println(ex);
}
}
} catch (Exception e) {
e.printStackTrace();
}
currPort.closePort();
}
//MyPannel funaction
public static JPanel myPanel(int count, double temp, double mois){
JP = new JPanel();
int width = (count-1)*420;
test = new JTextField(String.valueOf(count));
test.setBounds(0, 0, 200, 20);
JP.add(test);
th1 = new JThermometer();
th1.setBounds(10, 50, 150,300);
th1.setValue(0);
th1.setBackground(new Color(0,0,0,0));
th1.setForeground(Color.white);
String color = th1.getBackground().toString();
slider1 = new JSlider(JSlider.VERTICAL,0,100,0);
slider1.setBounds(110, 60, 50, 230);
slider1.setMinorTickSpacing(2);
slider1.setMajorTickSpacing(10);
slider1.setPaintTicks(true);
slider1.setPaintLabels(true);
slider1.setForeground(Color.white);
slider1.setBackground(new Color(0,0,0,0));
lblTemp = new JLabel("TEMPERATURE",SwingConstants.CENTER);
lblTemp.setBounds(15,30,140,30);
lblTemp.setForeground(Color.WHITE);
lblTemp.setFont(new Font("Arial", Font.BOLD, 20));
lblTemp.setBackground(Color.getColor(color));
txtTemp = new JTextField();
txtTemp.setFont(new Font("Arial", Font.BOLD, 16));
txtTemp.setBounds(115,300,50,30);
th2 = new JThermometer();
th2.setBounds(210, 50, 150, 300);
th2.setValue(0);
th2.setBackground(new Color(0,0,0,0));
th2.setForeground(Color.white);
slider2 = new JSlider(JSlider.VERTICAL,0,100,0);
slider2.setBounds(310, 60, 50, 230);
slider2.setMinorTickSpacing(2);
slider2.setMajorTickSpacing(10);
slider2.setPaintTicks(true);
slider2.setPaintLabels(true);
slider2.setBackground(new Color(0,0,0,0));
slider2.setForeground(Color.white);
lblMois = new JLabel("HUMIDITY",SwingConstants.CENTER);
lblMois.setBounds(215,30,140,30);
lblMois.setFont(new Font("Arial", Font.BOLD, 20));
lblMois.setForeground(Color.WHITE);
txtMois = new JTextField();
txtMois.setFont(new Font("Arial", Font.BOLD, 16));
txtMois.setBounds(315,300,50,30);
JP.add(lblTemp);
JP.add(txtTemp);
JP.add(lblMois);
JP.add(txtMois);
JP.add(th1,BorderLayout.CENTER);
JP.add(slider1);
JP.add(slider2);
JP.add(th2,BorderLayout.CENTER);
JP.setBounds(width, 20, 400, 400);
JP.setVisible(true);
JP.setLayout(new java.awt.BorderLayout());
JP.validate();
//JP.add(txt);
return JP;
}
//and arduino output will be like this..
29.5,56.9 25.5,40.3
29.5,54,8 25.5,40.0
so on...
I am working on an assignment for my Java class and I wrote a code that works similar to Microsoft word's word counter. Everything on my code works, the problem is when I run the program I need to click on the window in order for my output to appear or else nothing will show up. It acts as if it is hidden.
public static void main(String[] args) {
//JPanel contentPane = null;
//JTextField textField;
int length;
String msg;
Scanner scan = new Scanner (System.in);
System.out.println("Enter a sentence: ");
msg = scan.nextLine();
length = msg.length();
JFrame frame = new JFrame("Word Count");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(400, 300);
JLabel label1 = new JLabel("Statistics");
label1.setFont(new Font("Onyx", Font.BOLD, 12));
label1.setBounds(30, 10, 135, 15);
frame.add(label1);
JButton ex = new JButton("Close");
ex.setBounds(30, 200, 50, 50);
ex.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}});
frame.add(ex);
frame.setVisible(true);
JTextPane lbl = new JTextPane();
lbl.setBounds(30, 30, 310, 150);
lbl.setText(getStats(msg));
frame.getContentPane().add(lbl);
frame.setVisible(true);
}
public static String getStats(String msg){
int spcCount = 0;
int aCount = 0;
String tmpMsg = "";
for(int i = 0; i < msg.length(); i++){
if(msg.charAt(i) == ' '){
spcCount++;
}else if(msg.charAt(i) == 'a'){
aCount++;
}
}
tmpMsg += "Characters (with spaces)\t\t" + msg.length() + "\n";
tmpMsg += "Characters (without spaces)\t\t" + (msg.length()-spcCount) + "\n";
tmpMsg += "Spaces\t\t\t\t" + spcCount + "\n";
tmpMsg += "Words\t\t\t\t" + (spcCount+1) + "\n";
tmpMsg += "Vowels\t\t\t\t" + (msg.length() - msg.toLowerCase().replaceAll("a|e|i|o|u", "").length()) + "\n";
return tmpMsg;
}
}
This problem is obviously annoying and not efficient. So does the use of TextPane here cause this issue? Thank you in advance and don't hesitate to make edits if it helps with wording the question better.
Added few lines of code for setting it in front and deleted frame.setVisible(true); duplicate, main should look like this:
public static void main(String[] args) {
//JPanel contentPane = null;
//JTextField textField;
int length;
String msg;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence: ");
msg = scan.nextLine();
length = msg.length();
JFrame frame = new JFrame("Word Count");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(400, 300);
JLabel label1 = new JLabel("Statistics");
label1.setFont(new Font("Onyx", Font.BOLD, 12));
label1.setBounds(30, 10, 135, 15);
JButton ex = new JButton("Close");
ex.setBounds(30, 200, 50, 50);
ex.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.add(label1);
frame.add(ex);
JTextPane lbl = new JTextPane();
lbl.setBounds(30, 30, 310, 150);
lbl.setText(getStats(msg));
frame.getContentPane().add(lbl);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(false);
}
How to append a scroll pane for my window?
The program compiles properly, but the scroll pane for the window is not created. I really don't know why this is happening. I defined JScrollPane and even implemented it with scrollPane = new JScrollPane
Where is my mistake?
Below is my code:
import java.awt.*;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JScrollPane;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
public class RegForm extends JFrame implements ItemListener{
JLabel l0,li,l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13;
JButton b1,b2,b3,b4,b5;
JTextField t1,t2,t3,t4,t5,t6,t7,t8;
JTextArea a1,a2;
JComboBox<Integer> dd = new JComboBox<Integer>();
JComboBox<String> mm = new JComboBox<String>();
JComboBox<Integer> yyyy = new JComboBox<Integer>();
JComboBox<String> q = new JComboBox<String>();
JRadioButton rb1 = new JRadioButton( " Male ");
JRadioButton rb2 = new JRadioButton(" Female ");
JCheckBox cb1 = new JCheckBox (" C ");
JCheckBox cb2 = new JCheckBox (" C++ ");
JCheckBox cb3 = new JCheckBox (" Java ");
JCheckBox cb4 = new JCheckBox (" Oracle ");
JCheckBox cb5 = new JCheckBox (" Android ");
JCheckBox cb6 = new JCheckBox (" iOS ");
JCheckBox cb7 = new JCheckBox (" Web Designing ");
JCheckBox cb8 = new JCheckBox (" .Net ");
JCheckBox cb9 = new JCheckBox (" Same as Contact Address ");
JScrollPane scrollPane = new JScrollPane();
RegForm()
{
l0 = new JLabel("REGISTRATION FORM");
Font f0 = new Font("Algerian",Font.ITALIC,20);
l0.setFont(f0);
l0.setBounds(600,10,250,50);
scrollPane.add(l0);
li = new JLabel(" * Fields are mandatory");
Font fi = new Font("Arabic TypeSetting",Font.PLAIN,17);
li.setFont(fi);
li.setForeground(Color.RED);
li.setBounds(10,50,150,30);
scrollPane.add(li);
l1 = new JLabel(" * FirstName: ");
Font f1 = new Font("Bookman Old Style",Font.PLAIN,12);
l1.setFont(f1);
l1.setBounds(10,70,100,50);
scrollPane.add(l1);
t1 = new JTextField(20);
t1.setBounds(165,85,140,20);
scrollPane.add(t1);
l2 = new JLabel("* Confirm FirstName: ");
l2.setFont(f1);
l2.setBounds(10,100,150,50);
scrollPane.add(l2);
t2 = new JTextField(20);
t2.setBounds(165,115,140,20);
scrollPane.add(t2);
l3 = new JLabel(" Middle Name: ");
l3.setFont(f1);
l3.setBounds(15,130,120,50);
scrollPane.add(l3);
t3 = new JTextField(20);
t3.setBounds(165,145,140,20);
scrollPane.add(t3);
l4 = new JLabel(" Confirm Middle Name: ");
l4.setFont(f1);
l4.setBounds(15,160,150,50);
scrollPane.add(l4);
t4 = new JTextField(20);
t4.setBounds(165,175,140,20);
scrollPane.add(t4);
l5 = new JLabel(" * Sur Name: ");
l5.setFont(f1);
l5.setBounds(10,190,100,50);
scrollPane.add(l5);
t5 = new JTextField(20);
t5.setBounds(165,205,140,20);
scrollPane.add(t5);
l6 = new JLabel(" * Confirm Sur Name: ");
l6.setFont(f1);
l6.setBounds(10,220,150,50);
scrollPane.add(l6);
t6 = new JTextField(20);
t6.setBounds(165,235,140,20);
scrollPane.add(t6);
l7 = new JLabel(" * DD / MM / YYYY" );
Font f2 = new Font(" Comic Sans MS ",Font.ITALIC,12);
l7.setFont(f2);
l7.setBounds(10,260,150,50);
scrollPane.add(l7);
for(int j=1;j<=31;j++)
dd.addItem(new Integer(j));
dd.setBounds(165,275,47,20);
scrollPane.add(dd);
dd.addItemListener(this);
mm.addItem("January");
mm.addItem("February");
mm.addItem("March");
mm.addItem("April");
mm.addItem("May");
mm.addItem("June");
mm.addItem("July");
mm.addItem("August");
mm.addItem("September");
mm.addItem("October");
mm.addItem("November");
mm.addItem("December");
mm.setBounds(212,275,90,20);
scrollPane.add(mm);
mm.addItemListener(this);
for(int i=1990;i<=2016;i++)
yyyy.addItem(new Integer(i));
yyyy.setBounds(302,275,70,20);
scrollPane.add(yyyy);
yyyy.addItemListener(this);
l8 = new JLabel(" Age: ");
l8.setFont(f1);
l8.setBounds(15,290,50,50);
scrollPane.add(l8);
t8 = new JTextField(10);
t8.setBounds(165,305,50,20);
scrollPane.add(t8);
l9 = new JLabel(" Qualification ");
l9.setFont(f1);
l9.setBounds(15,320,120,50);
scrollPane.add(l9);
q.addItem(" B.Tech ");
q.addItem(" M.Tech ");
q.addItem(" MBA ");
q.addItem(" MCA ");
q.addItem(" Intermediate ");
q.addItem(" SSC ");
q.addItem(" Others ");
q.setBounds(165,335,100,20);
scrollPane.add(q);
q.addItemListener(this);
l10 = new JLabel(" Gender ");
l10.setFont(f1);
l10.setBounds(15,360,80,50);
scrollPane.add(l10);
rb1.setBounds(165,365,80,39);
rb2.setBounds(250,365,80,39);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
scrollPane.add(rb1);
scrollPane.add(rb2);
l11 = new JLabel(" Courses Intrested: ");
l11.setFont(f1);
l11.setBounds(15,450,150,50);
scrollPane.add(l11);
cb1.setBounds(165,390,100,50);
scrollPane.add(cb1);
cb2.setBounds(285,390,100,50);
scrollPane.add(cb2);
cb3.setBounds(165,425,100,50);
scrollPane.add(cb3);
cb4.setBounds(285,425,100,50);
scrollPane.add(cb4);
cb5.setBounds(165,460,100,50);
scrollPane.add(cb5);
cb6.setBounds(285,460,100,50);
scrollPane.add(cb6);
cb7.setBounds(165,495,100,50);
scrollPane.add(cb7);
cb8.setBounds(285,495,100,50);
scrollPane.add(cb8);
cb9.setBounds(15,630,200,50);
scrollPane.add(cb9);
l12 = new JLabel(" Contact Address: ");
l12.setFont(f1);
l12.setBounds(15,550,150,50);
scrollPane.add(l12);
a1 = new JTextArea (5,20);
a1.setBounds(165,545,250,80);
scrollPane.add(a1);
l13 = new JLabel(" Permenant Address: ");
l13.setFont(f1);
l13.setBounds(15,675,150,50);
scrollPane.add(l13);
a2 = new JTextArea (5,20);
a2.setBounds(165,680,250,80);
scrollPane.add(a2);
cb9.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource() == yyyy){
int y = (Integer) ie.getItem();
t8.setText(Integer.toString(2016-y));
t8.setEditable(false);
}
if(cb9.isSelected()){
a2.setText(a1.getText());
a2.setEditable(false);
}
}
public void actionPerformed(ActionEvent ae)
{
}
public static void main(String[] args)
{
RegForm rf = new RegForm();
rf.setTitle("Hai Hello");
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(10,10,100,100);
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(1500, 800));
contentPane.add(scrollPane);
rf.setContentPane(contentPane);
rf.pack();
rf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
rf.setVisible(true);
}
}
scrollPane.add(l11);
Never add components directly to a scroll pane.
l1.setBounds(10,70,100,50);
Don't use setBounds(...). It is the job of the layout manager to set the size/location of the component.
The basic logic would be:
JPanel panel = new JPanel(); // set your layout manager for the panel.
panel.add( someComponent );
panel.add( anotherComponent );
JScrollPane scrollPane = new JScrollPane( panel );
frame.add( scrollPane );
Read the Swing Tutorial for Swing basics. Every section in the tutorial has working examples. Maybe start with the section on How to Use Scroll Panes.
This works, but you'll need to layout the components better..
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RegForm extends JFrame implements ItemListener {
JLabel l0, li, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13;
JButton b1, b2, b3, b4, b5;
JTextField t1, t2, t3, t4, t5, t6, t7, t8;
JTextArea a1, a2;
JComboBox<Integer> dd = new JComboBox<Integer>();
JComboBox<String> mm = new JComboBox<String>();
JComboBox<Integer> yyyy = new JComboBox<Integer>();
JComboBox<String> q = new JComboBox<String>();
JRadioButton rb1 = new JRadioButton(" Male ");
JRadioButton rb2 = new JRadioButton(" Female ");
JCheckBox cb1 = new JCheckBox(" C ");
JCheckBox cb2 = new JCheckBox(" C++ ");
JCheckBox cb3 = new JCheckBox(" Java ");
JCheckBox cb4 = new JCheckBox(" Oracle ");
JCheckBox cb5 = new JCheckBox(" Android ");
JCheckBox cb6 = new JCheckBox(" iOS ");
JCheckBox cb7 = new JCheckBox(" Web Designing ");
JCheckBox cb8 = new JCheckBox(" .Net ");
JCheckBox cb9 = new JCheckBox(" Same as Contact Address ");
JScrollPane scrollPane;
JPanel panel = new JPanel(new GridLayout(0,1));
RegForm() {
l0 = new JLabel("REGISTRATION FORM");
Font f0 = new Font("Algerian", Font.ITALIC, 20);
l0.setFont(f0);
l0.setBounds(600, 10, 250, 50);
panel.add(l0);
li = new JLabel(" * Fields are mandatory");
Font fi = new Font("Arabic TypeSetting", Font.PLAIN, 17);
li.setFont(fi);
li.setForeground(Color.RED);
li.setBounds(10, 50, 150, 30);
panel.add(li);
l1 = new JLabel(" * FirstName: ");
Font f1 = new Font("Bookman Old Style", Font.PLAIN, 12);
l1.setFont(f1);
l1.setBounds(10, 70, 100, 50);
panel.add(l1);
t1 = new JTextField(20);
t1.setBounds(165, 85, 140, 20);
panel.add(t1);
l2 = new JLabel("* Confirm FirstName: ");
l2.setFont(f1);
l2.setBounds(10, 100, 150, 50);
panel.add(l2);
t2 = new JTextField(20);
t2.setBounds(165, 115, 140, 20);
panel.add(t2);
l3 = new JLabel(" Middle Name: ");
l3.setFont(f1);
l3.setBounds(15, 130, 120, 50);
panel.add(l3);
t3 = new JTextField(20);
t3.setBounds(165, 145, 140, 20);
panel.add(t3);
l4 = new JLabel(" Confirm Middle Name: ");
l4.setFont(f1);
l4.setBounds(15, 160, 150, 50);
panel.add(l4);
t4 = new JTextField(20);
t4.setBounds(165, 175, 140, 20);
panel.add(t4);
l5 = new JLabel(" * Sur Name: ");
l5.setFont(f1);
l5.setBounds(10, 190, 100, 50);
panel.add(l5);
t5 = new JTextField(20);
t5.setBounds(165, 205, 140, 20);
panel.add(t5);
l6 = new JLabel(" * Confirm Sur Name: ");
l6.setFont(f1);
l6.setBounds(10, 220, 150, 50);
panel.add(l6);
t6 = new JTextField(20);
t6.setBounds(165, 235, 140, 20);
panel.add(t6);
l7 = new JLabel(" * DD / MM / YYYY");
Font f2 = new Font(" Comic Sans MS ", Font.ITALIC, 12);
l7.setFont(f2);
l7.setBounds(10, 260, 150, 50);
panel.add(l7);
for (int j = 1; j <= 31; j++) {
dd.addItem(new Integer(j));
}
dd.setBounds(165, 275, 47, 20);
panel.add(dd);
dd.addItemListener(this);
mm.addItem("January");
mm.addItem("February");
mm.addItem("March");
mm.addItem("April");
mm.addItem("May");
mm.addItem("June");
mm.addItem("July");
mm.addItem("August");
mm.addItem("September");
mm.addItem("October");
mm.addItem("November");
mm.addItem("December");
mm.setBounds(212, 275, 90, 20);
panel.add(mm);
mm.addItemListener(this);
for (int i = 1990; i <= 2016; i++) {
yyyy.addItem(new Integer(i));
}
yyyy.setBounds(302, 275, 70, 20);
panel.add(yyyy);
yyyy.addItemListener(this);
l8 = new JLabel(" Age: ");
l8.setFont(f1);
l8.setBounds(15, 290, 50, 50);
panel.add(l8);
t8 = new JTextField(10);
t8.setBounds(165, 305, 50, 20);
panel.add(t8);
l9 = new JLabel(" Qualification ");
l9.setFont(f1);
l9.setBounds(15, 320, 120, 50);
panel.add(l9);
q.addItem(" B.Tech ");
q.addItem(" M.Tech ");
q.addItem(" MBA ");
q.addItem(" MCA ");
q.addItem(" Intermediate ");
q.addItem(" SSC ");
q.addItem(" Others ");
q.setBounds(165, 335, 100, 20);
panel.add(q);
q.addItemListener(this);
l10 = new JLabel(" Gender ");
l10.setFont(f1);
l10.setBounds(15, 360, 80, 50);
panel.add(l10);
rb1.setBounds(165, 365, 80, 39);
rb2.setBounds(250, 365, 80, 39);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
panel.add(rb1);
panel.add(rb2);
l11 = new JLabel(" Courses Intrested: ");
l11.setFont(f1);
l11.setBounds(15, 450, 150, 50);
panel.add(l11);
cb1.setBounds(165, 390, 100, 50);
panel.add(cb1);
cb2.setBounds(285, 390, 100, 50);
panel.add(cb2);
cb3.setBounds(165, 425, 100, 50);
panel.add(cb3);
cb4.setBounds(285, 425, 100, 50);
panel.add(cb4);
cb5.setBounds(165, 460, 100, 50);
panel.add(cb5);
cb6.setBounds(285, 460, 100, 50);
panel.add(cb6);
cb7.setBounds(165, 495, 100, 50);
panel.add(cb7);
cb8.setBounds(285, 495, 100, 50);
panel.add(cb8);
cb9.setBounds(15, 630, 200, 50);
panel.add(cb9);
l12 = new JLabel(" Contact Address: ");
l12.setFont(f1);
l12.setBounds(15, 550, 150, 50);
panel.add(l12);
a1 = new JTextArea(5, 20);
a1.setBounds(165, 545, 250, 80);
panel.add(a1);
l13 = new JLabel(" Permenant Address: ");
l13.setFont(f1);
l13.setBounds(15, 675, 150, 50);
panel.add(l13);
a2 = new JTextArea(5, 20);
a2.setBounds(165, 680, 250, 80);
panel.add(a2);
cb9.addItemListener(this);
scrollPane = new JScrollPane(panel);
add(scrollPane);
//add(panel);
}
public void itemStateChanged(ItemEvent ie) {
if (ie.getSource() == yyyy) {
int y = (Integer) ie.getItem();
t8.setText(Integer.toString(2016 - y));
t8.setEditable(false);
}
if (cb9.isSelected()) {
a2.setText(a1.getText());
a2.setEditable(false);
}
}
public void actionPerformed(ActionEvent ae) {
}
public static void main(String[] args) {
RegForm rf = new RegForm();
rf.setTitle("Hai Hello");
/*JScrollPane panel = new JScrollPane();
panel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setBounds(10, 10, 100, 100);
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(1500, 800));
contentPane.add(panel);
rf.setContentPane(contentPane);*/
rf.pack();
rf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
rf.setVisible(true);
}
}
Notes:
As mentioned by #camickr, setting the bounds of the components won't work reliably. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Please try to solve programming errors before you've got to dozens of components! For simple testing of layouts with many components, just add dummy components in a loop. To put that another way: For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
Safer to use logical font names that specific one, e.g. Algerian will only work on systems with that font installed!
Ok, so I recently asked about how to get access to individual columns of an array in java, and I got an answer that worked perfectly. I then however intended to calculate things such as the maximum value in this column, and the average. However, I came across an issue. In order to access each value, I assume this column needs to be treated as an array also. However, the way I got access to each column was by storing it into a double. Therefore, I have no idea how to take each column and calculate things. Can anyone help me please? I'm sorry for posting so much that probably seems like nothing here, but we had no teacher for 12 weeks and are expected to turn in this work by just teaching ourselves, and I'm just really stuck.
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame.
private JPanel contentPane; //Create a container for the GUI.
//Create other components used in the GUI
private JTextField maxTxtVCC;
private JTextField maxTxtTemp;
private JTextField maxTxtLight;
private JTextField minTxtLight;
private JTextField avTxtLight;
private JTextField minTxtTemp;
private JTextField avTxtTemp;
private JTextField minTxtVCC;
private JTextField avTxtVCC;
private JButton btnMax;
private JButton btnMin;
private JButton btnAv;
private JTextField opnTxt;
private JButton btnOpn;
private TextArea textArea;
private JFileChooser fc;
private String content = "";
String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
int totalValues; //Used to hold the amount of values in the array (52790 ish)
Double[][] values;
double c4, c5, c6;
/**
* Launch the application.
*/
public static void main(String[] args) { //Main method
EventQueue.invokeLater(new Runnable() {
public void run() { //Create a runnable method
try {
CSVFiles frame = new CSVFiles(); //Launch the GUI
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace(); //Print errors
}
}
});
}
/**
* Create the frame.
*/
public CSVFiles() { //Open constructor
super ("CSV Files"); //Create a title for the GUI
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
setBounds(100, 100, 800, 600); //Set size and location
contentPane = new JPanel(); //Declare the JPanel
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
setContentPane(contentPane); //Add the JPanel
contentPane.setLayout(null); //Set the layout
maxTxtVCC = new JTextField(); //Declare this text field
maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
maxTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtVCC); //Add to the content pane
maxTxtTemp = new JTextField(); //Declare this text field
maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
maxTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtTemp); //Add to the content pane
maxTxtLight = new JTextField(); //Declare this text field
maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
maxTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtLight); //Add to the content pane
JLabel lblLight = new JLabel("Light"); //Declare this label
lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblLight.setBounds(22, 469, 46, 17); //Set size and location
contentPane.add(lblLight); //Add to the content pane
JLabel lblTemp = new JLabel("Temperature"); //Declare this label
lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblTemp.setBounds(10, 503, 109, 17); //Set size and location
contentPane.add(lblTemp);
JLabel lblVCC = new JLabel("VCC"); //Declare this label
lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblVCC.setBounds(22, 534, 46, 17); //Set size and location
contentPane.add(lblVCC); //Add to the content pane
minTxtLight = new JTextField(); //Declare this text field
minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
minTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtLight); //Add to the content pane
avTxtLight = new JTextField(); //Declare this text field
avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
avTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtLight); //Add to the content pane
minTxtTemp = new JTextField(); //Declare this text field
minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
minTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtTemp); //Add to the content pane
avTxtTemp = new JTextField(); //Declare this text field
avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
avTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtTemp); //Add to the content pane
minTxtVCC = new JTextField(); //Declare this text field
minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
minTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtVCC); //Add to the content pane
avTxtVCC = new JTextField(); //Declare this text field
avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
avTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtVCC); //Add to the content pane
btnMax = new JButton("Maximum"); //Declare this button
btnMax.setBounds(110, 438, 89, 23); //Set size and location
contentPane.add(btnMax); //Add to the content pane
btnMin = new JButton("Minimum"); //Declare this button
btnMin.setBounds(221, 438, 89, 23); //Set size and location
contentPane.add(btnMin); //Add to the content pane
btnAv = new JButton("Average"); //Declare this button
btnAv.setBounds(328, 438, 89, 23); //Set size and location
contentPane.add(btnAv); //Add to the content pane
textArea = new TextArea(); //Declare this text area
textArea.setBounds(22, 55, 551, 367); //Set size and location
textArea.setEditable(false); //Set it so it cannot be edited
contentPane.add(textArea); //Add to the content pane
btnOpn = new JButton("Open File"); //Declare this button
btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
public void actionPerformed(ActionEvent arg0) { //Method for action performed
try{
fc = new JFileChooser(); //Declare the file chooser
fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type
int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
File f; //Create a file to hold the data
//If the selected file is approved by the file chooser...
if(returnVal == JFileChooser.APPROVE_OPTION){
f = fc.getSelectedFile(); //Stored selected file into file variable
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
textArea.append("\nLoading file...\n\n"); //Print out loading message and some new lines
in.readLine(); //Skip the first line as it's just headers
int index = 0; //Integer used to label the indexes of the array
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
c4 = Double.parseDouble(temp[3]);
c5 = Double.parseDouble(temp[4]);
c6 = Double.parseDouble(temp[5]);
}
totalValues = index; //Set a value to the total values
textArea.append(builder.toString()); //Using the string builder to compile the text
textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
in.close(); //Close the reader.
values = new Double [index][3];
}
else{
f = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
btnOpn.setBounds(484, 26, 89, 23); //Set size and location
contentPane.add(btnOpn); //Add to the content pane
opnTxt = new JTextField(); //Declare this text field
opnTxt.setBounds(22, 27, 452, 20); //Set size and location
opnTxt.setEditable(false); //Set it so it cannot be edited
contentPane.add(opnTxt); //Add to the content pane
}
//Methods for Calculations
public static double findMax(double[] array){
double max;
max = array[0];
for(int i=1;i<array.length;++i){
if(array[i]>max){
max = array[i];
}
}
return max;
}
}
Also, after this, I tried an alterantive code, where instead of getting individual columns, I would instead store the unwanted columns into an array so they are voided during calculation, but this also does not work. I'll admit very much that I didn't fully understand this method, but it was based on an example code that was given to us without any explanation of what it was doing, so I thought I'd atleast try. It displays the file on the text area, but gives a null pointer exception when I tried to click the max button. http://gyazo.com/27ef7cf9f4bc0c72ecdc3c1f84e6d0f8 Again, appriciate any help. I'm trying to rush a bit cuz my class is coming to me for help cuz last year, I watched a series on java basics in my free time and so had no trouble with our first year work, and they came to me for help. However, I have found no java series or anything on stuff like this, just like specific videos that only help a little. So yeah, really big thanks for any help. :)
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame.
private JPanel contentPane; //Create a container for the GUI.
//Create other components used in the GUI
private JTextField maxTxtVCC;
private JTextField maxTxtTemp;
private JTextField maxTxtLight;
private JTextField minTxtLight;
private JTextField avTxtLight;
private JTextField minTxtTemp;
private JTextField avTxtTemp;
private JTextField minTxtVCC;
private JTextField avTxtVCC;
private JButton btnMax;
private JButton btnMin;
private JButton btnAv;
private JTextField opnTxt;
private JButton btnOpn;
private TextArea textArea;
private JFileChooser fc;
private String content = "";
String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
int totalValues; //Used to hold the amount of values in the array (52790 ish)
Double[][] values;
/**
* Launch the application.
*/
public static void main(String[] args) { //Main method
EventQueue.invokeLater(new Runnable() {
public void run() { //Create a runnable method
try {
CSVFiles frame = new CSVFiles(); //Launch the GUI
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace(); //Print errors
}
}
});
}
/**
* Create the frame.
*/
public CSVFiles() { //Open constructor
super ("CSV Files"); //Create a title for the GUI
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
setBounds(100, 100, 800, 600); //Set size and location
contentPane = new JPanel(); //Declare the JPanel
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
setContentPane(contentPane); //Add the JPanel
contentPane.setLayout(null); //Set the layout
maxTxtVCC = new JTextField(); //Declare this text field
maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
maxTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtVCC); //Add to the content pane
maxTxtTemp = new JTextField(); //Declare this text field
maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
maxTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtTemp); //Add to the content pane
maxTxtLight = new JTextField(); //Declare this text field
maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
maxTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtLight); //Add to the content pane
JLabel lblLight = new JLabel("Light"); //Declare this label
lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblLight.setBounds(22, 469, 46, 17); //Set size and location
contentPane.add(lblLight); //Add to the content pane
JLabel lblTemp = new JLabel("Temperature"); //Declare this label
lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblTemp.setBounds(10, 503, 109, 17); //Set size and location
contentPane.add(lblTemp);
JLabel lblVCC = new JLabel("VCC"); //Declare this label
lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblVCC.setBounds(22, 534, 46, 17); //Set size and location
contentPane.add(lblVCC); //Add to the content pane
minTxtLight = new JTextField(); //Declare this text field
minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
minTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtLight); //Add to the content pane
avTxtLight = new JTextField(); //Declare this text field
avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
avTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtLight); //Add to the content pane
minTxtTemp = new JTextField(); //Declare this text field
minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
minTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtTemp); //Add to the content pane
avTxtTemp = new JTextField(); //Declare this text field
avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
avTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtTemp); //Add to the content pane
minTxtVCC = new JTextField(); //Declare this text field
minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
minTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtVCC); //Add to the content pane
avTxtVCC = new JTextField(); //Declare this text field
avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
avTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtVCC); //Add to the content pane
btnMax = new JButton("Maximum"); //Declare this button
btnMax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double tempArray1 [] = new double [totalValues];
double tempArray2 [] = new double [totalValues];
double tempArray3 [] = new double [totalValues];
for (int i = 0; i < totalValues; i++){
tempArray1[i] = values[i][0]; //assign the indexes along side each individual sensor from sensor value
tempArray2[i] = values[i][1];
tempArray3[i] = values[i][2];
}
//execute the method defined in Utils.java to calculate maximum
maxTxtLight.setText(findMax(tempArray1)+"");
maxTxtTemp.setText(findMax(tempArray2)+"");
maxTxtVCC.setText(findMax(tempArray3)+"");
}
});
btnMax.setBounds(110, 438, 89, 23); //Set size and location
contentPane.add(btnMax); //Add to the content pane
btnMin = new JButton("Minimum"); //Declare this button
btnMin.setBounds(221, 438, 89, 23); //Set size and location
contentPane.add(btnMin); //Add to the content pane
btnAv = new JButton("Average"); //Declare this button
btnAv.setBounds(328, 438, 89, 23); //Set size and location
contentPane.add(btnAv); //Add to the content pane
textArea = new TextArea(); //Declare this text area
textArea.setBounds(22, 55, 551, 367); //Set size and location
textArea.setEditable(false); //Set it so it cannot be edited
contentPane.add(textArea); //Add to the content pane
btnOpn = new JButton("Open File"); //Declare this button
btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
public void actionPerformed(ActionEvent arg0) { //Method for action performed
try{
fc = new JFileChooser(); //Declare the file chooser
fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type
int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
File f; //Create a file to hold the data
//If the selected file is approved by the file chooser...
if(returnVal == JFileChooser.APPROVE_OPTION){
f = fc.getSelectedFile(); //Stored selected file into file variable
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
textArea.append("\nLoading file...\n\n"); //Print out loading message and some new lines
in.readLine(); //Skip the first line as it's just headers
int index = 0; //Integer used to label the indexes of the array
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
}
totalValues = index; //Set a value to the total values
textArea.append(builder.toString()); //Using the string builder to compile the text
textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
in.close(); //Close the reader.
values = new Double [index][3];
for(int i = 0; i < totalValues; i++){
String cols[] = contentCSV[i].split(",");
String tempMillis = cols[0]; //Use a string to take the millis stamp out of the array
String tempStamp = cols[1]; //Use a string to take the time stamp out of the array
String tempDateTime = cols[2]; //Use a string to take the date stamp out of the array
for(int columns=3;columns<cols.length;++columns){
//temp sensor value holds the 9 sensors and the index numbers, parsing the data into double
values[i][columns-3] = Double.parseDouble(cols[columns]);
}
}
}
else{
f = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
btnOpn.setBounds(484, 26, 89, 23); //Set size and location
contentPane.add(btnOpn); //Add to the content pane
opnTxt = new JTextField(); //Declare this text field
opnTxt.setBounds(22, 27, 452, 20); //Set size and location
opnTxt.setEditable(false); //Set it so it cannot be edited
contentPane.add(opnTxt); //Add to the content pane
}
//Methods for Calculations
public static double findMax(double[] array){
double max;
max = array[0];
for(int i=1;i<array.length;++i){
if(array[i]>max){
max = array[i];
}
}
return max;
}
}
The problem is here:
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
c4 = Double.parseDouble(temp[3]);
c5 = Double.parseDouble(temp[4]);
c6 = Double.parseDouble(temp[5]);
}
Your storing your values into temporary local (local to the while loop) variables.
These variables are re-assigned every loop so you lose the information.
You can do one of two things:
Calculate the running SUM, and number of rows in order to calculate the average at the end. Average = SUM / COUNT
Store all values in arraylists, and calculate average at the end.
Example:
double c4avg=0, c5avg=0, c6avg=0;
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
//Calculate Running Sum stored in AVG variable
c4avg += Double.parseDouble(temp[3]);
c5avg += Double.parseDouble(temp[4]);
c6avg += Double.parseDouble(temp[5]);
}
//Divide by total rows to get average
c4avg/=index;
c5avg/=index;
c6avg/=index;
I have this GUI:
I would like after I enter a number in the Length of hot tub text box for that number to be automatically entered into the Width of hot tub text box, but only if the Round Tub radio button is selected.
public void createHotTubs()
{
hotTubs = new JPanel();
hotTubs.setLayout(null);
labelTubStatus = new JTextArea(6, 30);
hotTubs.add(labelTubStatus);
JLabel lengthLabel = new JLabel(
"Length of hot tub(ft):");
lengthLabel.setBounds(10, 15, 260, 20);
hotTubs.add(lengthLabel);
hotTubLengthText = new JTextField();
hotTubLengthText.setBounds(180, 15, 150, 20);
hotTubs.add(hotTubLengthText);
JLabel widthLabel = new JLabel(
"Width of hot tub(ft):");
widthLabel.setBounds(10, 40, 260, 20);
hotTubs.add(widthLabel);
hotTubWidthText = new JTextField();
hotTubWidthText.setBounds(180, 40, 150, 20);
hotTubs.add(hotTubWidthText);
JLabel depthLabel = new JLabel(
"Average depth the hot tub(ft):");
depthLabel.setBounds(10, 65, 260, 20);
hotTubs.add(depthLabel);
hotTubDepthText = new JTextField();
hotTubDepthText.setBounds(180, 65, 150, 20);
hotTubs.add(hotTubDepthText);
JLabel volumeLabel = new JLabel("The hot tub volume is:(ft ^3");
volumeLabel.setBounds(10, 110, 260, 20);
hotTubs.add(volumeLabel);
hotTubVolumeText = new JTextField();
hotTubVolumeText.setBounds(180, 110, 150, 20);
hotTubVolumeText.setEditable(false);
hotTubs.add(hotTubVolumeText);
final JRadioButton rdbtnRoundTub = new JRadioButton("Round Tub");
rdbtnRoundTub.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
hotTubWidthText.setEditable(false);
}
});
rdbtnRoundTub.setSelected(true);
rdbtnRoundTub.setBounds(79, 150, 109, 23);
hotTubs.add(rdbtnRoundTub);
JRadioButton rdbtnOvalTub = new JRadioButton("Oval Tub");
rdbtnOvalTub.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
hotTubWidthText.setEditable(true);
}
});
rdbtnOvalTub.setBounds(201, 150, 109, 23);
hotTubs.add(rdbtnOvalTub);
ButtonGroup radioBtnGroup = new ButtonGroup();
radioBtnGroup.add(rdbtnRoundTub);
radioBtnGroup.add(rdbtnOvalTub);
JButton btnCalculateVlmn = new JButton("Calculate Volume");
btnCalculateVlmn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
double width = 0, length = 0, depth = 0, volume = 0;
String lengthString, widthString, depthString;
lengthString = hotTubLengthText.getText();
widthString = hotTubWidthText.getText();
depthString = hotTubDepthText.getText();
depth = Double.valueOf(depthString);
length = Double.valueOf(lengthString);
width = Double.valueOf(widthString);
try
{
if (rdbtnRoundTub.isSelected())
{
volume = length * width * depth;
}
else
{
volume = Math.PI * length * width / 4 * depth;
}
DecimalFormat formatter = new DecimalFormat("#,###,###.###");
hotTubVolumeText.setText("" + formatter.format(volume));
}
catch (NumberFormatException e)
{
labelTubStatus
.setText("Enter all three numbers!!");
}
}
});
Add a focus listener to your length text field when it loses focus and the round tub is selected, compute and set the the width.