JEditorPane focus problems after setText() - java

There is a problem in my application when trying to set focus on a JEditorPane using the tab key. I did not understand why at first, but I manage to make a small test case that demonstrates the issue.
public class JEditorPaneFocusTest
{
public static void main(String... args) throws Exception
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JTextField(), BorderLayout.NORTH);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body>Hello World</body></html>");
container.add(editorPane, BorderLayout.CENTER);
jFrame.setSize(new Dimension(400, 400));
jFrame.setVisible(true);
}
}
(Tested on Windows 7 and Mac OS X Lion.) The application will start with focus on the JTextField. Using the tab key won't set focus to the JEditorPane. But if you comment the setText line, it seems to work...
Any idea?

short answer
delay this event by wraping to the invokeLater()
longer answer
Focus / Focus Subsystem is asynchronous, in most cases hard to manage/timing this/these even(s), for better understanding about this issue you have to read linked tutorials,
example about Focus issue
import java.awt.*;
import java.awt.event.*;
import java.awt.font.TextAttribute;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
public class TextAttributeSTRIKETHROUGH {
private JFrame frame = new JFrame();
private JPanel pnl = new JPanel();
private JLabel focusLabel = new JLabel(" focusLost Handle ");
private JFormattedTextField formTextField;
private JLabel docLabel = new JLabel(" document Handle ");
private JFormattedTextField formTextField1;
private NumberFormat formTextFieldFormat;
private double amount = 10000.00;
private Map attributes;
#SuppressWarnings("unchecked")
public TextAttributeSTRIKETHROUGH() {
formTextFieldFormat = NumberFormat.getNumberInstance();
formTextFieldFormat.setMinimumFractionDigits(2);
formTextFieldFormat.setMaximumFractionDigits(2);
formTextFieldFormat.setRoundingMode(RoundingMode.HALF_UP);
focusLabel.setFont(new Font("Serif", Font.BOLD, 14));
focusLabel.setForeground(Color.blue);
focusLabel.setPreferredSize(new Dimension(120, 27));
formTextField = new JFormattedTextField(formTextFieldFormat);
formTextField.setValue(amount);
formTextField.setFont(new Font("Serif", Font.BOLD, 22));
formTextField.setForeground(Color.black);
formTextField.setBackground(Color.yellow);
formTextField.setPreferredSize(new Dimension(120, 27));
formTextField.setHorizontalAlignment(SwingConstants.RIGHT);
formTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
formTextField.requestFocus();
formTextField.setText(formTextField.getText());
formTextField.selectAll();
}
public void focusLost(FocusEvent e) {
//Runnable doRun = new Runnable() {
//#Override
//public void run() {
double t1a1 = (((Number) formTextField.getValue()).doubleValue());
if (t1a1 < 1000) {
formTextField.setValue(amount);
}
//}
// };
//SwingUtilities.invokeLater(doRun);
}
});
docLabel.setFont(new Font("Serif", Font.BOLD, 14));
docLabel.setForeground(Color.blue);
docLabel.setPreferredSize(new Dimension(120, 27));
formTextField1 = new JFormattedTextField(formTextFieldFormat);
formTextField1.setValue(amount);
formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
formTextField1.setForeground(Color.black);
formTextField1.setBackground(Color.yellow);
formTextField1.setPreferredSize(new Dimension(120, 27));
formTextField1.setHorizontalAlignment(SwingConstants.RIGHT);
formTextField1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
formTextField1.requestFocus();
formTextField1.setText(formTextField1.getText());
formTextField1.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
formTextField1.getDocument().addDocumentListener(docListener);
attributes = (new Font("Serif", Font.BOLD, 24)).getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
pnl = new JPanel();
pnl.setBorder(new EmptyBorder(2, 2, 2, 2));
pnl.setLayout(new GridLayout(2, 2));
pnl.add(focusLabel);
pnl.add(formTextField);
pnl.add(docLabel);
pnl.add(formTextField1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pnl, BorderLayout.CENTER);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
formTextFieldFocus1();
}
//
private DocumentListener docListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
DocumentEvent.EventType type = documentEvent.getType();
double t1a1 = (((Number) formTextField1.getValue()).doubleValue());
if (t1a1 < 1000) {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.setFont(new Font(attributes));
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
}
};
SwingUtilities.invokeLater(doRun);
}
}
};
private void formTextFieldFocus1() {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.grabFocus();
formTextField1.requestFocus();
formTextField1.setText(formTextField1.getText());
formTextField1.selectAll();
}
};
SwingUtilities.invokeLater(doRun);
}
private void formTextFieldFocus() {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField.grabFocus();
formTextField.requestFocus();
formTextField.setText(formTextField.getText());
formTextField.selectAll();
formTextFieldFocus1();
}
};
SwingUtilities.invokeLater(doRun);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TextAttributeSTRIKETHROUGH fl = new TextAttributeSTRIKETHROUGH();
}
});
}
}

All GUI related code should be executed on the EDT. See Concurrency in Swing for more details.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.html.*;
public class JEditorPaneFocusTest
{
public static void main(String... args) throws Exception
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JTextField(), BorderLayout.NORTH);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body>Hello World</body></html>");
container.add(editorPane, BorderLayout.CENTER);
jFrame.setSize(new Dimension(400, 400));
jFrame.setVisible(true);
}
});
}
}

Related

Show scrollbars only when mouse is over

I want to show scrollbars in a JScrollPane only when the mouse is over it. I tried adding a MouseAdapter to the JScrollbar as MouseListener with the methods shown below, but it didn't work very well. The scrollbars blinked when the mouse moved above them.
Any suggestions?
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
Runnable runner = new Runnable()
{
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
};
Thread t = new Thread(runner, "Enter Thread");
t.start();
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
Runnable runner = new Runnable()
{
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
};
Thread t = new Thread(runner, "Exit Thread");
t.start();}
In this case, the way to use the MouseListener is troublesome so I can not recommend it much.
For example, the mouse cursor flickers over the JScrollBar.
You might be able to use a JLayer:
Responding to Events - How to Decorate Components with the JLayer Class (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
import java.awt.*;
import java.awt.event.*;
import java.util.Collections;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class ScrollPaneMouseOverTest {
public JComponent makeUI() {
String text = String.join("\n", Collections.nCopies(100, "aaaaa"));
JTextArea ta = new JTextArea(
"Mouse cursor flickers over the JScrollBar.\n" + text);
ta.addMouseListener(new MouseAdapter() {
#Override public void mouseEntered(MouseEvent e) {
JScrollPane sp = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, (Component) e.getSource());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
#Override public void mouseExited(MouseEvent e) {
JScrollPane sp = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, (Component) e.getSource());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
}
});
JScrollPane scroll = new JScrollPane(new JTextArea(text));
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(new JScrollPane(ta));
p.add(new JLayer<>(scroll, new LayerUI<JScrollPane>() {
#Override public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK);
}
}
#Override public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
#Override protected void processMouseEvent(
MouseEvent e, JLayer<? extends JScrollPane> l) {
JScrollPane sp = l.getView();
switch (e.getID()) {
case MouseEvent.MOUSE_ENTERED:
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
break;
case MouseEvent.MOUSE_EXITED:
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
break;
default:
break;
}
//super.processMouseEvent(e, l);
}
}));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ScrollPaneMouseOverTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
I have edited my answer to include the comment below.
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(600, 600));
scrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(final java.awt.event.MouseEvent evt) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
});
}
#Override
public void mouseExited(final java.awt.event.MouseEvent evt) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JScrollPane sp = (JScrollPane) evt.getSource();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
});
}
});
JPanel panel = new JPanel(new BorderLayout());
add(panel);
JTextArea ta = new JTextArea();
ta.setPreferredSize(new Dimension(500, 500));
scrollPane.add(ta);
panel.add(scrollPane);

One JSpinner change all

I have a problem with using JSpinner. When I change spinerkp all variables (kp,sp,lk,ct) are changing value, and when I change any other JSpinner nothing happen. I don't know what is wrong with this. Anybody know what is wrong with this?
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class PorownanieLokat
{
private JFrame frame;
private JLabel naglowek;
private JLabel status;
private JPanel panel;
public int kp;
public int lk;
public int ct;
public int sp;
public PorownanieLokat()
{
przygotujGUI();
}
public static void main(String args[])
{
PorownanieLokat porownanieLokat = new PorownanieLokat();
porownanieLokat.Lokata();
}
private void przygotujGUI() {
frame = new JFrame("SWING");
frame.setSize(new Dimension(400, 400));
frame.setLayout(new GridLayout(4, 1));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
naglowek = new JLabel("", JLabel.CENTER);
status = new JLabel("", JLabel.CENTER);
status.setSize(350, 100);
panel = new JPanel();
panel.setLayout(new FlowLayout());
frame.add(naglowek);
frame.add(status);
frame.add(panel);
frame.setVisible(true);
}
public void Lokata()
{
Obliczenia obliczenia = new Obliczenia();
naglowek.setText("Wypełnij wszystkie pola aby obliczyć kapitał końcowy!");
JButton x = new JButton( "Oblicz!");
x.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
status.setText("Kapitał końcowy to: "+obliczenia.Licz(kp,sp,lk,ct));
}
});
SpinnerModel spinnerModel1 = new SpinnerNumberModel(1,0,10000,1);
JSpinner spinerkp = new JSpinner(spinnerModel1);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e1) {
kp =(int) ((JSpinner)e1.getSource()).getValue();
System.out.println(kp);
}
});
SpinnerModel spinnerModel2 = new SpinnerNumberModel(1,0,100,1);
JSpinner spinersp = new JSpinner(spinnerModel2);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e2) {
sp= (int) ((JSpinner)e2.getSource()).getValue();
System.out.println(sp);
}
});
SpinnerModel spinnerModel3 = new SpinnerNumberModel(1,1,12,1);
JSpinner spinerlk = new JSpinner(spinnerModel3);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e3) {
lk=(int) ((JSpinner)e3.getSource()).getValue();
System.out.println(lk);
}
});
SpinnerModel spinnerModel4 = new SpinnerNumberModel(1,0,50,1);
JSpinner spinerct = new JSpinner(spinnerModel4);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e4) {
ct= (int) ((JSpinner)e4.getSource()).getValue();
System.out.println(ct);
}
});
panel.add(spinerkp);
panel.add(spinersp);
panel.add(spinerlk);
panel.add(spinerct);
panel.add(x);
frame.setVisible(true);
}
}
Your code creates four JSpinner instances, and four ChangeListener's, but adds each ChangeListener to spinerkp (rather than adding them to their corresponding JSpinner).
JSpinner spinerkp...
spinnerkp.addChangeListener(./..)
JSpinner spinersp...
spinnersp.addChangeListener(./..)//add the change listener to the appropriate JSpinner
...

I thought I had the program ready to run but when I run it nothing happens

So I thought I had this code being able to work but it is not working.
I do not know what to do and I have tried looking at everything everyone has suggested but I just do not know what to do so any help would be greatly appreciated!
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class memory extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(156, 93, 82));
g.fill3DRect(21,3,7,12, true);
g.setColor(new Color(156,23,134));
g.fillOval(1,15,15,15);
g.fillOval(16,15,15,15);
g.fillOval(31,15,15,15);
g.fillOval(7,31,15,15);
g.fillOval(22,31,15,15);
g.fillOval(16,47,15,15);
setVisible(false);}
public memory()
{
GridLayout h =new GridLayout(3,3);
final JFrame frame = new JFrame();
final JPanel pan = new JPanel(h);
frame.add(pan);
pan.setBackground(new Color(130,224,190));
pan.setFont(new Font("Serif", Font.BOLD, 28));
JButton button1= new JButton();
pan.add(button1);
final JLabel label1= new JLabel("hi");
label1.setVisible(false);
pan.add(label1);
JButton button2= new JButton();
pan.add(button2);
final JLabel label2= new JLabel("hi");
label2.setVisible(false);
pan.add(label2);
JButton button3= new JButton();
pan.add(button3);
final JLabel label3 = new JLabel("hi");
label3.setVisible(false);
pan.add(label3);
JButton button4 = new JButton();
pan.add(button4);
final JLabel label4 = new JLabel("hi");
label4.setVisible(false);
pan.add(label4);
JButton button5= new JButton();
pan.add(button5);
final JLabel label5= new JLabel("hi");
label5.setVisible(false);
pan.add(label5);
JButton button6= new JButton();
pan.add(button6);
final JLabel label6= new JLabel("hi");
label6.setVisible(false);
pan.add(label6);
JButton button7= new JButton();
pan.add(button7);
final JLabel label7= new JLabel("hi");
label7.setVisible(false);
pan.add(label7);
JButton button8= new JButton();
pan.add(button8);
final JLabel label8= new JLabel("hi");
label8.setVisible(false);
pan.add(label8);
JButton button9= new JButton();
pan.add(button9);
final JButton button10= new JButton("Exit");
pan.add(button10);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Memory Game");
frame.setSize(500,500);
frame.setVisible(true);
setLayout(new BorderLayout());
add(pan,BorderLayout.CENTER);
add(button10, BorderLayout.SOUTH);
setSize(600,600);
setVisible(true);
final JLabel label9= new JLabel("hi");
label9.setVisible(false);
pan.add(label9);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label1.setVisible(true);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label2.setVisible(true);
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label3.setVisible(true);
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label4.setVisible(true);
}
});
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label5.setVisible(true);
}
});
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label6.setVisible(true);
}
});
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label7.setVisible(true);
}
});
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label8.setVisible(true);
frame.getContentPane().add(new memory());
setVisible(true);
}});
;
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label9.setVisible(true);}}
);
button10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (button10.getSize() != null) {
System.exit(0);}}
});};
public static void main(String args[])
{
new memory();
};
}
As I said in your last question, you need to add your panel to an instance of a JFrame...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new memory());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Take some time and have a read through Creating a GUI With JFC/Swing
You'll also want to remove
final JFrame frame = new JFrame();
final JPanel pan = new JPanel(h);
frame.add(pan);
From the constructor and simple add your components directly to the (memory) panel
You'll also need to remove setVisible(false); from your paintComponent method ... which explains why you're having so many problems...
You must have a JFrame and show it for a swing application. I dont see anything like that.
Your main should be like this:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new memory());
frame.setSize(500, 400);
frame.setVisible(true);
}
});
}

ProgressBar % text

SO I used the: ProgressBarDemo.java on Java tutorials. How would I go on adding
if 20% {
taskOutput.append(String.format("Completed %d%% of task.\n", task.getProgress()));
if 40% {
taskOutput.append(String.format("Completed %d%% loading region.\n", task.getProgress()));
if 60% {
taskOutput.append(String.format("Completed %d%% loading maps.\n", task.getProgress()));
etc...
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;
public class ProgressBarDemo extends JPanel implements ActionListener, PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
setProgress(0);
while (progress < 100) {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {}
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
#Override
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
setCursor(null);
taskOutput.append("Finished loading WorldPlay!\n");
}
}
public ProgressBarDemo() {
super(new BorderLayout());
startButton = new JButton("Start");
startButton.setActionCommand("start");
startButton.addActionListener(this);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5,5,5,5));
taskOutput.setEditable(false);
JPanel panel = new JPanel();
panel.add(startButton);
panel.add(progressBar);
add(panel, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
public void actionPerformed(ActionEvent evt) {
startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
taskOutput.append(String.format("Completed %d%% of task.\n", task.getProgress()));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("WorldPlay");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ProgressBarDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Close a swing Dialog after done operations

I have a jdialog and want close it on confirmation after that store the data of a text box... now I have no problem to store the data from the box but,
How can I close this dialog after the operation???
Seems a simple thing but I haven't found the solution.
public class test extends JDialog {
private final JPanel contentPanel = new JPanel();
public test() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try{
int x=Integer.parseInt(textField.getText());
saver.saveN(x);
}catch(Exception ecc){
JOptionPane.showMessageDialog(Test.this,"error");
}
}
});
}
}
}
}
Either use Window#dispose or Window#setVisible(false).
if you use this dialog only once time then there is same to use dispose() as setVisible(false)
in the case that you invoke this method more than once time, then you can use HIDE_ON_CLOSE
or setVisible(false), better would be re_use this JDialog
EDIT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
private static final long serialVersionUID = 1L;
private JDialog dialog = new JDialog();
private final JPanel contentPanel = new JPanel();
private Timer timer1;
private JButton killkButton = new JButton("Kill JDialog");
public Test() {
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel buttonPane = new JPanel();
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
killkButton.setActionCommand("Kill JDialog");
buttonPane.add(killkButton);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
startTimer();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
dialog.setLayout(new BorderLayout());
dialog.getRootPane().setDefaultButton(okButton);
dialog.add(buttonPane, BorderLayout.SOUTH);
dialog.add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setLocation(100, 100);
dialog.setVisible(true);
setKeyBindings();
}
private void setKeyBindings() {
killkButton.getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
killkButton.getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
}
If you plan to use a jDialog again with all the field values and component states left the same when you close it, use setVisible(false).
In any other case, call dispose(), to avoid the jDialog remaining in the memory when it is no longer required.

Categories