java GUI how to save into text file - java

i need to save texts from text boxes to text file but any code i found on or made it didn't work, any idea? like any at all? which code would work. i had to use java gui where my teacher teach us about java, but nothing about GUI so ii cant even make save to text file.
public class FlightsPanel extends JPanel {
private Flight flightSelected = null;
private JTextField textFieldDepartureAirport;
private JTextField textFieldArrivalAirport;
private JTextField textFieldDepartureDate;
private JTextField textFieldArrivalDate;
private JRadioButton rdbtnBoarding;
private JRadioButton rdbtnChecking;
private JRadioButton rdbtnAvailable;
private JRadioButton rdbtnClosed;
private JTextField textFieldCost;
private DefaultListModel<String> populateFlights() {
DefaultListModel<String> list = new DefaultListModel<String>();
ArrayList<Flight> FlightList = MainMenu.getAirlineMgr().getFlightList();
for (int i = 0; i < FlightList.size(); i++) {
list.addElement(FlightList.get(i).getFlightNumber());
}
return list;
}
private void displayFlight(String number) {
flightSelected = MainMenu.getAirlineMgr().getFlightByNumber(number);
textFieldDepartureAirport.setText(flightSelected.getDepartureAirport());
textFieldArrivalAirport.setText(flightSelected.getArrivalAirport());
textFieldDepartureDate.setText(flightSelected.getDepartureDate().toString());
textFieldArrivalDate.setText(flightSelected.getArrivalDate().toString());
textFieldCost.setText(Double.toString(flightSelected.getCost()));
if (flightSelected.getFlightStatus() == Flight.Status.AVAILABLE) {
rdbtnAvailable.setSelected(true);
} else {
if (flightSelected.getFlightStatus() == Flight.Status.BOARDING) {
rdbtnBoarding.setSelected(true);
} else {
if (flightSelected.getFlightStatus() == Flight.Status.CHECKING) {
rdbtnChecking.setSelected(true);
} else {
if (flightSelected.getFlightStatus() == Flight.Status.CLOSED) {
rdbtnClosed.setSelected(true);
}
}
}
}
}
private void saveFlight() {
flightSelected.setDepartureAirport(textFieldDepartureAirport.getText());
flightSelected.setArrivalAirport(textFieldArrivalAirport.getText());
flightSelected.setCost(Double.parseDouble(textFieldCost.getText()));
// flightSelected.setDepartureDate(textFieldDepartureDate.getText());
// flightSelected.setArrivalDate(textFieldArrivalDate.getText());
if (rdbtnAvailable.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.AVAILABLE);
} else {
if (rdbtnBoarding.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.BOARDING);
} else {
if (rdbtnChecking.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.CHECKING);
} else {
if (rdbtnClosed.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.CLOSED);
}
}
}
}
}
public FlightsPanel() {
setBackground(new Color(175, 238, 238));
setLayout(null);
JList list = new JList(populateFlights());
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
displayFlight(list.getSelectedValue().toString());
}
});
list.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
list.setBounds(141, 161, 89, 81);
add(list);
JLabel lblNewLabel = new JLabel("Available flights:");
lblNewLabel.setBounds(141, 136, 121, 14);
add(lblNewLabel);
textFieldDepartureAirport = new JTextField();
textFieldDepartureAirport.setBounds(206, 36, 112, 20);
add(textFieldDepartureAirport);
textFieldDepartureAirport.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Departure Airport:");
lblNewLabel_1.setBounds(206, 11, 112, 14);
add(lblNewLabel_1);
textFieldArrivalAirport = new JTextField();
textFieldArrivalAirport.setColumns(10);
textFieldArrivalAirport.setBounds(10, 36, 112, 20);
add(textFieldArrivalAirport);
JLabel lblArrivalAirport = new JLabel("Arrival Airport:");
lblArrivalAirport.setBounds(10, 11, 112, 14);
add(lblArrivalAirport);
textFieldDepartureDate = new JTextField();
textFieldDepartureDate.setColumns(10);
textFieldDepartureDate.setBounds(206, 91, 192, 20);
add(textFieldDepartureDate);
JLabel lblDepartureDate = new JLabel("Departure Date:");
lblDepartureDate.setBounds(206, 67, 112, 14);
add(lblDepartureDate);
textFieldArrivalDate = new JTextField();
textFieldArrivalDate.setColumns(10);
textFieldArrivalDate.setBounds(10, 91, 192, 20);
add(textFieldArrivalDate);
JLabel lblArrivalDate = new JLabel("Arrival Date:");
lblArrivalDate.setBounds(10, 66, 112, 14);
add(lblArrivalDate);
rdbtnBoarding = new JRadioButton("BOARDING");
rdbtnBoarding.setBounds(10, 211, 112, 23);
add(rdbtnBoarding);
rdbtnChecking = new JRadioButton("CHECKING");
rdbtnChecking.setBounds(10, 237, 112, 23);
add(rdbtnChecking);
rdbtnAvailable = new JRadioButton("AVAILABLE");
rdbtnAvailable.setBounds(10, 159, 112, 23);
add(rdbtnAvailable);
JLabel lblStatus = new JLabel("Status:");
lblStatus.setBounds(20, 138, 220, 14);
add(lblStatus);
rdbtnClosed = new JRadioButton("CLOSED");
rdbtnClosed.setBounds(10, 185, 112, 23);
add(rdbtnClosed);
ButtonGroup group = new ButtonGroup();
group.add(rdbtnBoarding);
group.add(rdbtnChecking);
group.add(rdbtnAvailable);
group.add(rdbtnClosed);
JButton button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MainMenu.hideFlights();
}
});
button.setBounds(10, 269, 89, 23);
add(button);
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveFlight();
MainMenu.hideFlights();
}
});
btnConfirm.setBounds(351, 269, 89, 23);
add(btnConfirm);
JLabel lblCost = new JLabel("Cost:");
lblCost.setBounds(341, 11, 112, 14);
add(lblCost);
textFieldCost = new JTextField();
textFieldCost.setColumns(10);
textFieldCost.setBounds(328, 36, 112, 20);
add(textFieldCost);
}
}pic of design

You can use basic file writing from Java. The only difference here from basic file writing is that you need to get the Strings to write from the text attributes of your objects. Here is one example from your code:
import java.io.PrintWriter;
try{
PrintWriter fileWriter = new PrintWriter("myFile.txt", "UTF-8");
fileWriter.println(textFieldDepartureAirport.selectAll());
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
Since your teacher did not include much about the UI items, you are able to look up the JavaDoc info about the object type that is holding the data. For example, your text boxes are declared as JTextField, so you can find more info about this class here:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html

Related

Clip won't stop in Java after reopening panel

I am writing a music player that can be played in background while users do their thing. The problem is when I exit the music player panel into other panel, the music can't be stopped anymore.
Here is my code
JButton btnAddMusic = new JButton("add music");
btnAddMusic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
returnValue=browser.showOpenDialog(main);
if(returnValue==browser.APPROVE_OPTION){
selectedFile=browser.getSelectedFile();
String filepath=selectedFile.toString();
String filename=selectedFile.getName();
main.getController().storeMusic(filename, filepath);
populateJComboBox();
}
}
});
btnAddMusic.setBounds(15, 187, 115, 29);
add(btnAddMusic);
JButton btnlogout = new JButton("");
btnlogout.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19));
btnlogout.setBackground(UIManager.getColor("Button.background"));
Image aimg= new ImageIcon(this.getClass().getResource("/logot.png")).getImage();
Image aImage = aimg.getScaledInstance(55, 55, Image.SCALE_DEFAULT);
btnlogout.setIcon(new ImageIcon(aImage));
btnlogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
main.showRegisterPanel();
}
});
btnlogout.setForeground(UIManager.getColor("Button.foreground"));
btnlogout.setBackground(Color.WHITE);
btnlogout.setOpaque(true);
btnlogout.setBorderPainted(false);
btnlogout.setBounds(411, 0, 64, 53);
add(btnlogout);
JLabel icon = new JLabel("");
icon.setBounds(15, 16, 93, 81);
Image img= new ImageIcon(this.getClass().getResource("/tplogo.png")).getImage();
Image newImage = img.getScaledInstance(70, 70, Image.SCALE_DEFAULT);
icon.setIcon(new ImageIcon(newImage));
add(icon);
JLabel lblNewLabel = new JLabel("Music Player");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNewLabel.setBounds(155, 29, 276, 53);
add(lblNewLabel);
this.btnhome = new JButton("");
btnhome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
check();
}
});
btnhome.setBackground(Color.WHITE);
btnhome.setBounds(180, 232, 75, 63);
Image home= new ImageIcon(this.getClass().getResource("/home.png")).getImage();
Image ahome = home.getScaledInstance(55, 55, Image.SCALE_DEFAULT);
btnhome.setIcon(new ImageIcon(ahome));
btnhome.setForeground(UIManager.getColor("Button.foreground"));
btnhome.setBackground(Color.WHITE);
btnhome.setOpaque(true);
btnhome.setBorderPainted(false);
add(btnhome);
JButton btnPlay = new JButton("play");
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
for(int i=0;i<1024;i++){
try{
if(comboBox.getSelectedIndex()==i){
sound=new File(music[comboBox.getSelectedIndex()]);
ais=AudioSystem.getAudioInputStream(sound);
clip=AudioSystem.getClip();
clip.open(ais);
clip.start();
}
}catch(Exception e){
}
}
}});
btnPlay.setBounds(170, 187, 115, 29);
add(btnPlay);
JButton btnStop = new JButton("stop");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clip.stop();
}
});
btnStop.setBounds(320, 187, 115, 29);
add(btnStop);
browser.setFileFilter(filter);
this.comboBox = new JComboBox();
comboBox.setBounds(77, 111, 262, 26);
add(comboBox);
populateJComboBox();
}
private void populateJComboBox() {
this.mu = this.main.getController().getAllMusic(); //get hardcoded cluster details
DefaultComboBoxModel model = new DefaultComboBoxModel();
for(int i = 0; i<mu.length; i++) // for loop to add the cluster details into the comboBox model
{
Music clu = mu[i];
model.addElement(clu.getMname());
music[i]=clu.getMc();
}
this.comboBox.setModel(model); //setting the comboBox model with the model with cluster details added
}
private void check(){
this.user = this.main.getController().getAllUsers();
for(int i = 0; i<user.length;i++)
{
User use = user[i];
String aa = use.getType();
if(aa=="Student"){
main.showSthomepanel();
}
else if(aa=="Staff"){
main.showshomePanel();
}
else{
btnhome.setEnabled(false);
}
}
The initialise is done, but I can't post because of this weird code system.
This problem is caused by the focus being taken away from the panel. The easiest way to fix this is to use a JWindow instead of a JPanel.

Jcombobox not selecting item

Im trying to insert the Jcombobox value into my sqlite database but whenever I run the program, it only inserts '9' in to my database. Please advise. I am trying to import the integer that the user picks into my sqlite database. For some reason, even with the action listener, the default value, 9, is still being inputed into the table and im not sure why. Here is the full code, not including the connection and the Jtable.
public class create extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
create frame = new create();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
private JTextField textField_2;
String uniqueString = UUID.randomUUID().toString();
private JTextField textField_3;
/**
* Create the frame.
*/
public create() {
connect = connection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 204, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblStudentName = new JLabel("Student ID:");
lblStudentName.setBounds(96, 69, 72, 16);
contentPane.add(lblStudentName);
textField = new JTextField();
textField.setBounds(173, 64, 216, 26);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblGrade = new JLabel("Grade:");
lblGrade.setBounds(125, 107, 47, 16);
contentPane.add(lblGrade);
JComboBox comboBox = new JComboBox();
comboBox.addItem(9);
comboBox.addItem(10);
comboBox.addItem(11);
comboBox.addItem(12);
comboBox.setBounds(173, 102, 72, 29);
contentPane.add(comboBox);
comboBox.setSelectedItem(9);
comboBox.addActionListener(comboBox);
int selectedNumber = (int)comboBox.getSelectedItem();
JLabel lblInputBookOver = new JLabel("Teacher:");
lblInputBookOver.setBounds(111, 146, 61, 21);
contentPane.add(lblInputBookOver);
textField_1 = new JTextField();
textField_1.setBounds(173, 143, 216, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton button = new JButton("<");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int count = 0; count <= 0; count++) {
//dispose();
options sc = new options();
sc.setVisible(true);
}
}
});
button.setBounds(6, 6, 30, 29);
contentPane.add(button);
JLabel lblStudentname = new JLabel("Student Name:");
lblStudentname.setBounds(74, 31, 99, 16);
contentPane.add(lblStudentname);
textField_2 = new JTextField();
textField_2.setBounds(173, 26, 216, 26);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(125, 180, 42, 26);
contentPane.add(lblEmail);
textField_3 = new JTextField();
textField_3.setBounds(173, 180, 216, 26);
contentPane.add(textField_3);
textField_3.setColumns(10);
JButton btnCheckout = new JButton("Checkout");
btnCheckout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String uniqueString = UUID.randomUUID().toString().replace("-", "");
try {
String query = "insert into data ('Name', 'Student ID', 'Teacher', 'Grade', 'Email', 'Ebook') values (?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1,textField_2.getText() );
pst.setString(2,textField.getText() );
pst.setString(3,textField_1.getText() );
pst.setInt(4, selectedNumber);
pst.setString(5,textField_3.getText() );
pst.setString(6, uniqueString);
for (int count = 0; count <= 0; count++) {
//dispose();
confirm sc = new confirm();
sc.setVisible(true);
count = 0;
}
pst.execute();
pst.close();
}
catch (Exception w){
w.printStackTrace();
}
}
});
btnCheckout.setBounds(173, 218, 117, 29);
contentPane.add(btnCheckout);
}
}
It inserts 9 to your database because the selected item is always 9, and this because you add it first to your combobox. In order to insert the selected value, you will have to use an ActionListener. Then you can take user's selection and do whatever you want.
An example of its usage:
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ComboBox extends JFrame {
public ComboBox() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
JComboBox<Integer> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedItem(42); // The initial selection is 42.
comboBox.addActionListener(e -> {
int selectedNumber = (int) comboBox.getSelectedItem();
System.out.println("Selected number: " + selectedNumber);
// Do whatever with selected number
});
add(comboBox);
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
}
}

Issue in Radio Button Action Listener

I have written some code when one of the option in radio button is clicked
it should display one jlabel and jtext field. And when other option in the radio button is clicked it should hide the previous shown jlabel and jtext field and display new jlabel and jtext field.
In the output when I click on one of the radio button it is displaying nothing unless and until I maximize my Window. After geting my jlabel and jtextfield If I click on other radio button the jlabel and jtextfield is hidden but Im not able to see new jlabel and jtextfield for that radiobutton.
enter code here
public class Emp4 {
private JFrame frame;
private JTextField jtxtName;
private JTextField jtxtAge;
private JTextField jtxtSal;
private JTextField jtxtHour_Pay;
private JTextField jtxtHour_Worked;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Emp4 window = new Emp4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Emp4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(30, 11, 414, 36);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblEmployeeDatabase = new JLabel("Employee Database");
lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblEmployeeDatabase.setBounds(157, 7, 193, 25);
panel.add(lblEmployeeDatabase);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel_1.setBounds(10, 61, 464, 230);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel jlblEmpName = new JLabel("Employee Name");
jlblEmpName.setBounds(10, 11, 110, 14);
panel_1.add(jlblEmpName);
jtxtName = new JTextField();
jtxtName.setBounds(114, 8, 120, 20);
panel_1.add(jtxtName);
jtxtName.setColumns(10);
JLabel jlblEmpAge = new JLabel("Employee Age");
jlblEmpAge.setBounds(10, 52, 110, 14);
panel_1.add(jlblEmpAge);
jtxtAge = new JTextField();
jtxtAge.setColumns(10);
jtxtAge.setBounds(114, 49, 120, 20);
panel_1.add(jtxtAge);
JLabel jlblEmpType = new JLabel("Employee Type");
jlblEmpType.setBounds(10, 95, 110, 14);
panel_1.add(jlblEmpType);
JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
JRadioButton jrdbtnContract = new JRadioButton("Contract ");
JLabel jlblEmpHour = new JLabel("Hourly Rate");
jlblEmpHour.setBounds(5, 121, 66, 14);
ButtonGroup group =new ButtonGroup();
JLabel jlblEmpSal = new JLabel("Salary");
jlblEmpSal.setBounds(114, 121, 66, 14);
JLabel jlblEmpWork = new JLabel("Hours Worked");
jlblEmpWork.setBounds(150, 120, 86, 24);
jtxtSal = new JTextField();
jtxtSal.setColumns(10);
jtxtSal.setBounds(164, 121, 109, 23);
jtxtHour_Pay = new JTextField();
jtxtHour_Pay.setColumns(10);
jtxtHour_Pay.setBounds(75, 121, 59, 23);
jtxtHour_Worked = new JTextField();
jtxtHour_Worked.setColumns(10);
jtxtHour_Worked.setBounds(243, 121, 109, 23);
group.add(jrdbuttonFullTime);
group.add(jrdbtnContract);
jrdbuttonFullTime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrdbuttonFullTime.isSelected()){
//jrdbtnContract.setSelected(false);
panel_1.add(jlblEmpSal);
panel_1.add(jtxtSal);
jlblEmpHour.setVisible(false);
jtxtHour_Pay.setVisible(false);
jtxtHour_Worked.setVisible(false);
jlblEmpWork.setVisible(false);
}
}
});
jrdbuttonFullTime.setBounds(113, 91, 109, 23);
panel_1.add(jrdbuttonFullTime);
jrdbtnContract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrdbtnContract.isSelected()){
//jrdbuttonFullTime.setSelected(false);
panel_1.add(jlblEmpHour);
panel_1.add(jtxtHour_Pay);
panel_1.add(jlblEmpWork);
panel_1.add(jtxtHour_Worked);
jlblEmpSal.setVisible(false);
jtxtSal.setVisible(false);
}
}
});
jrdbtnContract.setBounds(218, 91, 109, 23);
panel_1.add(jrdbtnContract);
}
}
Insteed of adding and removing components, simply add all and hide/show them on radiobox selection like this:
panel_1.add(jlblEmpSal);
panel_1.add(jtxtSal);
panel_1.add(jlblEmpHour);
panel_1.add(jtxtHour_Pay);
panel_1.add(jlblEmpWork);
panel_1.add(jtxtHour_Worked);
ActionListener myAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlblEmpHour.setVisible(jrdbtnContract.isSelected());
jtxtHour_Pay.setVisible(jrdbtnContract.isSelected());
jtxtHour_Worked.setVisible(jrdbtnContract.isSelected());
jlblEmpWork.setVisible(jrdbtnContract.isSelected());
jlblEmpSal.setVisible(jrdbuttonFullTime.isSelected());
jtxtSal.setVisible(jrdbuttonFullTime.isSelected());
}
};
myAction.actionPerformed(null); // to initialize labels first
jrdbuttonFullTime.addActionListener(myAction); // add actionlisteners
jrdbtnContract.addActionListener(myAction);// add actionlisteners
As you can see, you dont even need 2 separate action listeners as one but shared instance is just enough.
So the complete app will look like this:
public class Emp4 {
private JFrame frame;
private JTextField jtxtName;
private JTextField jtxtAge;
private JTextField jtxtSal;
private JTextField jtxtHour_Pay;
private JTextField jtxtHour_Worked;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Emp4 window = new Emp4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Emp4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(30, 11, 414, 36);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblEmployeeDatabase = new JLabel("Employee Database");
lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblEmployeeDatabase.setBounds(157, 7, 193, 25);
panel.add(lblEmployeeDatabase);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel_1.setBounds(10, 61, 464, 230);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel jlblEmpName = new JLabel("Employee Name");
jlblEmpName.setBounds(10, 11, 110, 14);
panel_1.add(jlblEmpName);
jtxtName = new JTextField();
jtxtName.setBounds(114, 8, 120, 20);
panel_1.add(jtxtName);
jtxtName.setColumns(10);
JLabel jlblEmpAge = new JLabel("Employee Age");
jlblEmpAge.setBounds(10, 52, 110, 14);
panel_1.add(jlblEmpAge);
jtxtAge = new JTextField();
jtxtAge.setColumns(10);
jtxtAge.setBounds(114, 49, 120, 20);
panel_1.add(jtxtAge);
JLabel jlblEmpType = new JLabel("Employee Type");
jlblEmpType.setBounds(10, 95, 110, 14);
panel_1.add(jlblEmpType);
JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
JRadioButton jrdbtnContract = new JRadioButton("Contract ");
JLabel jlblEmpHour = new JLabel("Hourly Rate");
jlblEmpHour.setBounds(5, 121, 66, 14);
ButtonGroup group = new ButtonGroup();
JLabel jlblEmpSal = new JLabel("Salary");
jlblEmpSal.setBounds(114, 121, 66, 14);
JLabel jlblEmpWork = new JLabel("Hours Worked");
jlblEmpWork.setBounds(150, 120, 86, 24);
jtxtSal = new JTextField();
jtxtSal.setColumns(10);
jtxtSal.setBounds(164, 121, 109, 23);
jtxtHour_Pay = new JTextField();
jtxtHour_Pay.setColumns(10);
jtxtHour_Pay.setBounds(75, 121, 59, 23);
jtxtHour_Worked = new JTextField();
jtxtHour_Worked.setColumns(10);
jtxtHour_Worked.setBounds(243, 121, 109, 23);
group.add(jrdbuttonFullTime);
group.add(jrdbtnContract);
panel_1.add(jlblEmpSal);
panel_1.add(jtxtSal);
panel_1.add(jlblEmpHour);
panel_1.add(jtxtHour_Pay);
panel_1.add(jlblEmpWork);
panel_1.add(jtxtHour_Worked);
ActionListener myAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlblEmpHour.setVisible(jrdbtnContract.isSelected());
jtxtHour_Pay.setVisible(jrdbtnContract.isSelected());
jtxtHour_Worked.setVisible(jrdbtnContract.isSelected());
jlblEmpWork.setVisible(jrdbtnContract.isSelected());
jlblEmpSal.setVisible(jrdbuttonFullTime.isSelected());
jtxtSal.setVisible(jrdbuttonFullTime.isSelected());
}
};
myAction.actionPerformed(null); // to initialize labels first
jrdbuttonFullTime.addActionListener(myAction);
jrdbtnContract.addActionListener(myAction);
jrdbtnContract.setBounds(218, 91, 109, 23);
jrdbuttonFullTime.setBounds(113, 91, 109, 23);
panel_1.add(jrdbuttonFullTime);
panel_1.add(jrdbtnContract);
}
}
I've revised your code a little. This should get you going on the right path:
public class Emp4 {
private JFrame frame;
private JTextField jtxtName;
private JTextField jtxtAge;
private JTextField jtxtSal;
private JTextField jtxtHour_Pay;
private JTextField jtxtHour_Worked;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
try {
Emp4 window = new Emp4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Emp4()
{
initialize();
}
private void initialize()
{
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(30, 11, 414, 36);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblEmployeeDatabase = new JLabel("Employee Database");
lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblEmployeeDatabase.setBounds(157, 7, 193, 25);
panel.add(lblEmployeeDatabase);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel_1.setBounds(10, 61, 464, 230);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel jlblEmpName = new JLabel("Employee Name");
jlblEmpName.setBounds(10, 11, 110, 14);
panel_1.add(jlblEmpName);
jtxtName = new JTextField();
jtxtName.setBounds(114, 8, 120, 20);
panel_1.add(jtxtName);
jtxtName.setColumns(10);
JLabel jlblEmpAge = new JLabel("Employee Age");
jlblEmpAge.setBounds(10, 52, 110, 14);
panel_1.add(jlblEmpAge);
jtxtAge = new JTextField();
jtxtAge.setColumns(10);
jtxtAge.setBounds(114, 49, 120, 20);
panel_1.add(jtxtAge);
JLabel jlblEmpType = new JLabel("Employee Type");
jlblEmpType.setBounds(10, 95, 110, 14);
panel_1.add(jlblEmpType);
JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
JRadioButton jrdbtnContract = new JRadioButton("Contract ");
JLabel jlblEmpHour = new JLabel("Hourly Rate");
jlblEmpHour.setBounds(5, 121, 66, 14);
ButtonGroup group = new ButtonGroup();
JLabel jlblEmpSal = new JLabel("Salary");
jlblEmpSal.setBounds(114, 121, 66, 14);
JLabel jlblEmpWork = new JLabel("Hours Worked");
jlblEmpWork.setBounds(150, 120, 86, 24);
jtxtSal = new JTextField();
jtxtSal.setColumns(10);
jtxtSal.setBounds(164, 121, 109, 23);
jtxtHour_Pay = new JTextField();
jtxtHour_Pay.setColumns(10);
jtxtHour_Pay.setBounds(75, 121, 59, 23);
jtxtHour_Worked = new JTextField();
jtxtHour_Worked.setColumns(10);
jtxtHour_Worked.setBounds(243, 121, 109, 23);
//*******************************************************************
// Add all your salary fields here, not in ActionListeners
// Start them off invisible
//*******************************************************************
jlblEmpSal.setVisible(false);
panel_1.add(jlblEmpSal);
jtxtSal.setVisible(false);
panel_1.add(jtxtSal);
panel_1.add(jlblEmpHour);
jlblEmpHour.setVisible(false);
panel_1.add(jtxtHour_Pay);
jtxtHour_Pay.setVisible(false);
panel_1.add(jlblEmpWork);
jlblEmpWork.setVisible(false);
jtxtHour_Worked.setVisible(false);
panel_1.add(jtxtHour_Worked);
group.add(jrdbuttonFullTime);
group.add(jrdbtnContract);
jrdbuttonFullTime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (jrdbuttonFullTime.isSelected()) {
//jrdbtnContract.setSelected(false);
// ****************************************************
// In ActionListeners for radiobuttons, hide the fields you
// don't want to see, make visible the ones you do want to see
// ****************************************************
jlblEmpSal.setVisible(true);
jtxtSal.setVisible(true);
jlblEmpHour.setVisible(false);
jtxtHour_Pay.setVisible(false);
jtxtHour_Worked.setVisible(false);
jlblEmpWork.setVisible(false);
}
}
});
jrdbuttonFullTime.setBounds(113, 91, 109, 23);
panel_1.add(jrdbuttonFullTime);
jrdbtnContract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (jrdbtnContract.isSelected()) {
//jrdbuttonFullTime.setSelected(false);
// ****************************************************
// In ActionListeners for radiobuttons, hide the fields you
// don't want to see, make visible the ones you do want to see
// ****************************************************
jlblEmpHour.setVisible(true);
jtxtHour_Pay.setVisible(true);
jlblEmpWork.setVisible(true);
jtxtHour_Worked.setVisible(true);
jlblEmpSal.setVisible(false);
jtxtSal.setVisible(false);
}
}
});
jrdbtnContract.setBounds(218, 91, 109, 23);
panel_1.add(jrdbtnContract);
}
}
Your radio buttons start off both unchecked, so you see no salary detail initially. When you click one or the other, the corresponding details appear.
In which case(which radiobutton checked ?) you want to show which controls?

how to save data to database from JCombobox and JTextarea in eclipse juno

I'm using eclipse Juno to write my code. I would like to input my data to database but when I click the save button I got error on JTextarea and JCombobox.
Here's the error:
Cannot refer to a non-final variable textALAMAT inside an inner class
defined in a different method Cannot refer to a non-final variable
cbJURUSAN inside an inner class defined in a different method
and here's my code:
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(35, 282, 475, 106);
contentPane.add(scrollPane);
tabelmodel = new DefaultTableModel(null,header);
tabel = new JTable();
tabel.setModel(tabelmodel);
scrollPane.setViewportView(tabel);
JLabel lblNim = new JLabel("NIM");
lblNim.setBounds(35, 24, 46, 14);
contentPane.add(lblNim);
JLabel lblNama = new JLabel("NAMA");
lblNama.setBounds(35, 59, 46, 14);
contentPane.add(lblNama);
JLabel lblJurusan = new JLabel("JURUSAN");
lblJurusan.setBounds(35, 97, 46, 14);
contentPane.add(lblJurusan);
JLabel lblAlamat = new JLabel("ALAMAT");
lblAlamat.setBounds(35, 138, 46, 14);
contentPane.add(lblAlamat);
textNIM = new JTextField();
textNIM.setBounds(119, 18, 230, 27);
contentPane.add(textNIM);
textNIM.setColumns(10);
textNAMA = new JTextField();
textNAMA.setColumns(10);
textNAMA.setBounds(119, 53, 230, 27);
contentPane.add(textNAMA);
JComboBox cbJURUSAN = new JComboBox();
cbJURUSAN.setModel(new DefaultComboBoxModel(new String[] {"Teknik Informatika", "Teknik Komputer", "Sistem Informasi", "Sastra Inggris"}));
cbJURUSAN.setBounds(118, 91, 231, 27);
contentPane.add(cbJURUSAN);
final JTextArea textALAMAT = new JTextArea();
textALAMAT.setBounds(119, 133, 354, 90);
contentPane.add(textALAMAT);
JButton btnSave = new JButton("SAVE");
btnSimpan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
String jurusan = "";
if(cbJURUSAN.getSelectedIndex() == 0)
{
jurusan = "Teknik Informatika";
}
else if(cbJURUSAN.getSelectedIndex() == 1)
{
jurusan = "Teknik Komputer";
}
else if(cbJURUSAN.getSelectedIndex() == 2)
{
jurusan = "Sistem Informasi";
}
else if(cbJURUSAN.getSelectedIndex() == 3)
{
jurusan = "Sastra Inggris";
}
try
{
Connection konek = koneksi.getKoneksi();
String query = "INSERT INTO mahasiswa VALUES (?,?,?,?)";
PreparedStatement prepare = konek.prepareStatement(query);
prepare.setInt(1,Integer.parseInt(textNIM.getText()));
prepare.setString(2, textNAMA.getText());
prepare.setString(3, jurusan);
prepare.setString(4, textALAMAT.getText());
prepare.executeUpdate();
JOptionPane.showMessageDialog(null,"Data berhasil ditambahkan ke database");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null,"Data gagal ditambahkan ke database");
System.out.println(ex);
}
finally
{
getDataTable();
}
}
});
btnSave.setBounds(49, 248, 89, 23);
contentPane.add(btnSimpan);
Can anybody help me to solve this?
The listener requieres you to change the variables textALAMAT, cbJURUSAN to final.
i see you've placed textALAMAT as final, but add it to the later too:
final JComboBox cbJURUSAN = new JComboBox();

JApplet issue stating class not found and class not found exception

I am having an issue that is giving me an error message and a blank applet is appearing. The error message says load:class Myapp.class not found and java.lang.ClassNotFoundException and then a list of lines saying # and then some other jargon.
If I run try to run the program as a Jcreator applet like I expected I get the prior stated error and if I run it in an application it just gives me the main method error.
Here is my program:
package MyPack;
import javax.swing.*;
import java.awt.event.*;
public class Myapp extends JApplet implements ItemListener{
JButton jbtnOne;
JButton jbtnTwo;
JLabel jlab;
JComboBox comboBox;
JComboBox comboBox_1;
JCheckBox chckbxPizza;
JCheckBox chckbxBurger;
JCheckBox chckbxSalad;
JLabel label_3;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
JTextArea txtrCommentsForSpecial;
JTextArea txtrCommentsForSpecial_2;
JTextArea txtrCommentsForSpecial_1;
JInternalFrame internalFrame;
public Myapp() {
}
public void init() {
setSize(700,640);
// setVisible(true);
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
guiInit(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}
// Called second, after init(). Also called
// whenever the applet is restarted.
public void start() {
// Not used by this applet.
}
// Called when the applet is stopped.
public void stop() {
// Not used by this applet.
}
// Called when applet is terminated. This is
// the last method executed.
public void destroy() {
// Not used by this applet.
}
// Setup and initialize the GUI.
private void guiInit() {
// Create two buttons and a label.
// setLayout(null);
String a[] = { "Chiken Tikka", "Fajita", "Vegetable"};
comboBox = new JComboBox(a);
comboBox.setBounds(115, 103, 100, 20);
comboBox.addItemListener(this);
getContentPane().add(comboBox);
String b[] = { "small", "medium","large","extra large"};
comboBox_1 = new JComboBox(b);
// comboBox_1.addItemListener(this);
// comboBox_1.setEnabled(false);
getContentPane().add(comboBox_1);
comboBox_1.setBounds(290, 103, 140, 20);
// setSize(300, 300);
getContentPane().setLayout(null);
JLabel lblSelectMenu = new JLabel("Select Menu");
lblSelectMenu.setForeground(new Color(72, 61, 139));
lblSelectMenu.setFont(new Font("Segoe Script", Font.BOLD, 16));
lblSelectMenu.setBounds(58, 10, 107, 34);
getContentPane().add(lblSelectMenu);
chckbxPizza = new JCheckBox("Pizza");
chckbxPizza.setBounds(37, 64, 97, 23);
getContentPane().add(chckbxPizza);
JLabel lblFlavour = new JLabel("flavour");
lblFlavour.setBounds(60, 103, 45, 20);
getContentPane().add(lblFlavour);
JLabel lblSize = new JLabel("size");
lblSize.setBounds(253, 103, 45, 20);
getContentPane().add(lblSize);
JLabel lblQty = new JLabel("Qty");
lblQty.setBounds(451, 103, 35, 20);
getContentPane().add(lblQty);
textField = new JTextField();
textField.setBounds(485, 103, 86, 20);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblComments = new JLabel("comments");
lblComments.setBounds(139, 154, 76, 20);
getContentPane().add(lblComments);
txtrCommentsForSpecial = new JTextArea();
txtrCommentsForSpecial.setForeground(new Color(220, 220, 220));
txtrCommentsForSpecial.setText("comments for special features");
txtrCommentsForSpecial.setBounds(210, 154, 268, 61);
getContentPane().add(txtrCommentsForSpecial);
chckbxBurger = new JCheckBox("Burger");
chckbxBurger.setBounds(37, 236, 97, 23);
getContentPane().add(chckbxBurger);
JLabel label = new JLabel("flavour");
label.setBounds(60, 286, 45, 20);
getContentPane().add(label);
String c[] = { "Fish", "Vegetable", "Chicken"};
JComboBox comboBox_2 = new JComboBox(c);
comboBox_2.setBounds(115, 286, 100, 20);
getContentPane().add(comboBox_2);
JLabel label_1 = new JLabel("size");
label_1.setBounds(253, 286, 45, 20);
getContentPane().add(label_1);
JComboBox comboBox_3 = new JComboBox(b);
comboBox_3.setBounds(290, 286, 110, 20);
getContentPane().add(comboBox_3);
JLabel label_2 = new JLabel("Qty");
label_2.setBounds(451, 286, 35, 20);
getContentPane().add(label_2);
textField_1 = new JTextField();
textField_1.setBounds(485, 286, 86, 20);
getContentPane().add(textField_1);
textField_1.setColumns(10);
label_3 = new JLabel("comments");
label_3.setBounds(139, 340, 76, 20);
getContentPane().add(label_3);
txtrCommentsForSpecial_1 = new JTextArea();
txtrCommentsForSpecial_1.setForeground(new Color(220, 220, 220));
txtrCommentsForSpecial_1.setText("comments for special features");
txtrCommentsForSpecial_1.setBounds(210, 340, 268, 61);
getContentPane().add(txtrCommentsForSpecial_1);
chckbxSalad = new JCheckBox("Soft Drink");
chckbxSalad.setBounds(37, 424, 97, 23);
getContentPane().add(chckbxSalad);
JLabel label_4 = new JLabel("flavour");
label_4.setBounds(60, 475, 45, 20);
getContentPane().add(label_4);
String f[] = { "Pepsi", "Coca Cola", "Sprite","7up"};
JComboBox comboBox_4 = new JComboBox(f);
comboBox_4.setBounds(115, 475, 86, 20);
getContentPane().add(comboBox_4);
JLabel label_5 = new JLabel("size");
label_5.setBounds(253, 475, 45, 20);
getContentPane().add(label_5);
JComboBox comboBox_5 = new JComboBox(b);
comboBox_5.setBounds(290, 475, 110, 20);
getContentPane().add(comboBox_5);
JLabel label_6 = new JLabel("Qty");
label_6.setBounds(451, 475, 35, 20);
getContentPane().add(label_6);
textField_2 = new JTextField();
textField_2.setBounds(485, 475, 86, 20);
getContentPane().add(textField_2);
textField_2.setColumns(10);
JLabel label_7 = new JLabel("comments");
label_7.setBounds(139, 546, 76, 20);
getContentPane().add(label_7);
txtrCommentsForSpecial_2 = new JTextArea();
txtrCommentsForSpecial_2.setForeground(new Color(220, 220, 220));
txtrCommentsForSpecial_2.setText("comments for special features");
txtrCommentsForSpecial_2.setBounds(210, 546, 268, 61);
getContentPane().add(txtrCommentsForSpecial_2);
JButton btnNewButton = new JButton("Ok");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
internalFrame = new JInternalFrame("Order Details");
internalFrame.setBounds(100, 80, 450, 300);
internalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
internalFrame.getContentPane().setLayout(null);
internalFrame.setVisible(true);
JTextArea textArea = new JTextArea();
textArea.setBounds(67, 52, 270, 149);
internalFrame.getContentPane().add(textArea);
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
internalFrame.setVisible(false);
}
});
btnOk.setBounds(164, 212, 89, 23);
internalFrame.getContentPane().add(btnOk);
JLabel lblOrderYouPlaced = new JLabel("Order You Placed");
lblOrderYouPlaced.setBounds(67, 26, 98, 14);
internalFrame.getContentPane().add(lblOrderYouPlaced);
getContentPane().add(internalFrame);
}
});
btnNewButton.setBounds(162, 616, 89, 23);
getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Reset");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField_1.setText("");
textField_2.setText("");
chckbxPizza.setText("");
chckbxBurger.setText("");
chckbxSalad.setText("");
txtrCommentsForSpecial.setText("");
txtrCommentsForSpecial_2.setText("");
txtrCommentsForSpecial_1.setText("");
}
});
btnNewButton_1.setBounds(279, 616, 89, 23);
getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Cancel");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnNewButton_2.setBounds(389, 616, 89, 23);
getContentPane().add(btnNewButton_2);
}
public void itemStateChanged(ItemEvent e) {
String b[] = { "Chikken Tikka", "Fajita" };
String c[] = { "Fish", "Vegetable", "Chicken"};
String d[] = { "Russian Salad", "Fruit Salad", "Beans Salad"};
String f[] = { "Pepsi", "Coca Cola", "Sprite","7up"};
if (e.getSource() == comboBox) {
if (comboBox.getSelectedItem().equals("Select")) {
comboBox_1.setEnabled(false);
} else if (comboBox.getSelectedItem().equals("Pizza")) {
comboBox_1.setEnabled(true);
comboBox_1.removeAllItems();
for (int i = 0; i < b.length; i++) {
comboBox_1.addItem(b[i]);
}
} else if (comboBox.getSelectedItem().equals("Burger")) {
comboBox_1.setEnabled(true);
comboBox_1.removeAllItems();
for (int i = 0; i < c.length; i++) {
comboBox_1.removeItem(c[i]);
comboBox_1.addItem(c[i]);
}
} else if (comboBox.getSelectedItem().equals("Salad")) {
comboBox_1.setEnabled(true);
comboBox_1.removeAllItems();
for (int i = 0; i < d.length; i++) {
comboBox_1.addItem(d[i]);
}
}else if (comboBox.getSelectedItem().equals("Soft Drink")) {
comboBox_1.setEnabled(true);
comboBox_1.removeAllItems();
for (int i = 0; i < f.length; i++) {
comboBox_1.addItem(f[i]);
}
}
}
}
}
Write the itemListener with a captial letter like this
public class Myapp extends JApplet implements ItemListener{
and import all this packages:
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

Categories

Resources