Button's ActionPerformed not working from another class - java

I have two classes, a GUI and a Customer class. The GUI builds the frame and button, and the Customer class gets the info from a database server. I have the ActionPerformed in the Customer class, but it doesn't appear to be noticing when I click the button. Any help is extremely appreciated!
GUI Class:
class GUI {
private static JFrame frame;
public static JTextField textField;
public static JButton btnGetInfo = new JButton("Get Info");
public static JTextArea textArea = new JTextArea();
public static void main (String args [])
throws SQLException {
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
GUI window = new GUI();
frame = new JFrame();
frame.setBounds(100, 100, 630, 470);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setBounds(10, 179, 594, 241);
frame.getContentPane().add(textArea);
textField = new JTextField();
textField.setBounds(255, 69, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnClearScreen = new JButton("Clear Screen");
btnClearScreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.setText("");
}
});
btnClearScreen.setBounds(492, 11, 112, 23);
frame.getContentPane().add(btnClearScreen);
JLabel lblEnterCustomerId = new JLabel("Enter Customer ID (1-6)");
lblEnterCustomerId.setBounds(240, 43, 153, 14);
frame.getContentPane().add(lblEnterCustomerId);
btnGetInfo.setBounds(255, 115, 89, 23);
frame.getContentPane().add(btnGetInfo);
window.frame.setVisible(true);
}
}
Customer Class:
public class Customer implements ActionListener {
public static void getInfoButton() {
GUI.btnGetInfo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("TEST");
String getCustID = GUI.textField.getText();
String query = ("select * from customers where CUSTID =" + getCustID);
final String user, pass;
user = "asdf";
pass = "asdf";
try{
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:#asdf",user,pass);
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery (query);
while (rset.next ())
{
GUI.textArea.append((rset.getString("CUSTID") + " - " + rset.getString("CUSTSSN")
+ " - " + rset.getString("LNAME") + " - " + rset.getString("FNAME") + " - " +
rset.getString("STREET") + " - " + rset.getString("CITY") + " - " + rset.getString("STATE") +
" - " + rset.getString("ZIP") + " - " + rset.getString("PHONE") + System.getProperty("line.separator")
+ System.getProperty("line.separator")));
}
}
catch (SQLException e)
{
System.out.println ("Could not load the db"+e);
}
}});
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

public static JButton btnGetInfo = new JButton("Get Info");
You should add the actionlistener to this
btnGetInfo.addActionListener(new Customer());
Your Customer should just look like this
public class Customer implements ActionListener {
// delete the uneccessary
#Override
public void actionPerformed(ActionEvent arg0) {
...
}
}
Unnecessary code
public static void getInfoButton() {
GUI.btnGetInfo.addActionListener(new ActionListener() {

Related

how to dedug in eclipse and solve Unknown Source erros

/*this is my java code which when i compile they don not show exactly error */
public class Login {
public JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conections;
private JTextField textField;
private JPasswordField passwordField;
public Login() {
initialize();
conections = SqliteConnectio.dbConnection();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 581, 411);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(266, 112, 193, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnLOGIN = new JButton("LOGIN");
Image jn=new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLOGIN.setIcon(new ImageIcon(jn));
btnLOGIN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select *from customer.sqlite where username=? and password=? ";
PreparedStatement pre = conections.prepareStatement(query);
pre.setString(1, textField.getText());
pre.setString(2, passwordField.getText());
ResultSet res = pre.executeQuery();
int count = 0;
while (res.next()) {
count++;
}
if (count == 1) {
JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
} else if (count > 1) {JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
}
else {
JOptionPane.showInternalMessageDialog(null, "username and password has been failed to be entered");
}
res.close();
pre.close();
} catch (Exception e) {
JOptionPane.showInternalMessageDialog(null, "you have failed to asses the database");
}
}
});
btnLOGIN.setBounds(321, 256, 125, 36);
frame.getContentPane().add(btnLOGIN);
JLabel userNAME = new JLabel("USERNAME");
userNAME.setBounds(156, 127, 85, 14);
frame.getContentPane().add(userNAME);
JLabel passLABEL = new JLabel("PASSWORD");
passLABEL.setBounds(156, 191, 85, 14);
frame.getContentPane().add(passLABEL);
passwordField = new JPasswordField();
passwordField.setBounds(266, 188, 193, 20);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("New label");
Image im=new ImageIcon(this.getClass().getResource("/login.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(im));
lblNewLabel.setBounds(10, 21, 136, 205);
frame.getContentPane().add(lblNewLabel);
}
}
//this is my connection to database which it seems to work just fine by prompting "username and password has sucseeful inserted"
package mi;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SqliteConnectio {
Connection conect=null;
public static Connection dbConnection(){
try {
Class.forName("org.sqlite.JDBC");
Connection conect=DriverManager.getConnection(
"jdbc:sqlite:E:\\JAVA WORLD\\sgliteDatabase\\customer.sqlite");
JOptionPane.showMessageDialog(null, "sucessful login to database");
return conect;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, "failed to login in database");
return null;
}
}
}

script inside windowbuilder (Eclipse, Java)

So i just started with eclipse and java script and i am also a new coder. I started of wtih this random name picker project. And the code is written like this:
public static void gods() {
System.out.println("You have to play this God:");
String[] gods =
{"Agni",
"Ah Muzen Cab",
"Ah Puch",
"Amaterasu",
"Anhur",
"Anubis",
"Ao Kuang",
"Aphrodite",
"Apollo",
"Arachne",
"Ares",
"Artemis",
"Athena",
"Awilix",
"Bacchus",
"Bakasura",
"Bastet",
"Bellona",
"Cabrakan",
"Chaac",
"Change",
"Chiron",
"Chronos",
"Cupid",
"Fenrir",
"Geb",
"Guan Yu",
"Hades",
"He Bo",
"Hel",
"Hercules",
"Hou Yi",
"Hun Batz",
"Isis",
"Janus",
"Kali",
"Khepri",
"Kukulkan",
"Kumbhakarna",
"Loki",
"Medusa",
"Mercury",
"Ne Zha",
"Neith",
"Nemesis",
"Nox",
"Nu Wa",
"Odin",
"Osiris",
"Poseidon",
"Ra",
"Rama",
"Ratatoskr",
"Ravana",
"Scylla",
"Serqet",
"Sobek",
"Sol",
"Sun Wukong",
"Sylvanus",
"Thanatos",
"Thor",
"Tyr",
"Ullr",
"Vamana",
"Vulcan",
"Xbalanque",
"Xing Tian",
"Ymir",
"Zeus",
"Zhong Kui"};
List<String> names = Arrays.asList(gods);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");
}
public static void roles() {
String[] roles = {" Solo", " Jungle", " Mid", " ADC", " Support"};
List<String> names = Arrays.asList(roles);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");}
public void Randomize() {
System.out.println("Here you have your god:");
gods();
System.out.println("Here you have your role:");
roles();}
But i want to import or set in this code inside my windowbuilder plugin. I have tried inserting it inside a JButton as an "actionPerformed" but when i launched the program and clicked the button it opened up the console in eclipse when i want it to open inside the program.
This is my windowbuilder code:
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Plswork window = new Plswork();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Plswork() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Comic Sans MS", Font.PLAIN, 18));
frame.getContentPane().setBackground(Color.MAGENTA);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtAronErDu = new JTextField();
txtAronErDu.setFont(new Font("SWTOR Trajan", Font.PLAIN, 22));
txtAronErDu.setText("Aron er du homofil?");
txtAronErDu.setBounds(0, 0, 434, 39);
frame.getContentPane().add(txtAronErDu);
txtAronErDu.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(199, 118, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public void actionPerformed(ActionEvent e) {
}
}
PS: This is how it looks when i imoprt it:
public class Plswork {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Plswork window = new Plswork();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Comic Sans MS", Font.PLAIN, 18));
frame.getContentPane().setBackground(Color.MAGENTA);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Sebbe");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You have to play this God:");
String[] gods =
{"Agni",
"Ah Muzen Cab",
"Ah Puch",
"Amaterasu",
"Anhur",
"Anubis",
"Ao Kuang",
"Aphrodite",
"Apollo",
"Arachne",
"Ares",
"Artemis",
"Athena",
"Awilix",
"Bacchus",
"Bakasura",
"Bastet",
"Bellona",
"Cabrakan",
"Chaac",
"Change",
"Chiron",
"Chronos",
"Cupid",
"Fenrir",
"Geb",
"Guan Yu",
"Hades",
"He Bo",
"Hel",
"Hercules",
"Hou Yi",
"Hun Batz",
"Isis",
"Janus",
"Kali",
"Khepri",
"Kukulkan",
"Kumbhakarna",
"Loki",
"Medusa",
"Mercury",
"Ne Zha",
"Neith",
"Nemesis",
"Nox",
"Nu Wa",
"Odin",
"Osiris",
"Poseidon",
"Ra",
"Rama",
"Ratatoskr",
"Ravana",
"Scylla",
"Serqet",
"Sobek",
"Sol",
"Sun Wukong",
"Sylvanus",
"Thanatos",
"Thor",
"Tyr",
"Ullr",
"Vamana",
"Vulcan",
"Xbalanque",
"Xing Tian",
"Ymir",
"Zeus",
"Zhong Kui"};
List<String> names = Arrays.asList(gods);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");
}
});
btnNewButton.setBounds(167, 117, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public void actionPerformed(ActionEvent e) {
}
}

java : sort and delete or refresh data make exception in jtable

please excute this code with java, and then..
button pattern1 -> button pattern2 -> table sort with any columns. ->
button delete -> exception.
Why exception occured?
here's code.
please help me..
===============================================
public class Test extends JFrame {
private DefaultTableModel modelTest = new DefaultTableModel();
private JTable tableTest = new JTable(modelTest);
private JScrollPane paneTest = new JScrollPane(tableTest);
private JButton button1 = new JButton("pattern1");
private JButton button2 = new JButton("pattern2");
private JButton button3 = new JButton("delete");
private void compInit() {
paneTest.setBounds(0, 0, 778, 300);
button1.setBounds(250, 320, 80, 20);
button2.setBounds(450, 320, 80, 20);
button3.setBounds(300, 400, 80, 20);
DefaultTableModel tmp = modelTest;
tmp.addColumn(" ");
tmp.addColumn("col1");
tmp.addColumn("col2");
tmp.addColumn("col3");
tmp.addColumn("col4");
tmp.addColumn("col5");
tmp.addColumn("col6");
tmp.addColumn("col7");
try {
tableTest.setDefaultRenderer(Class.forName("java.lang.String"), new DefaultTableCellRenderer());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
tableTest.setAutoCreateRowSorter(true);
tableTest.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableTest.getColumnModel().getColumn(0).setPreferredWidth(20);
tableTest.getColumnModel().getColumn(1).setPreferredWidth(45);
tableTest.getColumnModel().getColumn(2).setPreferredWidth(110);
tableTest.getColumnModel().getColumn(3).setPreferredWidth(60);
tableTest.getColumnModel().getColumn(4).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(5).setPreferredWidth(227);
tableTest.getColumnModel().getColumn(6).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(7).setPreferredWidth(100);
tableTest.getTableHeader().setForeground(new Color(105, 105, 105));
this.add(button1);
this.add(button2);
this.add(button3);
this.add(paneTest);
}
private void pattern1() {
for (int i = 0; i < 10; i++) {
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i + 1);
rowData.add("a : " + i);
rowData.add("b : " + i);
rowData.add("c : " + i);
rowData.add("d : " + i);
rowData.add("e : " + i);
rowData.add("f : " + i);
modelTest.addRow(rowData);
}
}
private void pattern2() {
for (int i = 0; i < 10; i++) {
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i + 1);
rowData.add("z : " + i);
rowData.add("y : " + i);
rowData.add("x : " + i);
rowData.add("w : " + i);
rowData.add("v : " + i);
rowData.add("u : " + i);
modelTest.addRow(rowData);
}
}
private void delete() {
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
private void eventInit() {
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pattern1();
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pattern2();
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delete();
}
});
}
public Test() {
this.setLayout(null);
this.compInit();
this.eventInit();
this.setSize(778, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] ar) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}
You have a problem in delete() method. JTable is designed using MVC pattern, so after removing all rows in Model, you should notify View about that. So correct version of delete() method will be:
private void delete() {
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
modelTest.fireTableDataChanged();
}
To delele the rows you should go through the model's method:
instead of
tmp.getDataVector().removeAllElements();
do it like this:
while (modelTest.getRowCount() > 0){
modelTest.removeRow(0);
}

Why doesn't the JButtons appear until i change the dimensions of my Screen;

When I run my program the JButtons don't appear until i change the size of the screen(setResizable = true;).
here is my code:
public class MainMenu extends JPanel {
Kingdomcraft kd;
Screen screen;
JButton playSP;
JButton playMP;
JButton settings;
JButton fullscreen;
JButton quit;
JButton createWorld;
JButton addServer;
JSlider sound;
JSlider light;
JList worldList;
JList serverList;
JTextField worldName;
JTextField serverName;
JTextField serverIP;
JButton addNewWorld;
JButton addNewServer;
private Preferences prefs;
private int soundLevel;
private int lightLevel;
public static boolean isFullscreen = false;
public static boolean serverNameFilled = false;
public static boolean serverIPFilled = false;
public void run() {
kd = new Kingdomcraft();
screen = new Screen();
playSP = new JButton("Singleplayer");
playMP = new JButton("Multiplayer");
settings = new JButton("Settings");
fullscreen = new JButton("Fullscreen");
quit = new JButton("Quit");
createWorld = new JButton("Create World");
addServer = new JButton("Add Server");
sound = new JSlider();
light = new JSlider();
prefs = Preferences.userNodeForPackage(MainMenu.class);
soundLevel = prefs.getInt("SOUND_LEVEL", 50);
lightLevel = prefs.getInt("LIGHT_LEVEL", 100);
worldList = new JList();
serverList = new JList();
worldName = new JTextField();
serverName = new JTextField();
serverIP = new JTextField();
addNewWorld = new JButton("Add");
addNewServer = new JButton("Add");
this.setBackground(Color.BLACK);
if (kd.inMainMenu) {
add(playSP);
playSP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove(sound);
remove(light);
remove(fullscreen);
remove(addServer);
remove(serverName);
remove(serverIP);
remove(addNewServer);
repaint();
add(createWorld);
createWorld.setSize(110, 25);
createWorld.setLocation(playSP.getX() - (playSP.getWidth() / 2) - 5, playSP.getY() + 35);
createWorld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(worldName);
worldName.setSize(110, 25);
worldName.setLocation(createWorld.getX(), createWorld.getY() + 35);
worldName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(addNewWorld);
addNewWorld.setSize(110, 25);
addNewWorld.setLocation(worldName.getX(), worldName.getY() + 35);
}
});
}
});
}
});
add(playMP);
playMP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove(sound);
remove(light);
remove(fullscreen);
remove(createWorld);
remove(worldName);
remove(addNewWorld);
repaint();
add(addServer);
addServer.setSize(100, 25);
addServer.setLocation(playMP.getX() - (playMP.getWidth() / 2) - 5, playMP.getY() + 35);
addServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(serverName);
serverName.setSize(100, 25);
serverName.setLocation(addServer.getX(), addServer.getY() + 35);
serverName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu.serverNameFilled = true;
}
});
add(serverIP);
serverIP.setSize(100, 25);
serverIP.setLocation(serverName.getX(), serverName.getY() + 35);
serverIP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu.serverIPFilled = true;
}
});
if (serverNameFilled && serverIPFilled) {
add(addNewServer);
addNewServer.setSize(100, 25);
addNewServer.setLocation(serverIP.getX(), serverIP.getY() + 35);
addNewServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}
});
}
});
add(settings);
settings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove(createWorld);
remove(addServer);
remove(worldName);
remove(serverName);
remove(serverIP);
remove(addNewWorld);
remove(addNewServer);
repaint();
add(sound);
sound.setSize(settings.getWidth(), settings.getHeight());
sound.setLocation(settings.getX() + (settings.getWidth() / 2) + 5, settings.getY() + 35);
sound.setOpaque(false);
sound.setMinimum(0);
sound.setMaximum(100);
sound.setValueIsAdjusting(true);
sound.setValue(soundLevel);
sound.setToolTipText("Audio: " + soundLevel + "%");
sound.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
soundLevel = sound.getValue();
sound.setToolTipText("Audio: " + soundLevel + "%");
prefs.putInt("SOUND_LEVEL", soundLevel);
}
});
add(light);
light.setSize(settings.getWidth(), settings.getHeight());
light.setLocation(sound.getX(), sound.getY() + 35);
light.setOpaque(false);
light.setMinimum(50);
light.setMaximum(150);
light.setValueIsAdjusting(true);
light.setValue(lightLevel);
light.setToolTipText("Brightness: " + lightLevel + "%");
light.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
lightLevel = light.getValue();
light.setToolTipText("Brightness: " + lightLevel + "%");
prefs.putInt("LIGHT_LEVEL", lightLevel);
}
});
add(fullscreen);
fullscreen.setSize(100, settings.getHeight());
fullscreen.setLocation(settings.getX() + (settings.getWidth() / 2) - 50, light.getY() + 35);
fullscreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu.isFullscreen = true;
}
});
}
});
add(quit);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(ABORT);
}
});
}
}
}
I understand that this is a lot of code to skim through but I'm just plain stumped.
When you add a UI component in swing, you need to call the component's revalidate method for the changes to take effect.
Can't tell exactly what you are doing but I'm not sure you should be continually removing/adding individual components.
Maybe you should be use a Card Layout which will allow to you remove/add panels based on the specific function the user requests.

Change Title of JFrame in my program

I am having trouble with one part of my code. I have been working for so long on this and I am exhausted and missing something easy. I need to have a text box to enter a new title for the JFrame, a button that says "Set New Name" and an "Exit Button.
Can someone look at this code and give me some info so I can go to bed.
Thank you
//Good One
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Pool {
public static void main(String[] args) {
new poolCalc();
}
}
class poolCalc extends JFrame {
private static final long serialVersionUID = 1L;
public static final double MILLIMETER = 1;
public static final double METER = 1000 * MILLIMETER;
public static final double INCH = 25.4 * MILLIMETER;
public static final double FOOT = 304.8 * MILLIMETER;
public static final double YARD = 914.4 * MILLIMETER;
private static final DecimalFormat df = new DecimalFormat("#,##0.###");
private JTabbedPane tabs;
private JPanel generalPanel;
private JPanel optionsPanel;
private JPanel customerPanel;
private JPanel contractorPanel;
private JPanel poolPanel;
private JPanel hotTubPanel;
private JPanel tempCalPanel;
private JPanel lengthCalPanel;
public poolCalc() {
super("The Pool Calculator");
setSize(340, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
initializeComponents();
setLocationRelativeTo(null);
setVisible(true);
}
private void initializeComponents() {
Container pane = getContentPane();
tabs = new JTabbedPane();
generalTab();
optionsTab();
customerTab();
contractorTab();
poolsTab();
hotTubsTab();
tempCalTab();
lengthCalTab();
tabs.add("General", generalPanel);
tabs.add("Options", optionsPanel);
tabs.add("Customers", customerPanel);
tabs.add("Contractors", contractorPanel);
tabs.add("Pools", poolPanel);
tabs.add("Hot Tubs", hotTubPanel);
tabs.add("Temp Calc", tempCalPanel);
tabs.add("Length Calc", lengthCalPanel);
pane.add(tabs);
}
private JButton createExitButton() {
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic('x');
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return exitButton;
}
private void generalTab() {
generalPanel = new JPanel(new FlowLayout());
String currentTime = SimpleDateFormat.getInstance().format(
Calendar.getInstance().getTime());
generalPanel.add(new JLabel("Today's Date: " + currentTime));
generalPanel.add(createExitButton());
}
private JTextField createTitleField(String text, int length) {
JTextField tf = new JTextField(length);
tf.setEditable(false);
tf.setFocusable(false);
tf.setText(text);
return tf;
}
// FIX
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
private void customerTab() {
customerPanel = createContactPanel("Customer", "customer.txt");
}
private void contractorTab() {
contractorPanel = createContactPanel("Contractor", "contractor.txt");
}
private void poolsTab() {
poolPanel = new JPanel(new FlowLayout());
final JRadioButton roundPool = new JRadioButton("Round Pool");
final JRadioButton ovalPool = new JRadioButton("Oval Pool");
final JRadioButton rectangularPool = new JRadioButton("Rectangle Pool");
roundPool.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundPool);
group.add(rectangularPool);
poolPanel.add(roundPool);
poolPanel.add(rectangularPool);
poolPanel.add(new JLabel("Enter the pool's length (ft): "));
final JTextField lengthField = new JTextField(10);
poolPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the pool's width (ft): ");
widthLabel.setEnabled(false);
poolPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
poolPanel.add(widthField);
poolPanel.add(new JLabel("Enter the pool's depth (ft): "));
final JTextField depthField = new JTextField(10);
poolPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
poolPanel.add(calculateVolume);
poolPanel.add(createExitButton());
poolPanel.add(new JLabel("The pool's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
poolPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(2, 20, "");
poolPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundPool.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundPool.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
}
if (rectangularPool.isSelected()) {
volume = length * width * depth * 5.9;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener poolsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundPool) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == rectangularPool) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundPool.addActionListener(poolsListener);
ovalPool.addActionListener(poolsListener);
rectangularPool.addActionListener(poolsListener);
}
private void hotTubsTab() {
hotTubPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubPanel.add(roundTub);
hotTubPanel.add(ovalTub);
hotTubPanel.add(new JLabel("Enter the tub's length (ft): "));
final JTextField lengthField = new JTextField(10);
hotTubPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
widthLabel.setEnabled(false);
hotTubPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubPanel.add(widthField);
hotTubPanel.add(new JLabel("Enter the tub's depth (ft): "));
final JTextField depthField = new JTextField(10);
hotTubPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubPanel.add(calculateVolume);
hotTubPanel.add(createExitButton());
hotTubPanel.add(new JLabel("The tub's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"Width will be set to the same value as length");
hotTubPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0,2) * depth;
}
if (ovalTub.isSelected()) {
volume = Math.PI * ((length * width)*2) * depth;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);}
private void tempCalTab() {
tempCalPanel = new JPanel(new FlowLayout());
tempCalPanel.add(new JLabel("Enter temperature: "));
final JTextField temperatureField = new JTextField(10);
tempCalPanel.add(temperatureField);
final JComboBox optionComboBox = new JComboBox(
new String[] { "C", "F" });
tempCalPanel.add(optionComboBox);
tempCalPanel.add(new JLabel("Result: "));
final JTextField resultField = new JTextField(18);
resultField.setEditable(false);
tempCalPanel.add(resultField);
final JLabel oppositeLabel = new JLabel("F");
tempCalPanel.add(oppositeLabel);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
tempCalPanel.add(convertButton);
tempCalPanel.add(createExitButton());
final JTextArea messageArea = createMessageArea(1, 20,
"System Messages");
tempCalPanel.add(messageArea);
optionComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if ("F".equals(e.getItem())) {
oppositeLabel.setText("C");}
else {
oppositeLabel.setText("F");}}}
});
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidationResult result = validateFields(new JTextField[] { temperatureField });
String errors = "";
if (result.filled != 1 || result.valid != 1) {
errors += "Value set to zero";}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
temperatureField.setText("0");}
else {
messageArea.setVisible(false);}
double temperature = Double.parseDouble(temperatureField
.getText());
double resultValue = 0;
if (oppositeLabel.getText().equals("C")) {
resultValue = (temperature - 32.0) / 9.0 * 5.0;}
else if (oppositeLabel.getText().equals("F")) {
resultValue = ((temperature * 9.0) / 5.0) + 32.0;}
resultField.setText(df.format(resultValue));}
});
}
private void lengthCalTab() {
lengthCalPanel = new JPanel(new FlowLayout());
lengthCalPanel.add(createTitleField("Millimeters", 6));
lengthCalPanel.add(createTitleField("Meters", 4));
lengthCalPanel.add(createTitleField("Yards", 4));
lengthCalPanel.add(createTitleField("Feet", 3));
lengthCalPanel.add(createTitleField("Inches", 6));
final JTextField millimetersField = new JTextField(6);
final JTextField metersField = new JTextField(4);
final JTextField yardsField = new JTextField(4);
final JTextField feetField = new JTextField(3);
final JTextField inchesField = new JTextField(6);
lengthCalPanel.add(millimetersField);
lengthCalPanel.add(metersField);
lengthCalPanel.add(yardsField);
lengthCalPanel.add(feetField);
lengthCalPanel.add(inchesField);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double millimeters = convertToDouble(millimetersField.getText());
double meters = convertToDouble(metersField.getText());
double yards = convertToDouble(yardsField.getText());
double feet = convertToDouble(feetField.getText());
double inches = convertToDouble(inchesField.getText());
double value = 0;
if (millimeters != 0) {
value = millimeters * MILLIMETER;}
else if (meters != 0) {
value = meters * METER;}
else if (yards != 0) {
value = yards * YARD;}
else if (feet != 0) {
value = feet * FOOT;}
else if (inches != 0) {
value = inches * INCH;}
millimeters = value / MILLIMETER;
meters = value / METER;
yards = value / YARD;
feet = value / FOOT;
inches = value / INCH;
millimetersField.setText(df.format(millimeters));
metersField.setText(df.format(meters));
yardsField.setText(df.format(yards));
feetField.setText(df.format(feet));
inchesField.setText(df.format(inches));}
private double convertToDouble(String s) {
try {
return Double.parseDouble(s);}
catch (Exception e) {
return 0;}}
});
JButton clearButton = new JButton("Clear");
clearButton.setMnemonic('l');
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
millimetersField.setText(null);
metersField.setText(null);
yardsField.setText(null);
feetField.setText(null);
inchesField.setText(null);}
});
lengthCalPanel.add(convertButton);
lengthCalPanel.add(clearButton);
lengthCalPanel.add(createExitButton());}
private String loadDataFromFile(String fileName) {
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
data += reader.readLine() + "\n";}
reader.close();}
catch (IOException e){
}
return data;}
private JPanel createContactPanel(final String contactName,
final String fileName) {
JPanel pane = new JPanel(new FlowLayout());
final JTextArea customerDisplay = new JTextArea(8, 25);
customerDisplay.setLineWrap(true);
customerDisplay.setEditable(false);
pane.add(new JScrollPane(customerDisplay));
pane.add(createExitButton());
JButton addCustomerButton = new JButton("Add " + contactName);
addCustomerButton.setMnemonic('A');
pane.add(addCustomerButton);
JButton refreshButton = new JButton("Refresh");
refreshButton.setMnemonic('R');
pane.add(refreshButton);
final JTextArea messageArea = createMessageArea(2, 25, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
addCustomerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new EditContact(contactName, fileName);}
});
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = loadDataFromFile(fileName);
if (data != "") {
customerDisplay.setText(data);
customerDisplay.setEnabled(true);
messageArea.setText("File " + fileName
+ " can be read from!");
}
else {
customerDisplay.setText("Click Add "
+ contactName
+ " button to add "
+ contactName.toLowerCase()
+ ". And click Refresh button to update this pane.");
customerDisplay.setEnabled(false);
messageArea.setText("File " + fileName + " is not "
+ "there yet! It will be created "
+ "when you add " + contactName.toLowerCase()
+ "s!");
}
}
});
refreshButton.doClick();
return pane;
}
private JTextArea createMessageArea(int rows, int cols, String text) {
final JTextArea messageArea = new JTextArea(rows, cols);
messageArea.setBorder(BorderFactory.createEmptyBorder());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font("System", Font.PLAIN, 12));
messageArea.setText(text);
messageArea.setBackground(null);
messageArea.setForeground(Color.GRAY);
messageArea.setEnabled(true);
messageArea.setFocusable(false);
return messageArea;
}
private class ValidationResult {
int filled;
int valid;
}
private ValidationResult validateFields(JTextField[] fields) {
ValidationResult result = new ValidationResult();
for (int i = 0; i < fields.length; i++) {
JTextField field = fields[i];
if ((field.getText() != null) && (field.getText().length() > 0)) {
result.filled++;
}
try {
Double.parseDouble(field.getText());
field.setBackground(Color.white);
result.valid++;
}
catch (Exception e) {
field.setBackground(Color.orange);
}
}
return result;
}
private class EditContact extends JDialog {
private static final long serialVersionUID = 1L;
private final String contactName;
private final String fileName;
private File file;
private JTextField nameField;
private JTextField addressField;
private JTextField cityField;
private JComboBox stateComboBox;
private JTextField zipField;
private JTextField phoneField;
private JTextArea messageArea;
public EditContact(String contactName, String fileName) {
super(poolCalc.this, contactName + "s");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(418, 300);
this.contactName = contactName;
this.fileName = fileName;
initializeComponents();
if (openFile()) {
displayMessage(null);
}
else {
displayMessage("File " + fileName + " does not exist yet! "
+ "Will be created when you add a "
+ contactName.toLowerCase() + "!");
}
setLocationRelativeTo(null);
setVisible(true);
}
private void displayMessage(String message) {
if (message != null) {
messageArea.setVisible(true);
messageArea.setText(message);
}
else {
messageArea.setVisible(false);
}
}
private boolean openFile() {
file = new File(fileName);
return file.exists();
}
private boolean deleteFile() {
return file.exists() && file.delete();
}
private boolean saveToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,
true));
writer.write("Name: " + nameField.getText() + "\n");
writer.write("Address: " + addressField.getText() + "\n");
writer.write("City: " + cityField.getText() + "\n");
writer.write("State: "
+ stateComboBox.getSelectedItem().toString() + "\n");
writer.write("ZIP: " + zipField.getText() + "\n");
writer.write("Phone: " + phoneField.getText() + "\n");
writer.write("\n");
writer.close();
return true;
}
catch (IOException e) {
return false;
}
}
private void initializeComponents() {
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.add(new JLabel(contactName + " Name "));
nameField = new JTextField(25);
pane.add(nameField);
pane.add(new JLabel("Address "));
addressField = new JTextField(28);
pane.add(addressField);
pane.add(new JLabel("City "));
cityField = new JTextField(32);
pane.add(cityField);
pane.add(new JLabel("State "));
stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
pane.add(stateComboBox);
pane.add(new JLabel("ZIP "));
zipField = new JTextField(5);
pane.add(zipField);
pane.add(new JLabel("Phone "));
phoneField = new JTextField(10);
pane.add(phoneField);
JButton addContactButton = new JButton("Add " + this.contactName);
addContactButton.setMnemonic('A');
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveToFile()) {
displayMessage(contactName + " added");
}
else {
displayMessage("File saving error!");
}
}
});
pane.add(addContactButton);
JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
pane.add(closeButton);
JButton deleteFileButton = new JButton("Delete File");
deleteFileButton.setMnemonic('D');
deleteFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (deleteFile()) {
displayMessage("File " + fileName + " deleted!");
}
}
});
pane.add(deleteFileButton);
messageArea = createMessageArea(2, 30, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
}
}
}
Let's start with this (which I assume is where you create the details)...
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
The newTitle field is a local variable, so once the method exists, you will not be able to access the field (easily)...
You seem to have tried adding a actionListener to the newName button, which isn't a bad idea, but because you can't actually access the newTitle field, isn't going to help...
The use of setBounds is not only ill advised, but probably won't result in the results you are expecting, because the optionsPane is under the control a layout manager...
And while I was digging around, I noticed this if (errors != "") {...This is not how String comparison is done in Java. This is comparing the memory references of both Strings which will never be true, instead you should if (!"".equals(errors)) {...
But back to the problem at hand...
You are really close to having a solution. You could make the newTitle field a class instance variable, which would allow you to access the field within other parts of your program, but because you've made it final, there's something else you can try...
You can use an anonymous inner class instead...
newName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
Which should get a good nights sleep :D
It is a little unclear what you want, but if I understand you right you want the JButton newName to set the title of the JFrame to the text in some textbox?
In that case you would write
setTitle(someTextbox.getText());
inside the function of the button.
First, you need to create a JTextField that has public access. Then, create a JButton that implements ActionListener. After that you must implement the abstract method actionPerformed() in the JButton Subclass. Then in the run method say JFrame.setTitle(JTextfield.getText()).
Subclass Method:
public class main extends JFrame{
// Construct and setVisible()
}
class textfield extends JTextField{
// create field then add to JFrame
}
class button extends JButton implements ActionListener{
// create button
public void actionPerformed(ActionEvent e){
main.setTitle(textfield.getText());
}
Instance Method:
public class main implements ActionListener{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField();
JButton button = new JButtone();
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
public void actionPerformed(ActionEvent e){
frame.setTitle(field.getText);
}
}
Try This
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
// optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
// newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}

Categories