I have a register button where when i press register it should write the values to details.txt that was typed in the textfield. When i register for the first time it works but if the file contains some values it will freeze if i try to register the second time. Anyone can help to debug this pls?
Main Class
package assignment;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment
{
JFrame mainFrame;
JPanel framePanel,leftPnl,topPnl,btmPnl;
JLabel welcomeLabel,studId,passwd;
JTextField studField,passField;
JButton logBtn,signBtn;
Color btnClr,btnTxtClr,backgroundClr,lblClr;
Font mainFont,labelFont;
public void mainPage()
{
mainFrame = new JFrame("CGPA Calculator");
framePanel = new JPanel();
//-------------------Creating Components/Setting Fonts/Color----------------
-------------------------------------------
//Color
btnClr = new Color(0, 179, 60);
btnTxtClr = new Color(255,255,255);
backgroundClr = new Color(26, 26, 26);
lblClr = new Color(255,255,255);
//Fonts
mainFont = new Font("Verdana",Font.PLAIN,40);
labelFont = new Font("Verdana",Font.PLAIN,20);
//Button
logBtn = new JButton("<html><font face=\"Verdana\">Login</font></html>");//Source from:https://stackoverflow.com/questions/21046164/jbutton-text-with-different-font-family-in-different-words
logBtn.setFocusPainted(false);
logBtn.setBackground(btnClr);
logBtn.setForeground(btnTxtClr);
signBtn = new JButton("<html><font face=\"Verdana\">Register</font></html>");
signBtn.setFocusPainted(false);
signBtn.setBackground(btnClr);
signBtn.setForeground(btnTxtClr);
//Label
welcomeLabel = new JLabel("CGPA Calculator");
welcomeLabel.setForeground(lblClr);
studId = new JLabel("Student ID :");
studId.setForeground(lblClr);
passwd = new JLabel("Password :");
passwd.setForeground(lblClr);
//TextField
studField = new JTextField(8);
studField.setBorder(javax.swing.BorderFactory.createEmptyBorder());//Sourced From:https://stackoverflow.com/questions/2281937/swing-jtextfield-how-to-remove-the-border
passField = new JTextField(8);
passField.setBorder(BorderFactory.createEmptyBorder());
//Adding Fonts to Components
welcomeLabel.setFont(mainFont);
studId.setFont(labelFont);
passwd.setFont(labelFont);
//Panel
leftPnl = new JPanel();
topPnl = new JPanel();
btmPnl = new JPanel();
//----------------------Adding of panels/layout/components--------------------------------------------------------
//Seting up layouts to panel
leftPnl.setLayout(new FlowLayout());
btmPnl.setLayout(new BoxLayout(btmPnl,BoxLayout.X_AXIS));
//TOPPANEL(Adjustments)
topPnl.setBackground(backgroundClr);
topPnl.add(welcomeLabel);
topPnl.add(Box.createRigidArea(new Dimension(0,150)));
//LEFTPANEL(Adjustements)
leftPnl.setBackground(backgroundClr);
leftPnl.add(Box.createRigidArea(new Dimension(0,70)));
leftPnl.add(studId);
leftPnl.add(studField);
leftPnl.add(passwd);
leftPnl.add(passField);
//BOTTOMPANEL
btmPnl.setBackground(backgroundClr);
btmPnl.add(Box.createRigidArea(new Dimension(130,0)));
btmPnl.add(logBtn);
btmPnl.add(Box.createRigidArea(new Dimension(40,0)));
btmPnl.add(signBtn);
btmPnl.add(Box.createRigidArea(new Dimension(200,200)));
//Action Listeners(lambda expression)
signBtn.addActionListener((ActionEvent e) -> {
SignUpPage sign = new SignUpPage();
sign.SecondPage();
sign.getFrame().setVisible(true);
//mainFrame.setVisible(false);
});
mainFrame.getContentPane().setBackground(backgroundClr);
mainFrame.add(topPnl,BorderLayout.NORTH);
mainFrame.add(leftPnl,BorderLayout.WEST);
mainFrame.add(btmPnl,BorderLayout.SOUTH);
mainFrame.setVisible(true);
mainFrame.setSize(450,450);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Assignment display = new Assignment();
display.mainPage();
new SignUpPage();
}
}
register class
package assignment;
import javax.swing.*;
import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import java.io.*;
public class SignUpPage
{
private JFrame signFrame;
JTextField idField,passwdField;
JButton registerBtn,cancelBtn,resetBtn;
JLabel studIdLbl,passwdLbl,schoolLbl,label;
JComboBox schoolBox;
String [] school = {"School Of Computing & Creative Media","School Of
Communication & Creative Arts","School Of Engineering","School Of Business"
,"School of Hospiality Tourism & Culinary Arts"};
Font labelFont;
Color btnClr,btnTxtClr,lblClr,backgroundClr;
String selectSchool;
BufferedReader validateFile;
String details;
String detailsArray[];
int detailsExists = 0;
public void SecondPage()
{
//ComboBox(Class)
label = new JLabel("");
//Color
btnClr = new Color(0, 179, 60);
btnTxtClr = new Color(255,255,255);
backgroundClr = new Color(26, 26, 26);
lblClr = new Color(255,255,255);
//Font
labelFont = new Font("Verdana",Font.PLAIN,13);
//JTextField
idField = new JTextField("Student ID",4);
idField.setMinimumSize(new Dimension(300,30));
idField.setMaximumSize(new Dimension(300,30));
idField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
passwdField = new JTextField("Password",4);
passwdField.setMinimumSize(new Dimension(300,30));
passwdField.setMaximumSize(new Dimension(300,30));
passwdField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
//JComboBox
schoolBox = new JComboBox(school);
schoolBox.setFont(labelFont);
schoolBox.setMinimumSize(new Dimension(300,30));
schoolBox.setMaximumSize(new Dimension(300,30));
schoolBox.addActionListener((ActionEvent e)->{
JComboBox <String> schoolCombo = (JComboBox<String>) e.getSource();
selectSchool = (String) schoolCombo.getSelectedItem();
});
//Panel
JPanel fieldPnl = new JPanel();
JPanel btnPnl = new JPanel();
//Button
registerBtn = new JButton("<html><font face=\"Verdana\">Register</font></html>");
registerBtn.setBackground(btnClr);
registerBtn.setForeground(lblClr);
cancelBtn = new JButton("<html><font face=\"Verdana\">Cancel</font></html>");
cancelBtn.setBackground(btnClr);
cancelBtn.setForeground(lblClr);
resetBtn = new JButton("<html><font face=\"Verdana\">Reset</font></html>");
resetBtn.setBackground(btnClr);
resetBtn.setForeground(lblClr);
//Label
studIdLbl = new JLabel("Student ID:");
passwdLbl = new JLabel("Password");
schoolLbl = new JLabel("School:");
//Adding Components to Panel
fieldPnl.add(Box.createRigidArea(new Dimension(0,100)));
fieldPnl.setBackground(backgroundClr);
fieldPnl.add(idField);
fieldPnl.add(Box.createRigidArea(new Dimension(0,10)));
fieldPnl.add(passwdField);
fieldPnl.add(Box.createRigidArea(new Dimension(0,10)));
fieldPnl.add(schoolBox);
fieldPnl.add(Box.createRigidArea(new Dimension(0,50)));
btnPnl.setBackground(backgroundClr);
btnPnl.add(registerBtn);
btnPnl.add(cancelBtn);
btnPnl.add(resetBtn);
btnPnl.add(label);
btnPnl.add(Box.createRigidArea(new Dimension(0,190)));
//Layout
fieldPnl.setLayout(new BoxLayout(fieldPnl,BoxLayout.Y_AXIS));
//Action Listener
registerBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedWriter toFile;
try {
signUpValidation();
if(detailsExists==0)
{
toFile = new BufferedWriter(new FileWriter("details.txt",true));
toFile.write(idField.getText() + "," + passwdField.getText() + ","+selectSchool);
toFile.newLine();
toFile.flush();
}
else if(detailsExists==1)
{
//same values exists in file
}
} catch(FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
signFrame = new JFrame("Sign Up");
signFrame.add(btnPnl,BorderLayout.SOUTH);
signFrame.add(fieldPnl,BorderLayout.CENTER);
signFrame.setVisible(true);
signFrame.setSize(450,450);
signFrame.setResizable(false);
signFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
public Frame getFrame()
{
return signFrame;
}
public int signUpValidation() throws IOException
{
validateFile = new BufferedReader(new FileReader("details.txt"));
details = validateFile.readLine();
while(details!=null)
{
detailsArray=details.split(",");
if(idField.equals(detailsArray[0]) || passwdField.equals(detailsArray[1]))
{
detailsExists = 1;
}
else
detailsExists = 0;
}
return detailsExists;
}
}
while(details!=null) prevents the loop from ever exiting, because details is not updated with in the loop's context - it never becomes null
Something like...
String details = null;
while((details = validateFile.readLine()) !=null) {...
might be safer. But based on your code, you're only expecting a single line, so getting rid of the loop altogether might be a better solution
Related
I am very new to Java, but I'm using it for a school project to make a student tracker. I'm just starting with the layout, and am adding students to a file right now. On line 138, I need a way to add a counter every time I click the add button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
File StudentNames = new File("StudentNames.txt");
File StudentGrades = new File("StudentGrades.txt");
File StudentScore = new File("StudentScore.txt");
FileWriter NameFileWriter = new FileWriter("StudentNames.txt");
FileWriter GradeFileWriter = new FileWriter("StudentGrades.txt");
FileWriter ScoreFileWriter = new FileWriter("StudentScore.txt");
FileReader NameFileReader = new FileReader(StudentNames);
FileReader GradeFileReader = new FileReader(StudentGrades);
FileReader ScoreFileReader = new FileReader(StudentScore);
String[] NamesString = new String[] {""};
List<String> NamesList = Arrays.asList(NamesString);
JFrame frame = new JFrame("Tyke Tracking");
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Adding a panel to center the buttons
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints Center = new GridBagConstraints();
Center.gridx = 0;
JButton StudentsButton = new JButton("Students");
panel.add(StudentsButton, Center);
Center.gridx = 1;
JButton PrizesButton = new JButton("Prizes");
panel.add(PrizesButton, Center);
frame.getContentPane().add(panel);
frame.setVisible(true);
//Student Section
JFrame StuFrame = new JFrame("Tyke Tracking Students");
StuFrame.setSize(500,500);
StuFrame.setResizable(false);
StuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel StuPanelLeft = new JPanel();
JTextArea StudentsListed = new JTextArea();
StudentsListed.setEditable(false);
StudentsListed.setPreferredSize((new Dimension(250,500)));
StuPanelLeft.add(StudentsListed);
JPanel StuPanelRight = new JPanel(new GridBagLayout());
GridBagConstraints StuRight = new GridBagConstraints();
StuRight.gridy = 0;
JButton AddStu = new JButton("Add Students");
StuPanelRight.add(AddStu, StuRight);
StuRight.gridy = 1;
JButton EditStu = new JButton("Edit Students");
StuPanelRight.add(EditStu, StuRight);
StuRight.gridy = 2;
JButton Report = new JButton("Get Report");
Report.setPreferredSize(new Dimension(130,23)); //Making it even to other buttons
StuPanelRight.add(Report, StuRight);
StuRight.gridy = 3;
JButton backButton = new JButton("Back");
backButton.setPreferredSize(new Dimension(130,23));
StuPanelRight.add(backButton, StuRight);
StuFrame.getContentPane().add(StuPanelLeft, BorderLayout.WEST);
StuFrame.getContentPane().add(StuPanelRight);
//Adding Students
JFrame Adding = new JFrame("Adding Students");
Adding.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Adding.setSize(200,150);
Adding.setResizable(false);
JPanel AddStuPanel = new JPanel(new GridBagLayout());
JPanel AddStuPanelTop = new JPanel(new GridBagLayout());
GridBagConstraints AddStuGBC = new GridBagConstraints();
AddStuGBC.gridy = 1;
AddStuGBC.fill = GridBagConstraints.HORIZONTAL;
JTextField addNameField = new JTextField();
addNameField.setPreferredSize(new Dimension(150,20));
AddStuPanelTop.add(addNameField, AddStuGBC);
AddStuGBC.gridy = 0;
JLabel nameLabel = new JLabel("Name:");
AddStuPanelTop.add(nameLabel, AddStuGBC);
AddStuGBC.gridy = 2;
JLabel gradeLabel = new JLabel("Grade %:");
AddStuPanelTop.add(gradeLabel, AddStuGBC);
AddStuGBC.gridy = 3;
JTextField addGradeField = new JTextField();
addGradeField.setPreferredSize(new Dimension(150,20));
AddStuPanelTop.add(addGradeField, AddStuGBC);
AddStuGBC.gridy = 4;
JButton addButton = new JButton("Add");
AddStuPanel.add(addButton, AddStuGBC);
AddStuGBC.gridx = 1;
JButton closeButton = new JButton("Close");
AddStuPanel.add(closeButton, AddStuGBC);
Adding.getContentPane().add(AddStuPanelTop, BorderLayout.CENTER);
Adding.getContentPane().add(AddStuPanel, BorderLayout.SOUTH);
Adding.setVisible(false);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
NameFileWriter.append(addNameField.getText());
NameFileWriter.close();}
catch (IOException ignored) {}
try {
GradeFileWriter.append(addGradeField.getText());
GradeFileWriter.close();}
catch (IOException ignored) {}
//Way to count how many students there are, to write to correct line in files
}
});
closeButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Adding.setVisible(false);
}
});
StudentsButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
StuFrame.setVisible(true);
}
});
backButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
StuFrame.setVisible(false);
frame.setVisible(true);
}
});
AddStu.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Adding.setVisible(true);
}
});
}
}
I tried to name a variable and use a++, but I can't use it and keep adding since it's accessed within an inner variable. If I initiated it inside, then it would initiate it back every time i clicked the button.
Edit: As noted in the comments, Swing is single threaded so thread safety is not a concern with this solution. Nonetheless, using an AtomicInteger here is still an effective way of maintaining the click count from this anonymous class. A class member in the containing class would be a better solution but this is executed from a static context so I hesitate to suggest that.
AtomicInteger atomicInteger = new AtomicInteger(0);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
NameFileWriter.append(addNameField.getText());
NameFileWriter.close();}
catch (IOException ignored) {}
try {
GradeFileWriter.append(addGradeField.getText());
GradeFileWriter.close();}
catch (IOException ignored) {}
// Way to count how many students there are, to write to correct line in files
// Every time this statement is called, one is added
// to the total and the total is returned
int totalClicks = atomicInteger.addAndGet(1);
}
});
For class I'm supposed to be creating an application that first lets you choose which value you'd like to calculate, then asks to enter the appropriate info. Then when you click "calculate", it SHOULD display the answer. For some reason my JLabel that should be displaying the answer isn't showing up. I've been searching for a solution, but every thing I do, nothing appears after you click "calculate". I am a novice, please help :(
package decay.application;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecayApplication implements ActionListener {
JFrame frame;
JPanel content;
JLabel prompt1, prompt2, prompt3, prompt4, displayFinal, displayIntitial, displayConstant, choose;
JTextField enterFinal, enterInitial, enterConstant, enterElapsed;
JButton finButton, inButton, conButton, calculate1, calculate2, calculate3;
public DecayApplication(){
frame = new JFrame("Decay Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JPanel();
content.setLayout(new GridLayout(0, 2, 10, 5));
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
choose = new JLabel("Which would you like to calculate?");
content.add(choose);
finButton = new JButton("Final Amount");
finButton.setActionCommand("finalAmount");
finButton.addActionListener(this);
content.add(finButton);
inButton = new JButton("Initial Amount");
inButton.setActionCommand("initialAmount");
inButton.addActionListener(this);
content.add(inButton);
conButton = new JButton("Constant");
conButton.setActionCommand("constant");
conButton.addActionListener(this);
content.add(conButton);
frame.setContentPane(content);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){new DecayApplication();}
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
}
}
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
DecayApplication decay = new DecayApplication();
}
}
Here's your method actionPerformed:
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
//here should the if-loop end, because here is the end of instructions which should be called after clicking on the button
}
//and here the second if-loop
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
I am receiving this error when i change items in the Jcombobox, nothing breaks it just shows this error, is there anyway to just throw it so it doesn't show up. everything still works fine, but if you wish to have a look at the code. i will post below.
Error message:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:2056)
at java.awt.Component.getLocationOnScreen(Component.java:2030)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:395)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:393)
at sun.lwawt.macosx.LWCToolkit$CallableWrapper.run(LWCToolkit.java:538)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301)
And my code which i don't know which section to show so its all their.
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class TouchOn extends JDialog {
private JPanel mainPanel;
public ArrayList Reader(String Txtfile) {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File(Txtfile);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
if(!line.contains("*")){
Trains.add(line + "\n");
}
stringBuffer.append("\n");
}
fileReader.close();
//Arrays.asList(Trains).stream().forEach(s -> System.out.println(s));
return Trains;
} catch (IOException e) {
e.printStackTrace();
}
//return toString();
return null;
}
public TouchOn()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
JTextField touchOnTimeFieldhour = new JTextField();
JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
apply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if(belgrave.isSelected()){
String trainline = belgrave.getText();
}
if(glenwaverly.isSelected()){
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10,10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Don't create multiple JComboBoxes and then swap visibility. Instead use one JComboBox and create multiple combo box models, such as by using DefaultComboBoxModel<String>, and then swap out the model that it holds by using its setModel(...) method. Problem solved.
Note that using a variation on your code -- I'm not able to reproduce your problem:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFoo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
public static void createAndDisplayGui() {
final JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent evt) {
TouchOn2 touchOn2 = new TouchOn2(frame);
touchOn2.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class TouchOn2 extends JDialog {
private JPanel mainPanel;
#SuppressWarnings({ "rawtypes", "unused" })
public ArrayList Reader(String Txtfile) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add("Data String Number " + (i + 1));
}
// return toString();
// !! return null;
return list;
}
public TouchOn2(Window owner) {
super(owner);
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
#SuppressWarnings("unchecked")
public void setPanels() {
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
final JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
final JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
final JTextField sYear = new JTextField("2015");
final String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
final JTextField touchOnTimeFieldhour = new JTextField();
final JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
final JComboBox<String> cb = new JComboBox<>(
stations.toArray(new String[stations.size()]));
final JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
final JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
apply.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e) {
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy")
.format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if (belgrave.isSelected()) {
// !! ***** note you're shadowing variables here!!!! ****
String trainline = belgrave.getText();
}
if (glenwaverly.isSelected()) {
// !! and here too
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10, 10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.
I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!
Here is a photobucket directURL PrtSc of the UI, hope it helps.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Let's start with...
if (e.getActionCommand() == "Add More") {
Is not how you compare Strings in Java, you need to use the equals method instead, something like...
if ("Add More".equals(e.getActionCommand())) {
for example
Next you do...
add(inputPanel);
add(buttonPanel);
add(outputPanel);
which, when using a BorderLayout, adds each of the components to the default position within the BorderLayout, you need to provide position constraints for each component, otherwise strange things begin to happen, for example...
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
I just realised that you're using a GridLayout, personally, I think you'll get a better result from BorderLayout, but that's me
And then you create a new instance of resultTable and outputPanel, but you never add outputPanel to anything...
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][1]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
A better idea would be to create resultTable, wrap in a JScrollPane and add it to your screen.
When you want to "print" the data, create a new TableModel and apply it to the JTable
For example...
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
Take a look at How to Use Tables and How to Use Scroll Panes for more details
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class PayrollFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
PayrollFrame frame = new PayrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame() {
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel);
add(outputPanel, BorderLayout.SOUTH);
setVisible(true);
}
private void buildInputPanel() {
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel() {
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
TableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add More".equals(e.getActionCommand())) {
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
} else if ("Display Result".equals(e.getActionCommand())) {
printData();
} else if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString) {
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if (tempHour <= 40) {
salary.add(Double.toString(tempHour * tempRate));
} else {
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Thanks for #MadProgrammer 's help! His reply helps me to fix many problems I have, and really tried to explain things to me. After consulting with my instructor, I have successfully compile and run my program by editing the printData method.
private void printData()
{
DefaultTableModel model = new DefaultTableModel(columnNames,name.size());
resultTable.setModel(model);
for(int i=0; i<name.size(); i++)
{
resultTable.setValueAt(name.get(i),i,0);
resultTable.setValueAt(department.get(i),i,1);
resultTable.setValueAt(salary.get(i),i,2);
}
}
I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}