I am trying to pass values from my database java file to my frame java file.BY creating a function like "frame java . get value (name ,phone, date ) " and receiving the value in the frame java file . I tried to print the passed value in the console it works fine, but when i try to set value to the text field it doesn't display the text in the text filed... I don't what's wrong can any one help me to sort out this issue.
Here is database java function
public void check_room(String roomno, String date) throws SQLException {
String sql = "select * from customerinfo where roomno='" + roomno
+ "'and cdate='" + date + "' ";
System.out.print("search method called \n ");
System.out.print("\n ");
try {
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "hotel", "hotel");
} catch (SQLException ex) {
// Logger.getLogger(checkout.class.getName()).log(Level.SEVERE,
// null, ex);
}
sate = con.createStatement();
rs = sate.executeQuery(sql);
int tmp = 0;
try {
while (rs.next()) {
System.out.print("search found \n ");
String name = rs.getString("GUEST_NAME");
String phono = rs.getString("GUEST_PHO");
String addr = rs.getString("G_ADDR");
String paid = rs.getString("PAID");
String total = rs.getString("TOTAL");
String balance = rs.getString("BALANCE");
System.out.println(name);
mainmenu menu = new mainmenu();
menu.getvalue(name, phono, addr, paid, total, balance);
tmp++;
}
} catch (SQLException ex) {
// Logger.getLogger(checkout.class.getName()).log(Level.SEVERE,
// null, ex);
}
if (tmp <= 0) {
JOptionPane.showMessageDialog(null, "no details found ");
}
}
==========================================================================
This is my frame java file
public void getvalue(String name, String phono, String addr, String paid,String total, String balance) {
nam.setText(name);
pho.setText(phono);
// mainmenu();
}
I edited as u said but getting error . I have attached my skeleton code
and the error i get, below
edited code.
database file
public class OracelThinconnection
{
private MainMenu menu;
public OracelThinconnection(MainMenu menu)
{
this.menu=menu;
..................
.................
.............
========================================================================
Error i get
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: constructor OracelThinconnection()
location: class bookingapp.OracelThinconnection
at bookingapp.MainMenu.jButton1ActionPerformed(MainMenu.java:1438)
at bookingapp.MainMenu.access$300(MainMenu.java:33)
at bookingapp.MainMenu$4.actionPerformed(MainMenu.java:379)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
I don't understand the code you've not shown, but a guess as to your problem is that you're creating a new instance of your GUI, one not visualized, and trying to send information to it, while the visualized GUI sits unperturbed and un-updated.
The key is that you're creating a new instance of your mainmenu GUI, one that has no relationship to the one that is displayed. Passing data to this new instance will have no effect on the displayed GUI.
Here:
mainmenu menu= new mainmenu();
menu. getvalue (name, phono, addr, paid, total, balance);
You're creating a new mainmenu object (the class should be named MainMenu).
A solution, give your Database class a MainMenu field, and pass into this field a valid reference to the main gui, and then call methods on the GUI, but only on the Swing event thread. For example:
public class MyDataBase {
private MyGui gui;
// constructor gets passed a reference to the valid displayed GUI
public MyDataBase(MyGui gui) {
this.gui = gui;
}
public void someDataBaseMethod() {
// get database information
// now you can call methods on the actual displayed GUI
// but on the Swing event thread only. The SwingUtilities.invokeLater
// with the Runnable is required to be sure that you don't mess up
// Swing's threading model.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// this method below is being called on the
// displayed MyGui instance.
gui.updateGuiWithInformation(....); // some update method of the GUI
}
});
}
The key -- don't create a new GUI instance inside of the database code.
OK, you've changed your code and now have a constructor that looks like so:
public OracelThinconnection(MainMenu menu) {
// ....
}
Now you need to look at the line that the error is pointing to, MainMenu.java:1438, line 1438 (1438????) of the MainMenu class. On that line you likely call the OracelThinconnection constructor but are not passing the current MainMenu instance into it. The new constructor will accept a MainMenu reference, but when you call the constructor, you now have to remember to pass that reference in to the constructor.
Specifically, change it from
// not sure what you name the variable below
// but I just gave it thinConnection for now.
OracelThinconnection thinConnection = new OracelThinconnection();
to this:
OracelThinconnection thinConnection = new OracelThinconnection(this);
or if this doesn't work, then
OracelThinconnection thinConnection = new OracelThinconnection(MainMenu.this);
As an addendum, your code obviously has more than 1400 lines which tells you that you've got some huge God class that tries to do any thing and everything. I strongly urge you to refactor this code, to make smaller classes, each with their own sphere of responsibilities, else you will not be able to debug or enhance this program.
Related
Description
A JFileChooser is used in a Java Swing application. Users are able to enter any filename permitted by the operating system, but from time to time they will enter erroneous filenames, such as names including invalid characters.
If a user enters a name ending with a space, such as
SomeName
an error message is shown. This is done by overriding JFileChooser#approveSelection, matching the filename to an undesired regex and then displaying an error dialog.
However when the user enters only a space, then an exception is thrown:
2022-10-18 12:34:54 SEVERE (CustomExceptionHandler::uncaughtException) Uncaught exception: java.nio.file.InvalidPathException: Trailing char < > at index 22: C:\X\Y\Z\ on [AWT-EventQueue-0]
Exception Stacktrace:
java.nio.file.InvalidPathException: Trailing char < > at index 22: C:\X\Y\Z\
at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:191)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229)
at java.base/java.nio.file.Path.of(Path.java:147)
at java.base/java.nio.file.Paths.get(Paths.java:69)
at java.desktop/sun.awt.shell.ShellFolder.getShellFolder(ShellFolder.java:247)
at java.desktop/javax.swing.plaf.basic.BasicFileChooserUI.changeDirectory(BasicFileChooserUI.java:1353)
at java.desktop/javax.swing.plaf.basic.BasicFileChooserUI$ApproveSelectionAction.actionPerformed(BasicFileChooserUI.java:1142)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:297)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6635)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6400)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5011)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:117)
at java.desktop/java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:190)
at java.desktop/java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:235)
at java.desktop/java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:233)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.desktop/java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:233)
at java.desktop/java.awt.Dialog.show(Dialog.java:1070)
at java.desktop/javax.swing.JFileChooser.showDialog(JFileChooser.java:769)
at java.desktop/javax.swing.JFileChooser.showSaveDialog(JFileChooser.java:691)
at core.RetainerExportController.exportRetainer(RetainerExportController.java:156)
at core.RetainerExportController.lambda$1(RetainerExportController.java:64)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:297)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6635)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6400)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5011)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
This exception keeps popping up in our error logs, because while users are instructed not to enter spaces as filenames, they still will from time to time.
Investigation
After looking into this, the problem appears to be coming from the BasicFileChooserUI. There is a filter for missing or empty strings in the class:
if (filename == null || filename.length() == 0) {
// no file selected, multiple selection off, therefore cancel the approve action
resetGlobFilter();
return;
}
However there is no filter for a blank filename. So this name is not filtered by BasicFileChooserUI, but it is recognized to be ending on a space by the WindowsPathParser, which leads to the error.
There is more odd behavior as well. For example entering a name consisting purely of forbidden characters, such as
???
results in just nothing happening, i.e.
No exception is thrown
JFileChooser#approveSelection is also never reached
How to solve?
It is not clear how to solve it, because all of the erroneous behavior occurs in internal Swing and sun.nio.fs code. E.g. there are regex filters in our JFileChooser implementation, which trigger upon approveSelection and check for names consisting of spaces and invalid characters - however approveSelection is never called in this scenario. It is called if WindowsPathParser#parse and WindowsPathParser#normalize are passed, but otherwise the error handling is useless, because some weird internal error handling is done internally beforehand.
I've looked into extending the WindowsFileChooserUI or the BasicFileChooserUI, but not only would that introduce unnecessary explicit dependencies on the desktop package for the latter case, but it is (as far as I see) not possible to do, at least with anything close to clean software design, because both of those classes use private members that are crucial to the problem at hand. E.g. WindowsFileChooserUI holds the JTextField which handles the user input as a private member and sets it up and uses it in the same method, so accessing it and even modifying it in any class attempting to extend WindowsFileChooserUI is going to be a problem.
Long story short - how do I prevent an InvalidPathException from being thrown, when users open the JFileChooser dialog and enter only a space?
Notes
Because internal APIs are affected the used JDK may be relevant: 11.0.14_9
The dialog creation itself is not spectacular, it is created thusly:
JFileChooser dialog = new CustomFileChooser( file );
dialog.setDialogType( JFileChooser.SAVE_DIALOG );
dialog.setAcceptAllFileFilterUsed( false );
The only methods that are overridden by CustomFileChooser are
createDialog
approveSelection
Minimal reproducible example
Because an example has been requested, the error can be reproduced as follows:
Set up a swing application (e.g. in Eclipse)
Create a JFileChooser dialog as such:
JFileChooser dialog = new JFileChooser( file );
dialog.setDialogType( JFileChooser.SAVE_DIALOG );
dialog.setAcceptAllFileFilterUsed( false );
Run the application, make sure the dialog creation is triggered
In the dialog enter a space as filename:
Confirm
An InvalidPathException is thrown
Note that this error requires the JVM being run on Windows and my tests happened on Java 11.
While older file chooser versions stripped spaces from entered file names, they never cared about the validity of the names beyond spaces. E.g. entering something like \<\>\" gets accepted. Invalid path names didn’t cause exceptions, because java.io.File doesn’t check the syntax either.
In newer versions, the NIO FileSystem API is used at some places and the space is not always stripped. The specific exception occurs because new File(" ").getAbsoluteFile().isDirectory() evaluates to true for some reason (while new File(" ").isDirectory() doesn’t), so the file chooser tries to change the directory to the invalid path, instead of invoking approveSelection() which the application could override.
Since file chooser’s code can’t cope with exceptions for invalid files, I made this workaround which uses a special File subclass which reports not to be a directory and can be detected at approveSelection():
public class FileChooserTest {
static final class Invalid extends File {
final String originalName;
public Invalid(String pathname) {
super(pathname);
originalName = pathname;
}
#Override
public boolean isDirectory() {
return false;
}
#Override
public String getName() {
return originalName;
}
}
public static void main(String... args) {
if(!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(FileChooserTest::main);
return;
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ReflectiveOperationException | UnsupportedLookAndFeelException e) {
throw new RuntimeException(e);
}
JFileChooser fc = new JFileChooser() {
#Override
public void approveSelection() {
if(getSelectedFile() instanceof Invalid) {
setSelectedFile(null);
return;
}
super.approveSelection();
}
};
fc.setFileSystemView(new FileSystemView() {
#Override
public File createFileObject(String path) {
try {
Paths.get(path);
} catch(InvalidPathException ex) {
return new Invalid(path);
}
return super.createFileObject(path);
}
#Override
public File createFileObject(File dir, String filename) {
try {
Paths.get(filename);
} catch(InvalidPathException ex) {
return new Invalid(filename);
}
return super.createFileObject(dir, filename);
}
#Override
public File createNewFolder(File containingDir) throws IOException {
return FileSystemView.getFileSystemView().createNewFolder(containingDir);
}
});
if(fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println(fc.getSelectedFile());
}
else System.out.println("Not approved");
}
}
This does not only eliminate the exception but also prevents invalid files from getting approved. Of course, it could be improved, e.g. by providing feedback to the user. But it would be better if bugs like JDK-8196673 get fixed anyway.
Note: the reason why names containing * or ? are not rejected, is that they are converted to a file name filter. So when you enter, e.g. *.txt, it should show up in the filter combobox.
Maybe you could simply remove the leading/trailing spaces from the filename before file chooser processing is invoked:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main
{
public static void main(String[] args) throws Exception
{
JFileChooser fc = new JFileChooser( );
JTextField tf = SwingUtils.getDescendantsOfType(JTextField.class, fc).get(0);
tf.addFocusListener( new FocusAdapter()
{
#Override
public void focusLost(FocusEvent e)
{
JTextField tf = (JTextField)e.getSource();
tf.setText( tf.getText().trim() );
System.out.println( tf.getText() );
}
});
tf.addKeyListener( new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
JTextField tf = (JTextField)e.getSource();
tf.setText( tf.getText().trim() );
System.out.println( tf.getText() );
}
}
});
fc.showOpenDialog(null);
}
}
The above code requires the Swing Utils class.
I extended JFileChooser to add a confirmation dialog if the file I wanted to save has the same name as an existing file. Perhaps you can use this to start a more robust version of JFileChooser.
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class OSFileChooser extends JFileChooser {
private static final long serialVersionUID = 1L;
#Override
public void approveSelection() {
File f = getSelectedFile();
if (f.exists() && getDialogType() == SAVE_DIALOG) {
int result = JOptionPane.showConfirmDialog(this, f.getName() +
" exists, overwrite?",
"Existing file", JOptionPane.YES_NO_CANCEL_OPTION);
switch (result) {
case JOptionPane.YES_OPTION:
super.approveSelection();
return;
case JOptionPane.NO_OPTION:
return;
case JOptionPane.CLOSED_OPTION:
return;
case JOptionPane.CANCEL_OPTION:
cancelSelection();
return;
}
}
super.approveSelection();
}
#Override
public File getSelectedFile() {
File file = super.getSelectedFile();
if (file != null && getDialogType() == SAVE_DIALOG) {
String extension = getExtension(file);
if (extension.isEmpty()) {
FileTypeFilter filter = (FileTypeFilter) getFileFilter();
if (filter != null) {
extension = filter.getExtension();
String fileName = file.getPath();
fileName += "." + extension;
file = new File(fileName);
}
}
}
return file;
}
public String getExtension(File file) {
String extension = "";
String s = file.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < (s.length() - 1)) {
extension = s.substring(i + 1).toLowerCase();
}
return extension;
}
}
And the associated FileTypeFilter class.
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class FileTypeFilter extends FileFilter {
private String extension;
private String description;
public FileTypeFilter(String description, String extension) {
this.extension = extension;
this.description = description;
}
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return file.getName().endsWith("." + extension);
}
#Override
public String getDescription() {
return description + String.format(" (*.%s)", extension);
}
public String getExtension() {
return extension;
}
}
I'm a beginner. I want to write a weather app that gets some information from the web and show it to the user. But I have trouble to pass the user input to the JSON method. Can anybody help me?
the problem is in ActionListener part.
import com.google.gson.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
public class Weather extends JFrame implements ActionListener {
static JButton getWeather;
static JTextField inputZip, showCity, showState, showCondition, showTemp;
static JLabel enterZip, city, state, condition, temp, image;
public static double temp_f, temp_c;
static Image pic;
public static String zip, jCity, jState, jCondition, fORc;
public Weather() throws Exception {
//Button
getWeather = new JButton("Get Weather");
getWeather.addActionListener(this);
//TextFiels
inputZip = new JTextField(10);
showCity = new JTextField(10);
showState = new JTextField(10);
showCondition = new JTextField(10);
showTemp = new JTextField(10);
//Labels
enterZip = new JLabel ("Enter Zipcode:");
city = new JLabel ("City:");
state = new JLabel ("State:");
condition = new JLabel ("Condition:");
temp = new JLabel ("temp:");
//Radio Buttons
CheckboxGroup tUnit = new CheckboxGroup();
Checkbox f = new Checkbox ("f", tUnit, true);
Checkbox c = new Checkbox ("c", tUnit, false);
//Image
URL coldPicURL = new URL("https://cdn1.iconfinder.com/data/icons/xmas-color/512/snow_snowflake_winter_cold_weather-128.png");
URL hotPicURL = new URL("http://yowindow.com/img/yo_128.png");
URL picURL = new URL ("http://findicons.com/files/icons/2796/metro_uinvert_dock/128/the_weather_channel.png");
if (temp_f!=0 && temp_f<=60)
pic = ImageIO.read(coldPicURL);
else if (temp_f > 60)
pic = ImageIO.read(hotPicURL);
else
pic = ImageIO.read(picURL);
image = new JLabel(new ImageIcon(pic));
//Frame
JFrame weather = new JFrame ("Weather App");
weather.setVisible(true);
weather.setSize(500,250);
weather.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panels
JPanel pInput = new JPanel();
JPanel pDisplay = new JPanel();
JPanel pDisplayInfo = new JPanel();
JPanel pTempUnits = new JPanel();
JPanel pImage = new JPanel();
//Panels' Layout
pInput.setLayout(new FlowLayout());
pDisplay.setLayout(new BorderLayout());
pDisplayInfo.setLayout(new GridLayout(5,2));
pTempUnits.setLayout(new FlowLayout());
//Frame Layout
weather.add(pInput, BorderLayout.NORTH);
weather.add(pDisplay, BorderLayout.CENTER);
pDisplay.add(pDisplayInfo, BorderLayout.NORTH);
pDisplay.add(pTempUnits, BorderLayout.CENTER);
weather.add(pImage, BorderLayout.EAST);
//Insertion the objects into the panels
pInput.add(enterZip);
pInput.add(inputZip);
pInput.add(getWeather);
pDisplayInfo.add(city);
pDisplayInfo.add(showCity);
pDisplayInfo.add(state);
pDisplayInfo.add(showState);
pDisplayInfo.add(condition);
pDisplayInfo.add(showCondition);
pDisplayInfo.add(temp);
pDisplayInfo.add(showTemp);
pTempUnits.add(c);
pTempUnits.add(f);
pImage.add(image);
}
public void actionPerformed(ActionEvent e) {
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
getJson (zip);
showCity.setText(jCity);
showState.setText(jState);
showCondition.setText(jCondition);
if (fORc.equals("f"))
showTemp.setText(Double.toString(temp_f));
if (fORc.equals("c"))
showTemp.setText(Double.toString(temp_c));
}
public static void getJson(String zip) throws Exception {
String json="", line;
JsonElement jse;
final String key = "7b86aadc43344a90";
JsonParser parser = new JsonParser();
URL url = new URL("http://api.wunderground.com/api/" +
key + "/conditions/q/" + zip + ".json");
InputStream is = url.openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null)
json += line;
rd.close();
jse = parser.parse(json);
jCity=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("city").getAsString();
jState=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("state").getAsString();
jCondition=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("weather").getAsString();
temp_f=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_f").getAsDouble();
temp_c=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_c").getAsDouble();
}
public void itemStateChanged (ItemEvent ie){
Checkbox cb = (Checkbox)ie.getItemSelectable();
fORc = cb.getLabel();
}
public static void main(String[] args) throws Exception {
Weather w = new Weather();
}
}
On a first level:
getJson (zip);
that call throws an exception. And in Java you have to either try/catch that exception; or add it to the signature of the method this happens (using the throws keyword). In your case, that is not possible, as you are actually overriding an existing method; and then you can't add a throws statement to the method signature.
But the real answer here is: slow down. The above compiler error is about a super basic thing within Java. When you don't know what an Exception is, and how to properly deal with that, then you are many hours of learning away from writing a Swing UI application that wants to deal with JSON data from a remote site.
This also becomes obvious when looking in how you structure your code. You clearly separate responsibilities; you create classes around those that help you coming up with a clean OO based model. For example, you would fully separate the UI layer (swing) that displays information from the specifics where such information is coming from. Your JFrame shouldn't know anything about JSON input.
Your code shows nothing of that. I call this the "you should learn to crawl before going for hurdle racing" syndrome.
First,I think you'd better provide more detail information, what kind of problem is? Is that kind of exception for an unexpected result? Or you can just post the result for others to take a look.
Second, I tried to run your program. There are two issue in that.
1. in the code that you wrote a comment : //HERE'S WHERE I'M STUCKED !!! :(
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
getJson (zip);
showCity.setText(jCity);
showState.setText(jState);
the method getJson() you have "throws Exception", so when you invoke the method, you also need to deal with the exception maybe you can just catch the exception like this:
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
try {
getJson (zip);
} catch (Exception e1) {
e1.printStackTrace();
}
showCity.setText(jCity);
showState.setText(jState);
Or you can continue throw the exception.
when finished the previous problem, I found the "fORc" will meet a null pointer exception which you need to check your process when to pass the var.
Third,still about the fORc, in your code, you wrote
if (fORc.equals("f"))
showTemp.setText(Double.toString(temp_f));
if (fORc.equals("c"))
showTemp.setText(Double.toString(temp_c));
But I suggest you can change like this, then you can deal when the fORc is a null:
if (null == fORc)
//do something. like throw exception
if ("f".equals(fORc))
showTemp.setText(Double.toString(temp_f));
if ("c".equals(fORc))
showTemp.setText(Double.toString(temp_c));
Hope could help you.
I have a flume process that reads data from file on a spooldir & loads the data into MySQL database. There will be multiple types of files that can be processed by the same flume process.
I have created a custom sink java class (extending AbstractSink), that updates a local variable (sInterfaceType) after an initial/first read to decide the data format in the file.
I have to reset it once the file processing completes, so that it has to start with identifying the next batch/interface file.
I tried to do in stop() but it doesn't help. Did anybody do this?
My sink class looks like this:
public class MyFlumeSink2 extends AbstractSink implements Configurable {
private String sInterfaceType; //tells file format of current load
public MyFlumeSink2() {
//my initialization of variables
}
public void configure(Context context) {
//read context variables
}
public void start() {
//create db connection
}
#Override
public void stop() {
//destroy connection
sInterfaceType = ""; //This doesn't help me
super.stop();
}
public Status process() throws EventDeliveryException {
Channel channel = getChannel();
Transaction transaction = channel.getTransaction();
if((sInterfaceType=="" || sInterfaceType==null))
{
//Read first line & set sInterfaceType
}else
//Insert data in MySQL
transaction.commit();
}
}
We have to manually decide which event it is, there is no specialized method called for every new file.
I revised my code to read the event line & set InterfaceType based on first element. My code looks like this:
public Status process() throws EventDeliveryException {
//....other code...
sEvtBody = new String(event.getBody());
sFields = sEvtBody.split(",");
//check first field to know record type
enumRec = RecordType.valueOf( checkRecordType(sFields[0].toUpperCase()) );
switch(enumRec)
{
case CUST_ID:
sInterfaceType = "T_CUST";
bHeader = true;
break;
case TXN_ID:
sInterfaceType = "T_CUST_TXNS";
bHeader = true;
break;
default:
bHeader = false;
}
//insert if not header
if(!bHeader)
{
if(sInterfaceType == "T_CUST")
{
if(sFields.length == 14)
this.bInsertStatus = daoClass.insertHeader(sFields);
else
throw new Exception("INCORRECT_COLUMN_COUNT");
}else if(sInterfaceType == "T_CUST_TXNS")
{
if(sFields.length == 10)
this.bInsertStatus = daoClass.insertData(sFields);
else
throw new Exception("INCORRECT_COLUMN_COUNT");
}
//if(!bInsertStatus)
// logTransaction(sFields);
}
//....Other code....
I'm going to ask a huge favor here.
I have a view that when it opens, it should show every beverage from the database, and show that on the screen.
It also has to add a + button, an amount label next to it, and a - button. This should be done for every item.
The tables I'm getting the items from is called dhh_item by the way.
Now, I've got this:
public ArrayList<Item> getBeverages(Item item) {
ArrayList<Item> items = new ArrayList<>();
if (item != null) {
// First open a database connnection
DatabaseConnection connection = new DatabaseConnection();
if (connection.openConnection()) {
// If a connection was successfully setup, execute the SELECT statement.
ResultSet resultset = connection.executeSQLSelectStatement(
"SELECT * FROM dhh_item ");
if (resultset != null) {
try {
while (resultset.next()) {
String itemName = resultset.getString("itemName");
String status = resultset.getString("status");
String description = resultset.getString("description");
int price = resultset.getInt("price");
Item newItem = new Item(itemName, status, description, price);
items.add(newItem);
}
} catch (SQLException e) {
System.out.println(e);
items.clear();
}
}
// else an error occurred leave array list empty.
// We had a database connection opened. Since we're finished,
// we need to close it.
connection.closeConnection();
}
}
return items;
}
Is this correct in any way. Would I retrieve any data at all? (The .getString()'s are correct.)
Now, this method is inside of another Class (ItemDAO).
Can I call this from my view? How would I get it to make a new label + button for each?
Thanks a lot for those who could help me out on this one!
At the end, it should be looking like this:
for each beverage in the table.
Sounds rather straigh forward
Collection<Item> items=dao.getBeverages(someItem) // get all items
for(Item item:items){
label=new JLabel(item.getYourItemNameOrLabelOrhatever) // this will be the "coca-cola"
incButton=new JButton(incrementButtonAction); // craete/get some action
decButton=new JButton(decrementButtonAction); // same here
counter=new JLabel("0");
yourContainer.add(label);
yourContainer.add(incButton);
yourContainer.add(label);
yourContainer.add(decButton);
yourContainer.revalidate();
}
here is my entire class. I read data from a text file, put them into an aeeaylist. then from that array list i want to show the data on a JTable, when the specific method is called.But is doesnt show anything
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author George
*/
import java.awt.*;
import java.util.ArrayList;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.EOFException;
//import java.io.IOException;
//import java.io.ObjectInputStream;
/*import java.io.File;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.JOptionPane;*/
import java.io.*;
//import java.util.Locale;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Company extends JFrame {
private ArrayList<Employee> emp=new ArrayList<Employee>();
//Employee[] list=new Employee[7];
public void getEmployees(Employee emplo){
emp.add(emplo);
}
/*public void openTxt(){
try {
Scanner input=new Scanner(new File("Employees.txt"));
}
catch(FileNotFoundException e){
JOptionPane.showMessageDialog(null, "File Not Found.");
System.exit(1);
}
}*/
public void doRead() throws Exception{
//ArrayList<Employee> emp=new ArrayList<Employee>() ;
//Employee[] emp=new Employee[7];
//read from file
File data = new File("src/Employees.txt");
BufferedReader read = new BufferedReader(new FileReader(data));
String input;
int i = 0;
//int salesmen = 0;
while ((input = read.readLine()) != null) {
String [] lineParts = input.split(",");
/**
* the following block converts some of the strings inputted to
* the appropriate vartypes.
*/
String EmpNo=(lineParts[0]);
String type=lineParts[10];
String PostalCode = (lineParts[5]);
int phone = Integer.parseInt(lineParts[6]);
short DeptNo = (short) Integer.parseInt(lineParts[8]);
double Salary;
short card = (short) Integer.parseInt(lineParts[11]);
int dtype=0;
if(type.equals("FULL TIME")){
dtype=1;
}
else if(type.equals("SELLER")){
dtype=2;
}
else
dtype=3;
/**
* Creates employee instances depending on their type of employment
* (fulltime=1, parttime=3, salesman=2)
*/
switch (dtype) {
case 1 :
//empNo,firstname, lastname, address, city, PostalCode, phone,
//email, deptcode,Jobtype, salary, TimecardId, hoursW
Salary = Double.parseDouble(lineParts[10]);
emp.add(new FullTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0));
i++;
break;
case 2 :
Salary = Double.parseDouble(lineParts[10]);
ArrayList<Orders> orders=new ArrayList<Orders>();
Salary = Double.parseDouble(lineParts[10]);
emp.add(new Salesman(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0, orders));
i++;
break;
case 3 :
Salary = Double.parseDouble(lineParts[10]);
emp.add(new PartTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0));
i++;
break;
default :
break;
}
}
}
public ArrayList<Employee> getArray(){
return emp;
}
//test methodos gia tin proti epilogi-den deixnei tipota omws sto JTable ????
public /*JTable */ void getOptionA(){
ArrayList<Employee> list=getArray();
/*String[] columnNames = {"Code","First Name","Last Name","Address","Cisty","Postal Code","Phone","Email",
"Dept Code","Salary","Time Card","Hours"};*/
/* Object[][] data;
*/
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(new String[] {"Code","First Name","Last Name","Address","City","Postal Code","Phone","Email",
"Dept Code","Salary","Time Card","Hours"});
for( Employee current : list){
model.addRow(new Object[] {current.getCode(),current.getName(),current.getSurname(),
current.getAddress(),current.getCity(),current.getTK(),
current.getPhone(),current.getMail(),current.getDeptCode(),
current.getSalary(),current.getCard(),current.getHours()
});
}
/*JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);*/
//return table;
table.setPreferredScrollableViewportSize(new Dimension(500,50));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void showOptionA(){
getOptionA();
Company gui =new Company();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 400);
}
}
I call showOptionA() from a JButton located on another JFrame Class.
private void showEmployeesActionPerformed(java.awt.event.ActionEvent evt) {
Results showEmp=new Results();
//showEmp.setVisible(true);
//showEmp.setOptions(1);
Company company=new Company();
/*JTable table=company.getOptionA();
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
table.setVisible(true);*/
company.showOptionA();
}
Basically i have a "main"JFrame with different options, and each button,representing a different option, calls the appropriate option method from Company Class.
When i click on the button "Show Employees Status". i want it to show the JTable above. Instead a new Frame opens but is blank??
EDIT: if i change showOptionA() to static, and then just call it inside showEmployeesActionPerformed , ( which is located in class PayrollForm)
public static void showOptionA(){
Company gui =new Company();
gui.getOptionA();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 400);
}
i now see the columns but with no data(empty)
This has nothing to do with calling revalidate as recommended by another and likely has all to do with calling a method on the wrong object. In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. The key is to call this method on the proper reference, on the visualized GUI. You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. This can be done via a setCompany method:
setCompany(Company company) {
this.company = company);
}
or via a constructor parameter.
I think the reason is your method showOptionA():
first you add your JTable and Model to your Company Object, which is your Frame. But right after it, you create a new Company Object, set the wanted Frame settings and show that object instead of your first Company object, where the table is.
You just could leave the gui thing out, and set DefaultCloseOperation directly on your Company object and set it visible true.
Some other suggestions:
You also should set the size of your frame, before you set it visible true.
And getters normally just give back the related object, instead of putting it on some list.
Might be there are some more mistakes in it, but it should at least show your table.
Call revalidate() after adding anything to JTable (or its model).
Ok problem Solved!. The problem was in getOptionA() method.
i set the model of the Jtable, but not the option to be visible. SO thats why it appeared empty. I corrected this by moving
try {
//try to read from text file
doRead();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "An Exception has Occured! The application will now close.");
System.exit(0);
}
table.revalidate();
add(scrollPane);
setVisible(true);
setSize(600, 400);
up,from showOptionA, up to getOptionA() method. By doing this showOptionA becomes useless(and thus i deleted it). Now i call getOptionA from the showEmployeesActionPerformed and its all ok :). Thanks to all people who replied to my wuestion, and special thanks to Hovercraft Full Of Eels . He helped me undeestand why the table wasnt appearing the way i wanted it to