Calling a method on a JTabbedPane - java

I have created a method using JFreeChart and SQL that essentially creates a graph based on the data present in the database. I have 3 methods, one particular example, the users weight vs time. I wish to display these graphs in a JTabbedPane and am unsure how. When I call the method on the one tab it tells me static/void methods are not allowed. My method has no paramters. Here is my initial attempt:
panelWeight = new JPanel();
panelWeight.setLayout(null);
panelWeight.add(StatGraph.WeightGraph());
EDIT:
I returned to the drawing board, after discovering a) I cannot call a void method to the component and B) a null layout does not scale. Here is my re-written method I wish to call to the JTabbedPane, making the method non-void.
public static ChartFrame WeightGraph(){
ChartFrame returnFrame = null;
try{
ConnectionManager connectionManager = ConnectionManager.getInstance();
Connection connection = connectionManager.getConnection();
UserInfoManager user = new UserInfoManager();
int username = user.getId();
String query = "SELECT DATE, WEIGHT FROM STATS WHERE ID=" + username; JDBCCategoryDataset dataset = new JDBCCategoryDataset(connection, query);
JFreeChart chart = ChartFactory.createLineChart("WEIGHTvsDATE Chart", "Date", "Weight", dataset, PlotOrientation.VERTICAL, false, true, true);
BarRenderer renderer = null;
CategoryPlot plot = null;
renderer = new BarRenderer();
ChartFrame frame = new ChartFrame("Progress Log", chart);
returnFrame = frame;
//frame.setVisible(true);
//frame.setSize(750,400);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return returnFrame;
}
I then return to the GUI Frame and add the following code to the Panel in the TabbedPane, activated by using a click listener.
panelWeight.add(StatGraph.WeightGraph());
However, I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:488)
at java.awt.Container.addImpl(Container.java:1089)
at java.awt.Container.add(Container.java:415)
at GUI.PT.ProgressStatsPT.panelWeightMouseClicked(ProgressStatsPT.java:392)
at GUI.PT.ProgressStatsPT.access$600(ProgressStatsPT.java:26)
at GUI.PT.ProgressStatsPT$7.mouseClicked(ProgressStatsPT.java:138)
at java.awt.Component.processMouseEvent(Component.java:6528)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4542)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

What does exactly Graph.weightLg() return? The add() method from JPanel takes an instance of Component or a subclass. If the Graph.weightLg() method doesn't return anything (which I suppose is your case) the compilation will fail.

Related

XmlParser Error while rendering a Dynamic Jasper report in Java

I need create a report with Columns added dynamically, So i choose Dynamic Report version 5.3.2 to achieve this, but there is problem while rendering the report. i have an Exception i dont know what's wrong, it's about xml parser or something like but i don't really know. I use jdk 1.8.2.0 and Netabeans 11.0 as IDE, here is the excpetion
Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.<init>(SimpleFontExtensionHelper.java:149)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.getInstance(SimpleFontExtensionHelper.java:131)
at net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.ensureFontExtensions(FontExtensionsRegistry.java:80)
at net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.getExtensions(FontExtensionsRegistry.java:57)
at net.sf.jasperreports.extensions.DefaultExtensionsRegistry.getExtensions(DefaultExtensionsRegistry.java:134)
at net.sf.jasperreports.engine.util.JRStyledTextParser.<clinit>(JRStyledTextParser.java:86)
at net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:114)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:82)
at net.sf.jasperreports.engine.fill.JRFiller.createBandReportFiller(JRFiller.java:251)
at net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:272)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:156)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:145)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:758)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:1074)
at ar.com.fdvs.dj.core.DynamicJasperHelper.generateJasperPrint(DynamicJasperHelper.java:244)
at ar.com.fdvs.dj.core.DynamicJasperHelper.generateJasperPrint(DynamicJasperHelper.java:220)
at com.gepa.views.principal.PrincipalScreenx.rapportPerformanceActionAction(PrincipalScreenx.java:6307)
at com.gepa.views.principal.PrincipalScreenx$85.actionPerformed(PrincipalScreenx.java:3166)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Here is my code for creating the dynamic report
FastReportBuilder drb = new FastReportBuilder();
drb.addColumn("State", "state", String.class.getName(),30)
.addColumn("Branch", "branch", String.class.getName(),30)
.addColumn("Product Line", "productLine", String.class.getName(),50)
.addColumn("Item", "item", String.class.getName(),50)
.addColumn("Item Code", "id", Long.class.getName(),30,true)
.addColumn("Quantity", "quantity", Long.class.getName(),60,true)
.addColumn("Amount", "amount", Float.class.getName(),70,true)
.addGroups(2)
.setTitle("November " + 2021 +" sales report")
.setSubtitle("This report was generated at " + new Date())
.setPrintBackgroundOnOddRows(true)
.setUseFullPageWidth(true);
drb.addGlobalFooterVariable(drb.getColumn(4), DJCalculation.COUNT, null, new DJValueFormatter() {
public String getClassName() {
return String.class.getName();
}
public Object evaluate(Object value, Map fields, Map variables, Map parameters) {
return (value == null ? "0" : value.toString()) + " Clients";
}
});
List rowsDataList = new ArrayList();
DynamicReport dr = drb.build();
JasperPrint finalreport = DynamicJasperHelper.generateJasperPrint(dr,new ClassicLayoutManager(), rowsDataList);
JasperViewer.viewReport(finalreport);
}catch(Exception e)
{
e.printStackTrace();
}
I don't know if it's cause by a missing dependancy or a conflict but it's not working, Please help me to solve this. Thanks in advance
looks like your project is using a old version of the JAXP (Locate and uninstall the plugin that loads the outdated implementation of the Java API for XML Processing (JAXP), e.g., Xerces 2.6.)
I found this info that might help: https://support.cloudbees.com/hc/en-us/articles/360036082251-Pipeline-Maven-Integration-fails-due-to-java-lang-AbstractMethodError?page=21

In Java why do i get java.lang.IllegalStateException: cannot open system clipboard

In Java why do I get java.lang.IllegalStateException: cannot open system clipboard ?
This was running on Windows using Java 1.8.0_181 25.181-b13
java.lang.IllegalStateException: cannot open system clipboard
at sun.awt.windows.WClipboard.openClipboard(Native Method)
at sun.awt.datatransfer.SunClipboard.getClipboardFormatsOpenClose(SunClipboard.java:327)
at sun.awt.datatransfer.SunClipboard.isDataFlavorAvailable(SunClipboard.java:188)
at com.jthink.songkong.ui.startdialog.editsongs.EditSongsTable$PasteAction$1.flavorsChanged(EditSongsTable.java:170)
at sun.awt.datatransfer.SunClipboard$1SunFlavorChangeNotifier.run(SunClipboard.java:441)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
PasteAction methods is
public PasteAction(JTable tbl)
{
putValue(NAME, TextLabel.PASTEBUTTON.getMsg());
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
table = tbl;
final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.addFlavorListener(new FlavorListener()
{
#Override
public void flavorsChanged(FlavorEvent e)
{
try
{
setEnabled(cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR)
|| cb.isDataFlavorAvailable(DataFlavor.stringFlavor));
}
catch(IllegalArgumentException iae)
{
MainWindow.logger.log(Level.SEVERE, iae.getMessage(), iae);
}
}
});
setEnabled(cb.isDataFlavorAvailable(CellTransferable.CELL_DATA_FLAVOR)
|| cb.isDataFlavorAvailable(DataFlavor.stringFlavor));
}
This happens when the Java app is notified that it has lost ownership, so it sometimes needs to allow a small amount of time for the clipboard to be "ready." By adding a very short sleep command to the method, we will be able to avoid the runtime exceptions. Please go to below link for more information
https://coderanch.com/t/377833/java/listen-clipboard

[IllegalStateException : Attempt to Mutate in Notification]

I want to make a documentListener that if I type in the JTextField : txt_ip4class and match regex of IPv4 format it will change the JComboBox : box_ip4class content.
If the content is changed (itemStateChanged), range of IP Class will be written down to JTextField : txt_rangeclass, and bit usage will be write down to `JTextField : txt_bitclass``*.
I have succeeded in this method, but with a classic method (using jButton), but I failed in this method using documentListener. Only JComboBox : box_ip4Class changed.
My code, applying documentListener to txt_ip4class:
txt_ip4class.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
logUpdate();
}
#Override
public void removeUpdate(DocumentEvent e) {
logUpdate();
}
#Override
public void changedUpdate(DocumentEvent e) {
logUpdate();
}
void logUpdate() {
Runnable doHighlight = new Runnable() {
#Override
public void run() {
String aTxt = txt_ip4class.getText();
classValue = 1;
if (!aTxt.matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b")) {
classValue = 0;
} else if (aTxt.matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b")) {
try {
classW.classMain(classValue, box_ip4class, txt_ip4class, txt_rangeclass, txt_bitclass);
} catch (IllegalStateException e) {
}
}
}
};
SwingUtilities.invokeLater(doHighlight);
}
});
classW.Main contains two conditions, if zero it will set other fields based on jComboBox (txt_ip4class will be replaced), if one it should be set jComboBox choosing an option. And from that option, it should do like option zero
Full code (I export these files from Netbeans project to zip):
Succeed method which using jButton to execute
Failed method which using documentListener without jButton
Full exception stacktrace is here
or
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1338)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:658)
at javax.swing.text.JTextComponent.setText(JTextComponent.java:1669)
at engines.ClassW.setFromCombo(ClassW.java:140)
at interfaces.Netgui$1.logUpdate(Netgui.java:63)
at interfaces.Netgui$1.insertUpdate(Netgui.java:41)
at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:201)
at javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:748)
at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:707)
at javax.swing.text.PlainDocument.insertString(PlainDocument.java:130)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:669)
at javax.swing.text.JTextComponent.replaceSelection(JTextComponent.java:1328)
at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(DefaultEditorKit.java:884)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1663)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2882)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2929)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2845)
at java.awt.Component.processEvent(Component.java:6310)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771)
at java.awt.Component.dispatchEventImpl(Component.java:4760)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 19 seconds)
===============EDIT 1============
Thanks to #MarkRotteveel
And this post
This problem is fixed, but another problem is exist..
Code in the doHighlight is running in a loop.
===============EDIT 2============
Updated the code.
doHighlight no longer looping when the condition doesn't equal the regex.
but still doing loop when the condition equals.

Illegal State Exception in java

I'm getting this exception when I run my code. Even though the code runs fine, I'm getting some exceptions on the terminal
Exception in thread "AWT-EventQueue-1" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at SR.start(SR.java:38)
at SR.mouseClicked(SR.java:212)
at java.awt.Component.processMouseEvent(Component.java:6536)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Window.processEvent(Window.java:2025)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at org.GNOME.Accessibility.AtkWrapper$5.dispatchEvent(AtkWrapper.java:700)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
What am i doing wrong??
My start() method
private void start() throws IllegalStateException {
if (HelperThread == null)
HelperThread = new Thread(this);
HelperThread.start();
}
You appear to be starting the same Thread twice, which is not allowed.
If you're looking to reuse the same thread, I would recommend creating an ExecutorService instead.
The problem is that if HelperThread is not null (it already exists) and you call HelperThread.start() is tries to start() a thread that has already started or finished it's processing. If you want to restart processing, you'll have to stop the thread first. To do this gracefully, use a while (running) { } pattern in the actual thread. Then, int the start()-method, set the flag to false, wait for the thread to die and then start a new thread:
private void start() throws IllegalStateException {
if (HelperThread != null) {
running = false;
HelperThread.join(); // wait for it to die...
}
// Start fresh...
HelperThread = new Thread(this);
HelperThread.start();
}
Also, as a side note, avoid using capital letters as the first letters for variables. It should rather be "helperThread".

Exception is not being captured

I have a program where you can input name, surname, id and export them to a text file. The file can be imported back by using a load method. The problem with the load method is if you press the load button and don't select a file the list of errors will appear. I need to create an exception for these errors so the user will receive "Please Select a file" warning instead. So I created a custom exception:
public class CancelException extends Exception {
public CancelException() {
}
public CancelException(String message) {
super(message);
}
}
Then I tried to put it in the load method:
public static Person loadcons() throws IOException, CancelException {
Person loadcons = null;
try {
JFileChooser chooser = new JFileChooser();
int chooserOption = chooser.showSaveDialog(null);
chooserOption = JFileChooser.APPROVE_OPTION;
File file = new File(chooser.getSelectedFile().getAbsolutePath());
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
loadcons = (Person) input.readObject();
input.close();
return loadcons;
} catch (IOException ex) {
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (Exception ex) {
throw new CancelException("Please select a file");
}
return null;
}
private String toString(String PersonID) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
The problem is that the exception is not being recognized and it is still giving me the exception stack trace instead of the warning.
The list of errors are below:
Aug 17, 2015 12:41:50 PM ryan_assignment_sit2.CreateConsultant jButton3ActionPerformed
SEVERE: null
ryan_assignment_sit2.CancelException: Please select a file
at ryan_assignment_sit2.Person.loadcons(Person.java:105)
at ryan_assignment_sit2.CreateConsultant.jButton3ActionPerformed(CreateConsultant.java:218)
at ryan_assignment_sit2.CreateConsultant.access$300(CreateConsultant.java:29)
at ryan_assignment_sit2.CreateConsultant$4.actionPerformed(CreateConsultant.java:87)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
You can just check whether the file is selected or not by adding following condition:
if (chooser.getSelectedFile() == null)
{
JOptionPane.showMessageDialog(null, "Please select a file", "No file selected", JOptionPane.WARNING_MESSAGE);
}
null ryan_assignment_sit2.CancelException: Please select a file at ryan_assignment_sit2.Person.loadcons(Person.java:105) at
Isn't it throwing an exception ? because you have passed the message to super class which is exception class.
you can try it just printing the warning using JOption pane instead?

Categories