I have got a tricky problem. I need to pop a confirm message box for user to decide close or not when someone click the close sign on the right upper corner of the window. But It doesn't work. Whatever you choose in the pop message box , the dialog will always be closed. But the same logic works fine when I create a JFrame.
Below is my code in my netbeans IED.
I just use a WindowAdpter to catch the close event, plz igore the dummy code generated by neatbean.
Thanks.
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TestClosingDialog extends javax.swing.JDialog {
public TestClosingDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null,"Are you sure you need to close?", "Tip", JOptionPane.YES_NO_OPTION);
if (a == 0) {
System.out.println("yes " + a);
System.exit(0); //close
} else if (a==1) {
System.out.println("no " + a);
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestClosingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TestClosingDialog dialog = new TestClosingDialog(new JFrame(), true);
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
Change setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); to setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING);
This will require you to manually dispose of the dialog. Depending on your needs, you would simply need to change System.exit(0); to dispose();
I would, personally, advise against extending directly from a top level container like JDialog, but that's just me.
I prefer to use, something like, a JPanel that has a helper method that can display an dialog. This method would create the dialog and add the panel to it, for example
Related
When I try to add anything to JFrame in constructor and I have IllegalArgumentException.
Similar code is working in documentation:
https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Why my very simple code doesn't work? It is created in Netbeans 10.
Edit:
I also tried add label with position and sieze (setBounds) it doesn't help. I changed the code with setBounds method.
First, main class in JavaTestApp.java:
package javatestapp;
public class JavaTestApp {
public static void main(String[] args) {
TestForm mainFrame = new TestForm();
mainFrame.setLocation(300, 150);
mainFrame.setVisible(true);
mainFrame.toFront();
mainFrame.repaint();
}
}
Second file is:
package javatestapp;
import javax.swing.JLabel;
public class TestForm extends javax.swing.JFrame {
/**
* Creates new form TestForm
*/
public TestForm() {
initComponents();
JLabel label = new JLabel("Test label");
label.setBounds(10,10,100,25);
getContentPane().add(label);
}
// GENERATED CODE BELOW
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
pack();
}// </editor-fold>
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestForm().setVisible(true);
}
});
}
Stacktrace, regarding to #VGR request:
Exception in thread "main" java.lang.IllegalArgumentException
at org.netbeans.lib.awtextra.AbsoluteLayout.addLayoutComponent(Unknown Source)
at java.awt.Container.addImpl(Container.java:1120)
at java.awt.Container.add(Container.java:410)
at javatestapp.TestForm.<init>(TestForm.java:16)
at javatestapp.JavaTestApp.main(JavaTestApp.java:5)
BUILD STOPPED (total time: 9 seconds)
Link to project uploaded on weetransfer:
Project (scanned via my Bitdefender antivir)
I also chosen absolute layout
And that is your problem. You are not using it correctly.
getContentPane().add(label);
You can't just add the label to the frame without specifying the proper constraints. I've never used AbsoluteLayout (because I believe in proper layout management) but I would guess you need to specify constraints like x, y, width, height.
The layout manager can't guess where you want to position the component so you need to specify all the information. That is why you should be using a layout manager. Then the layout manager will position the component based on the rules of the layout manager. Much easier, once you practice it a little.
I have four small class: one extends from JFrame and has GUI form, second — extends from him and contains button work logic. Third class call second's class method, when second — call him :)). My problem in second method in second class: button can't enable! I click — it disabled, but, when calling method enableButton — nothing do!
First class:
public class ClassParent extends JFrame {
protected JButton button;
private JPanel mainJPanel;
public ClassParent() {
super("Window");
setContentPane(mainJPanel);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void showWindow() {
setVisible(true);
}
}
Second class:
public class ClassChildren extends ClassParent {
private CallerClass callerClass;
public ClassChildren(CallerClass callerClass) {
super();
this.callerClass = callerClass;
callerClass.setClassChildren(this);
button.addActionListener(a -> {
callerClass.callMe();
button.setEnabled(false);
});
}
public void enableButton() {
button.setEnabled(true);
}
}
Third class:
public class CallerClass {
private ClassChildren classChildren;
public void setClassChildren(ClassChildren classChildren) {
this.classChildren = classChildren;
}
public void callMe() {
classChildren.enableButton();
}
}
Main class:
public class Main {
public static void main(String[] args) {
new ClassChildren(new CallerClass()).showWindow();
}
}
And GUI form photo (I can't find code, other than open it in notepad :)):
Why is this happening and how fix it?
Apparently the OP has solved his problem, but I think this is an interesting and common-enough problem, so I've created a Minimal, Complete and Verifiable Example of what my recommended approach would be, for future reference.
You can check it out below, or you can get the full project from the GitHub repository.
(Reviews, suggestions, revisions and feedback are also welcome!)
Main JFrame:
/**
* #author Rodrigo Legendre Lima Rodrigues (AKA ArchR / AlmightyR)
* <rodrigolegendre.developer#gmail.com>
*/
public class Main extends javax.swing.JFrame {
/**
* A public method so we can enable/disable state from outside the class
* (while keeping the components encapsulated).
*
* #param enabled The input state the components should assume.
*/
public void setInputState(boolean enabled) {
this.startProcessButton.setEnabled(enabled);
}
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
startProcessButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Primary Frame");
startProcessButton.setText("Process");
startProcessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startProcessButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(startProcessButton, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(startProcessButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
#SuppressWarnings("Convert2Lambda")
private void startProcessButtonActionPerformed(java.awt.event.ActionEvent evt) {
//We need a non-annonymous reference for this frame to use within our annonymous 'run()'.
Main main = this;
//Here is were we disable input for (the components of) this frame before running the secondary frame.
this.setInputState(false);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Secondary(main).setVisible(true);
}
});
}
/**
* #param args the command line arguments
*/
#SuppressWarnings("Convert2Lambda")
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton startProcessButton;
// End of variables declaration
}
Secondary JFrame:
/**
*
* #author Rodrigo Legendre Lima Rodrigues (AKA ArchR)
* <rodrigolegendre.developer#gmail.com>
*/
public class Secondary extends javax.swing.JFrame {
/**
* A variable to hold a reference to the main frame. We need this to enable
* the input of main again after this frame's work is done.
*/
private Main main;
/**
* A self-reference to this frame. We need this to hide the frame from
* within the worker, after it's job is done.
*/
private Secondary secondary;
/**
* A SwingWorker executes a process without interfering with the UI's
* execution, which could otherwise cause delays or complete "locking" of
* the visual and input processes.
*/
SwingWorker<Integer, Integer> swingWorker = new SwingWorker<Integer, Integer>() {
#Override
#SuppressWarnings("SleepWhileInLoop")
protected Integer doInBackground() throws Exception {
//Execute the process...
for (int i = 0; i <= 100; i++) {
progressBar.setValue(i);
Thread.sleep(100);
}
//We handle reactivating the main frame's inputs on the closing event,
//to make sure they get enabled after this frame is closed,
//regardless of sucess, cancelation or failure.
//We close and dispose of the secondary frame.
//Note: We have set default close behavior for this frame to be disposing, so we simply send it a closing event.
secondary.dispatchEvent(new WindowEvent(secondary, WindowEvent.WINDOW_CLOSING));
//Alternatively:
//main.setInputState(true);
//secondary.setVisible(false);
//secondary.dispose();
return 100;
}
};
/**
* In order to start the process while keeping all related code contained
* within this class, we make it listen to it's own WindowOpened event.
*
* In order to avoid calling an overridable method ('addListener()') from
* the constructor, which could be "forgotten" on extensions, we create a
* private method to initialize all self-listeners.
*/
private void initSelfListeners() {
WindowListener taskStarterWindowListener = new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
//This starts the process when the window opens.
System.out.println("Performing task...");
swingWorker.execute();
}
//<editor-fold defaultstate="collapsed" desc="UNUSED EVENTS/METHODS">
#Override
public void windowClosing(WindowEvent e) {
//Do nothing.
}
#Override
public void windowClosed(WindowEvent e) {
//Do nothing.
}
#Override
public void windowIconified(WindowEvent e) {
//Do nothing.
}
#Override
public void windowDeiconified(WindowEvent e) {
//Do nothing.
}
#Override
public void windowActivated(WindowEvent e) {
//Do nothing.
}
#Override
public void windowDeactivated(WindowEvent e) {
//Do nothing.
}
//</editor-fold>
};
//Here is where the magic happens. We make (a listener within) the frame start listening to the frame's own WindowOpened event.
this.addWindowListener(taskStarterWindowListener);
}
/**
* Creates new form Secondary
*/
#SuppressWarnings("LeakingThisInConstructor")
private Secondary() {
initComponents();
initSelfListeners();
this.secondary = this;
}
public Secondary(Main main) {
this();
this.main = main;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
processingLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Secondary Frame");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
processingLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
processingLabel.setText("Processing...");
progressBar.setStringPainted(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(processingLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(processingLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formWindowClosing(java.awt.event.WindowEvent evt) {
//When the window is closed, we enable the input in the main frame again.
//This is advantageous as it handles most cases in one go...
//The cases were the window closes after the process is complete,
//the cases there the window closes due to cancelation,
//or the cases where it is closed by the user (after an error message) after a failure.
main.setInputState(true);
}
/**
* #param args the command line arguments
*/
#SuppressWarnings("Convert2Lambda")
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Secondary.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Secondary().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel processingLabel;
private javax.swing.JProgressBar progressBar;
// End of variables declaration
}
Problem was in that I call firstly callMe() and enable buttons and then — I disabled they in listeners......
Hey i have some questions/problems.
I have to create a little program for text editing. The (selected) text should be style. Bold, Italic, Underline, Right- left- center alignment.
It works great. I used the specific StyleEditorKit Actions.
My problem is now that this actions are fired through buttons in a jtoolbar and jmenuitems in a jmenu / jmenubar.
So there are two click elements to set a text bold, two elements to set a text italic and so on.
If one element (e.g. the button in the toolbar) is clicked, the jmenuitem should be selected/activated too.
But how can i realize this?
My idea is to check the selected text (CaretListener is implemented). If the text is bold => set the button and menuitem active.
But how can i get if the selectedText is bold/italic etc?
I think there is a StyledDocument tree with leafs for this stuff. But how can i get this tree? how can i get the leafs?
This are my first steps:
jTextPane1.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
Highlight[] h = jTextPane1.getHighlighter().getHighlights();
for(int i = 0; i < h.length; i++) {
System.out.println(h[i].getStartOffset());
System.out.println(h[i].getEndOffset());
String selectedText = jTextPane1.getSelectedText();
StyledDocument styleddoc = (StyledDocument) jTextPane1.getDocument();
System.out.println(styleddoc);
}
}
});
But i only get javax.swing.text.DefaultStyledDocument#5098cb76
How can i iterate over the tree and get the leafs / bold or italic elements?
Thank you
how can i get if the selectedText is bold/italic etc?
In your CaretListener you can use:
AttributeSet attributes = jTextPane1.getCharacterAttributes();
System.out.println( attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE) );
If one element (e.g. the button in the toolbar) is clicked, the jmenuitem should be selected/activated too.
You should be using an Action:
Action bold = new StyledEditorKit.BoldAction();
JButton boldButton = new JButton( bold );
JCheckBoxMenuItem boldMenuItem = new JCheckBoxMenuItem( bold );
When you set the state of an Action, the state of all components using the Action is changed. For example you can make the Action selected or enabled.
my code looks like this now
public void jToolBarInitButtons() {
jTextPane1.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
StyledDocument styleddoc = (StyledDocument) jTextPane1.getDocument();
AttributeSet attributes = jTextPane1.getCharacterAttributes();
System.out.println("bold " + attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE));
System.out.println("italic " + attributes.containsAttribute(StyleConstants.Italic, Boolean.TRUE));
}
So there are two click elements to set a text bold, two elements to set a text italic and so on. If one element (e.g. the button in the toolbar) is clicked, the jmenuitem should be selected/activated too. But how can i realize this?
Create both the menu item and the button by passing the same Action to their constructors.
It sounds like you intend show the bold state in the button and menu item, so you’ll probably want to create a JCheckBoxMenuItem and a JToggleButton. When you create the Action, set its SELECTED_KEY to a non-null value, so the buttons will keep it up to date:
action.putValue(Action.SELECTED_KEY, false);
From the Action documentation:
SELECTED_KEY
Components that honor this property only use the value if it is non-null. For example, if you set an Action that has a null value for SELECTED_KEY on a JToggleButton, the JToggleButton will not update it's selected state in any way. Similarly, any time the JToggleButton's selected state changes it will only set the value back on the Action if the Action has a non-null value for SELECTED_KEY. Components that honor this property keep their selected state in sync with this property. When the same Action is used with multiple components, all the components keep their selected state in sync with this property.
Your CaretListener should be as camickr described.
Sorry. This is the whole code:
Update 2: here is the code
public class TestFrame extends javax.swing.JFrame {
/**
* Creates new form TestFrame
*/
public TestFrame() {
initComponents();
initButtons();
}
Action boldAction = new StyledEditorKit.BoldAction();
Action italicAction = new StyledEditorKit.ItalicAction();
Action underlineAction = new StyledEditorKit.UnderlineAction();
public void initButtons() {
JButton boldButton = new JButton(boldAction);
boldButton.setText("bold");
JButton italicButton = new JButton(italicAction);
boldButton.setText("italic");
JButton underlineButton = new JButton(underlineAction);
boldButton.setText("underline");
jToolBar1.add(boldButton);
jToolBar1.add(italicButton);
jToolBar1.add(underlineButton);
jTextPane1.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
Highlighter.Highlight[] h = jTextPane1.getHighlighter().getHighlights();
for(int i = 0; i < h.length; i++) {
System.out.println("length " + h.length);
System.out.println(h[i].getStartOffset());
System.out.println(h[i].getEndOffset());
String selectedText = jTextPane1.getSelectedText();
StyledDocument styleddoc = (StyledDocument) jTextPane1.getDocument();
AttributeSet attributes = jTextPane1.getCharacterAttributes();
System.out.println("Bold " + attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE));
System.out.println("Italic " + attributes.containsAttribute("Italic " + StyleConstants.Italic, Boolean.TRUE));
System.out.println("Underline " + attributes.containsAttribute(StyleConstants.Underline, Boolean.TRUE));
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jToolBar1 = new javax.swing.JToolBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jTextPane1);
jToolBar1.setRollover(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(116, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(75, 75, 75))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(89, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
private javax.swing.JToolBar jToolBar1;
// End of variables declaration
}
I want to call my function on specific time interval. For now my time interval set fixed as 1 minute. I have following code example:
Timer.java
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Timer implements Runnable{
public static volatile boolean isRunning = true;
#Override
public void run() {
while (isRunning) {
if(Thread.currentThread().getName().equals("TimerThread")){
System.out.println("Start Time "+new Date());
try {
test();
Thread.sleep(60000);
} catch (InterruptedException ex) {
Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("End Time "+new Date());
}
}
}
public void test(){
System.out.println("Call Test ===========================> "+new Date());
}
}
NewJFrame.java
import java.awt.event.ItemEvent;
import java.util.Date;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jToggleButton1 = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jToggleButton1.setText("Start");
jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton1ItemStateChanged(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(162, 162, 162)
.addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(138, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jToggleButton1)
.addContainerGap(142, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if(evt.getStateChange() == ItemEvent.SELECTED){
jToggleButton1.setText("Stop");
timer = new Timer();
timer.isRunning = true;
timerThread = new Thread(timer);
timerThread.setName("TimerThread");
timerThread.start();
}else{
jToggleButton1.setText("Start");
timer.isRunning = false;
System.out.println("Stop Time ===============> "+new Date());
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
public Timer timer;
public Thread timerThread;
// Variables declaration - do not modify
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration
}
When I start thread then I will get following output:
Start Time Sat Aug 08 10:45:01 IST 2015
Call Test ===========================> Sat Aug 08 10:45:01 IST 2015
Once Time interval completed then I get following output:
End Time Sat Aug 08 10:46:01 IST 2015
Start Time Sat Aug 08 10:46:01 IST 2015
Call Test ===========================> Sat Aug 08 10:46:01 IST 2015
after that I have stop my thread on 00:00:30 second so I will get following output:
Stop Time ===============> Sat Aug 08 10:46:31 IST 2015
I have stop my Thread on 00:00:30 second but my function call automatically after 00:00:30 second
Any one help me that how can I call any function on fixed time interval using Thread Just like When I click on Start button then my thread will start and call function then after wait for 2 minute. After 2 minute again call my function and repeat cycle. If I click stop button then thread will stop until I will start Thread using Start button.
The correct answer is: Don't use a Thread. Use a Timer, SwingTimer or ScheduledExecutorService depending on what you want the Thread to do.
To answer the actual question though you want then check isRunning and exit immediately after the sleep completes. You can also send an interrupt to the thread to make the sleep stop immediately if that is something you want.
I had some questions earlier regarding this base code which were
solved here but now my issue is that i have to take this code and get
out the result in GUI textArea. What ive done so far is that ive
designed a textArea and a button but now im stuck. I dont know how to
translate that code i used as a base into the GUI and make it possible
to click on the button and display the answers into the textdisplay. I
dont know if i should copy this base code somewhere or do i need to do
totally different thing inside of the GUI? For instance under
jButtonActionPerformed, what do i need to do... im sorry im new to
this and so lost. Ive googled all day but its hard to understand.
Here is the base code :
import java.lang.String;
class Vara {
//Deklarerar variabler
private String name;
private double price;
private int antal;
//tildela konstruktorer för de deklarerade variablerna
public Vara (String name, int antal, double price) {
this.name = name;
this.antal = antal;
this.price = price;
} // slut constructor
public void setName(String name) {
this.name = name; }
public void setPrice (double price) {
this.price = price; }
public void setAntal (int antal) {
this.antal = antal; }
public String getName() {
return this.name;}
public double getPrice() {
return this.price; }
public int getAntal() {
return this.antal; }
}
//testklassen ska stå som en egen klass
class Test {
public static void main(String[] args){
Vara var = new Vara("Banan",5, 12.5);
System.out.println("Namnet är " +var.getName() +" och priset är " +var.getPrice() +" och antalet är "+var.getAntal() );// här slutar system.out
}
}
And here is the beginning of my code in GUI which i havent done anything on so far except creating a textArea and a button.
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(29, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(69, 69, 69))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 361, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
txtDisplay.setText(null);
txtDisplay.append(String.valueOf(String)+"\n");
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
in GUI Class make set the modifier to "Public Static" so it can be accessed from other class.
public static javax.swing.JTextArea jTextArea1;
then you can enter Value in this jTextArea1 from other classes. by accessing directly like this
NewJFrame.jTextArea1.append("text to append");
From your question it is not obvious if you want to put in data into your JTextArea or to read the content entered in the JTextArea in order to store it somewhere else. I will answer for both cases.
An elegant way to wire up data and GUI is to insert the data model object (in your case an instance of the class Vara) into a GUI object. E.g. this can be done right at the GUI object creation as shown in the code below. I commented each new line in your code with "// CHANGED: ...".
public class NewJFrame extends javax.swing.JFrame {
// CHANGED: store the model for this GUI
private Vara vara;
/**
* Creates new form NewJFrame
*/
public NewJFrame(Vara vara) { // CHANGED: provide the model for this GUI
this.vara = vara; // CHANGED: store the model for this GUI
initComponents();
// CHANGED: set TextArea content according to the data in the
// provided model object (if this is what you want)
jTextArea1.setText(vara.getName());
}
...
...
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
txtDisplay.setText(null);
txtDisplay.append(String.valueOf(String)+"\n");
// CHANGED: read the entered text from the TextArea and store it as the
// new name of the Vara object (if this is what you want to happen when
// the user clicks on the button)
vara.setName(jTextArea1.getText());
}
...
...
...
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
Some tips for a better programmer life:
use English everywhere, also in the comments
always name the GUI elements reasonable, e.g. your jButton1 could be btnSave ("btn" stands for Button) and your jTextArea1 could be taVaraName ("ta" stands for TextArea) - this greatly increase readability of your GUI code and makes debugging and maintaining much easier
use Eclipse for Java development, esp. if you want to build GUIs. It comes with a plugin called Eclipse WindowBuilder. This is "a powerful and easy to use bi-directional Java GUI designer", means you can: (1) easily drag-and-drop your GUI elements and get the code automatically generated for you; (2) modify any part of the code and see the drag-and-drop view automatically changing accordingly. It generates much cleaner and often shorter GUI code than the one you posted and lets you modify everything (does not have the "don't modify" parts you have in your code)