I have a small class that implements KeyListener, but even though I implemented all methods, including keyPressed(), and gave them all code to run, nothing happens when I press the enter (return) key.
Here is the class that I made implement KeyListener (the implemented methods are at the bottom):
public class TestPanel extends JPanel implements KeyListener {
Words word = new Words();
private JLabel rootLabel;
JLabel rootField;
private JLabel defLabel;
JTextField defField;
private JButton ok;
TestListener listener;
private JLabel correctLabel;
private JLabel incorrectLabel;
private int correctCount = 0;
private int incorrectCount = 0;
ActionListener okListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (defField.getText().equals("")) {
} else {
String root = word.getRoot();
String def = word.getDef();
boolean status;
if (defField.getText().equals(word.getDef())) {
correctCount++;
correctLabel.setText("Correct: " + correctCount);
status = true;
} else {
incorrectCount++;
incorrectLabel.setText("Incorrect: " + incorrectCount);
status = false;
}
defField.setText("");
word.setRootAndDef();
rootField.setText(word.getRoot());
TestEvent event = new TestEvent(ok, root, def, status);
listener.dataSubmitted(event);
}
}
};
public TestPanel() {
word = new Words();
rootLabel = new JLabel("Root: ");
rootField = new JLabel();
defLabel = new JLabel("Definition: ");
defField = new JTextField(20);
ok = new JButton("OK");
correctLabel = new JLabel("Correct: " + correctCount);
incorrectLabel = new JLabel("Incorrect: " + incorrectCount);
ok.setMnemonic(KeyEvent.VK_O);
setBorder(BorderFactory.createTitledBorder("Test"));
ok.addActionListener(okListener);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
// First row
gc.weightx = 1;
gc.weighty = 0.2;
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0, 0, 0, 5);
add(rootLabel, gc);
gc.gridx = 1;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(rootField, gc);
// Next row
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0, 0, 0, 5);
add(defLabel, gc);
gc.gridx = 1;
gc.gridy = 1;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(defField, gc);
// Next row
gc.weighty = 2;
gc.gridx = 1;
gc.gridy = 2;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(ok, gc);
// Next row
gc.weighty = 0.1;
gc.weightx = 1;
gc.gridx = 0;
gc.gridy = 3;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0, 0, 0, 20);
add(correctLabel, gc);
gc.weighty = 0.1;
gc.weightx = 1;
gc.gridx = 1;
gc.gridy = 3;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(incorrectLabel, gc);
}
public void setTestListener(TestListener listener) {
this.listener = listener;
}
public int getCorrectCount() {
return correctCount;
}
public int getIncorrectCount() {
return incorrectCount;
}
public void setCorrectCount(int correctCount) {
this.correctCount = correctCount;
}
public void setIncorrectCount(int incorrectCount) {
this.incorrectCount = incorrectCount;
}
public void setCorrectLabel(String text) {
correctLabel.setText(text);
}
public void setIncorrectLabel(String text) {
incorrectLabel.setText(text);
}
#Override
public void keyPressed(KeyEvent keySource) {
int key = keySource.getKeyCode();
if(key == KeyEvent.VK_ENTER) {
if (defField.getText().equals("")) {
} else {
String root = word.getRoot();
String def = word.getDef();
boolean status;
if (defField.getText().equals(word.getDef())) {
correctCount++;
correctLabel.setText("Correct: " + correctCount);
status = true;
} else {
incorrectCount++;
incorrectLabel.setText("Incorrect: " + incorrectCount);
status = false;
}
defField.setText("");
word.setRootAndDef();
rootField.setText(word.getRoot());
TestEvent event = new TestEvent(ok, root, def, status);
listener.dataSubmitted(event);
}
}
}
#Override
public void keyReleased(KeyEvent keySource) {
int key = keySource.getKeyCode();
if(key == KeyEvent.VK_ENTER) {
if (defField.getText().equals("")) {
} else {
String root = word.getRoot();
String def = word.getDef();
boolean status;
if (defField.getText().equals(word.getDef())) {
correctCount++;
correctLabel.setText("Correct: " + correctCount);
status = true;
} else {
incorrectCount++;
incorrectLabel.setText("Incorrect: " + incorrectCount);
status = false;
}
defField.setText("");
word.setRootAndDef();
rootField.setText(word.getRoot());
TestEvent event = new TestEvent(ok, root, def, status);
listener.dataSubmitted(event);
}
}
}
#Override
public void keyTyped(KeyEvent keySource) {
int key = keySource.getKeyCode();
if(key == KeyEvent.VK_ENTER) {
if (defField.getText().equals("")) {
} else {
String root = word.getRoot();
String def = word.getDef();
boolean status;
if (defField.getText().equals(word.getDef())) {
correctCount++;
correctLabel.setText("Correct: " + correctCount);
status = true;
} else {
incorrectCount++;
incorrectLabel.setText("Incorrect: " + incorrectCount);
status = false;
}
defField.setText("");
word.setRootAndDef();
rootField.setText(word.getRoot());
TestEvent event = new TestEvent(ok, root, def, status);
listener.dataSubmitted(event);
}
}
}
}
I have a small class that implements KeyListener, but even though I implemented all methods, including keyPressed(), and gave them all code to run, nothing happens when I press the enter (return) key. Please help me with this problem, here is the class that I made implement KeyListener (the implemented methods are at the bottom):
Short answer, don't. If you think you need a KeyListener, the likely hood is you don't. A KeyListener is a low level API which you very rarely need to use, as there are generally better ways to achieve the same thing.
In your case, both the JTextField and JButton support event notification via the ActionListener interface. In the case of the JTextField, this will notify you when the user presses the "action" key while field is focused and in the case of the JButton, when the user presses the "action", the buttons mnemonic key combination or presses the button with the mouse.
The ActionListener API is suppose to remove the complexity involved detecting this functionality and provide you with a simple call back through which you can perform the required action. Let's face it, we don't really care "how" the component was activated, only that it was
Instead, get rid of the KeyListener and simply use something like...
ok.addActionListener(okListener);
defField.addActionListener(okListener);
This way, the user won't need to press the button, but can press the "action" key for the field and the same functionality will get executed.
See How to Use Text Fields, How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
Related
I have a GUI application which is running fine, however I want to see how everything runs in debugging mode. The GUI has Monster moving in ScheduledExecutorService every 1 second. While the service is running in Debugging Mode, I want to see how User pressing button effects the Application. But, in debugging mode the button does not work, whereas it works when I am running the application normally. Please advise on how I can see user interaction in debuggin mode.
public class MainFrame extends JFrame{
private JLabel monsterLabel = new JLabel("0");
private JLabel statusLabel = new JLabel("Task not completed");
private JButton monsterButton = new JButton("Move Monster");
int monsterPosition = 1;
int playerPosition = 10;
public MainFrame(String title) {
super(title);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
add(monsterLabel, gc);
monsterLabel.setText("Monster position is: " + monsterPosition);
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 1;
gc.weighty = 1;
add(statusLabel, gc);
gc.gridx = 0;
gc.gridy = 2;
gc.weightx = 1;
gc.weighty = 1;
add(monsterButton, gc);
// Button to Move the monster
monsterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
monsterPosition = monsterPosition + 1;
setMonsterPosition(monsterPosition);
}
});
// The ScheduledExecutorService runs every 1 second.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(() -> moveMonster(), 1000L, 1000L, TimeUnit.MILLISECONDS);
setSize(200, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void setMonsterPosition(int monsterPosition) {
if(monsterPosition > 1 && monsterPosition < playerPosition) {
monsterLabel.setText("Monster position is: " + monsterPosition);
}
else {
monsterPosition = 0;
monsterLabel.setText("Monster has eaten the Player");
}
}
public void moveMonster() {
SwingWorker<Integer, Void> worker = new SwingWorker<>() {
#Override
protected Integer doInBackground() throws Exception {
monsterPosition++;
return monsterPosition;
}
#Override
protected void done() {
try {
Integer nextMonsterPosition = get();
setMonsterPosition(nextMonsterPosition);
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
worker.execute();
}
}
I am quite new to Java and before I end up asking this question I searched and searched SO, but I don't seem to get my head around it.
As you will see I have a class that creates a GUI, asks for some input and stores that input in a returnable String[].
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class InputConsole {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static String[] details = new String[3];
public static JButton btn2013;
public static JButton btn2014;
public static JButton btn2015;
public static JButton btn2016;
public static JButton btnGo;
public static JTextField textField2;
public static JTextField textField4;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;
}
btn2013 = new JButton("ZMR 2013");
btn2013.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2013";
btn2014.setEnabled(false);
btn2015.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
if (shouldWeightX) {
c.weightx = 0.0;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 0;
c.gridy = 0;
pane.add(btn2013, c);
btn2014 = new JButton("ZMR 2014");
btn2014.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2014";
btn2013.setEnabled(false);
btn2015.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 0);
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
pane.add(btn2014, c);
btn2015 = new JButton("ZMR 2015");
btn2015.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2015";
btn2013.setEnabled(false);
btn2014.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 2;
c.gridy = 0;
pane.add(btn2015, c);
btn2016 = new JButton("ZMR 2016");
btn2016.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2016";
btn2013.setEnabled(false);
btn2014.setEnabled(false);
btn2015.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 3;
c.gridy = 0;
pane.add(btn2016, c);
JLabel textField1 = new JLabel("What was your Bib number? : ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
pane.add(textField1, c);
textField2 = new JTextField(10);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[0] = textField2.getText();
textField4.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 2;
pane.add(textField2, c);
JLabel textField3 = new JLabel("What is your email address : ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
pane.add(textField3, c);
textField4 = new JTextField(15);
textField4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[1] = textField4.getText();
btnGo.setEnabled(true);
btnGo.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 3;
pane.add(textField4, c);
btnGo = new JButton("Go And Get Me My Diploma!");
btnGo.setEnabled(false);
btnGo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, details[0] + " " + details[1] + " " + details[2]);
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 0;
c.gridwidth = 4;
c.gridy = 4;
pane.add(btnGo, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Zagori Mountain Running Diploma Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setSize(500, 250);
frame.setVisible(true);
}
public String[] inputBib() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
return details;
}
But when I call this GUI in another class
public class CheckFiles {
InputConsole bibInput = new InputConsole();
String[] detailsInput = bibInput.inputBib();
private static Scanner scanner;
public String bibCorrected() {
String yearToCheck = null;
{
if (detailsInput[2] == "2016") {
yearToCheck = "ZMR2016.txt";
} else if (detailsInput[2] == "2015") {
yearToCheck = "ZMR2015.txt";
} else if (detailsInput[2] == "2014") {
yearToCheck = "ZMR2014.txt";
} else {
yearToCheck = "ZMR2013.txt";
in order to obtain that String[], I get a java.lang.NullPointerException. I Know that I get this because the program does not wait for the GUI to get all the input and files the returnable String[] as null. I think I know that I have to do something with wait() and notify() but I do not seem to understand exactly what.
Thank you in advance for any suggestions. (and very sorry for the long thread)
You could add a button on your GUI which will just call the bibCorrected() method. Currently you are showing and then returning so the array is empty and arg 2 is none existent therefor throwing an NPE. This would probably be the easiest way to resolve the issue.
Also, it's better to use String.equals(String) rather than ==. Read this StackOverflow post What is the difference between == vs equals() in Java?
I am using SwingWorker class to make a process run in another thread. What I want is, once this thread has finished processing, it should return a String and also it should enable a JMenuItem. I am using the done() method in the SwingWorker class to enable the JMenuItem but I receive a NullPinterException. The doInBackground() method returns a String which I want to access in the main GUI class - GUIMain.java, present in the same package. How should I do that? I saw many examples which implement done() or onPostExecute() methods, but I think I am going wrong somewhere. Here is the code which I have implemented:
public class GUIMain extends JFrame implements ActionListener, FocusListener, ItemListener, MouseListener, MouseMotionListener {
private JMenuBar menuBar; // Defined a menuBar item
private JMenu recalibrationMenu; // Define the recalibration menu item
private JMenuItem CGMenuItem;
private JMenuItem TGMenuItem;
private JMenu viewResultsMenu; // Define the View Results menu item
public JMenuItem cgResults;
public JMenuItem tgResults;
private JPanel TGImage;
private JPanel TGPanel;
private JPanel CGImage;
private JPanel CGPanel;
private JPanel CGRecalibrationParameters;
private JDialog resultsParameters;
private JLabel massPeakLabel = new JLabel("Select mass peak (m/z)");
private JTextField massPeakField = new JTextField(5);
private JLabel massWindowLabel = new JLabel("Mass window (Da)");
private JTextField massWindowField = new JTextField(5);
private float mzPeakValue;
private float massWindowValue;
private JButton massPeakSelectionButton = new JButton("OK");
private JButton CloseDialogButton = new JButton("Cancel");
private String CGRecalibratedFilesPath;
private String TGRecalibratedFilesPath;
/** Constructor to setup the GUI */
public GUIMain(String title) {
super(title);
setLayout(new BorderLayout());
menuBar = new JMenuBar();
menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
// build the Recalibration menu
recalibrationMenu = new JMenu("Recalibration");
CGMenuItem = new JMenuItem("Crystal Growth");
CGMenuItem.setEnabled(false); //initially disabled when app is launched
CGMenuItem.addActionListener(this);
TGMenuItem = new JMenuItem("Topological Greedy");
TGMenuItem.setEnabled(false); //initially disabled when app is launched
TGMenuItem.addActionListener(this);
recalibrationMenu.add(CGMenuItem);
recalibrationMenu.add(TGMenuItem);
// build the View Results menu
viewResultsMenu = new JMenu("View Results");
cgResults = new JMenuItem("CG Recalibration");
cgResults.setEnabled(false); //initially disabled when app is launched
cgResults.addActionListener(this);
tgResults = new JMenuItem("TG Recalibration");
tgResults.setEnabled(false); //initially disabled when app is launched
tgResults.addActionListener(this);
viewResultsMenu.add(cgResults);
viewResultsMenu.add(tgResults);
// add menus to menubar
menuBar.add(fileMenu);
menuBar.add(recalibrationMenu);
menuBar.add(viewResultsMenu);
// put the menubar on the frame
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked
setPreferredSize(new Dimension(1300, 800)); // Set the preferred window size
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public GUIMain()
{
}
}
public void actionPerformed(ActionEvent e) {
//Handle CG menu item action
**if ((e.getSource() == CGMenuItem)) {
RecalibrationWorker rw = new RecalibrationWorker(file,"CG");
rw.processCompleted();
rw.setVisible(true);
cgResults.setEnabled(true);
}**
if ((e.getSource() == cgResults)) {
viewRecalibrationResults("CG Recalibration - View Results", "CG");
}
if ((e.getSource() == tgResults)) {
viewRecalibrationResults("TG Recalibration - View Results", "TG");
}
}
private void viewRecalibrationResults(String dialogTitle, final String recalibrationType) {
resultsParameters = new JDialog();
resultsParameters.setLayout(new GridBagLayout());
resultsParameters.setTitle(dialogTitle);
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.WEST;
gc.ipady = 20;
// gc.anchor = GridBagConstraints.WEST;
resultsParameters.add(massPeakLabel, gc);
commonMassThresholdLabel.setLabelFor(massPeakField);
gc.gridx = 1;
gc.gridy = 0;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
resultsParameters.add(massPeakField,gc);
massPeakField.setText("");
massPeakField.addActionListener(this);
massPeakField.addFocusListener(this);
gc.gridx = 0;
gc.gridy = 1;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
resultsParameters.add(massWindowLabel, gc);
massWindowLabel.setLabelFor(massWindowField);
gc.gridx = 1;
gc.gridy = 1;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
resultsParameters.add(massWindowField,gc);
massWindowField.setText("");
massWindowField.addActionListener(this);
massWindowField.addFocusListener(this);
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.CENTER;
resultsParameters.add(massPeakSelectionButton, gc);
massPeakSelectionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("CG".equals(recalibrationType))
recalibrationResults("CG");
else if ("TG".equals(recalibrationType))
recalibrationResults("TG");
}
});
massPeakSelectionButton.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if ("CG".equals(recalibrationType))
recalibrationResults("CG");
else if ("TG".equals(recalibrationType))
recalibrationResults("TG");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
gc.gridx = 1;
gc.gridy = 2;
gc.anchor = GridBagConstraints.EAST;
resultsParameters.add(CloseDialogButton,gc);
CloseDialogButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
resultsParameters.dispose();
}
});
resultsParameters.setVisible(true);
resultsParameters.setLocationRelativeTo(this);
resultsParameters.setSize(270, 150);
resultsParameters.setResizable(false);
}
}
public class RecalibrationWorker extends JDialog {
private boolean isStarted = false;
private JLabel counterLabel = new JLabel("Recalibration not yet started");
private Worker worker = new Worker();
private JPanel recalibrationParameters;
private ButtonGroup radioButtonGroup = new ButtonGroup();
private JRadioButton rawSpectra = new JRadioButton("Use raw spectra");
private JRadioButton preprocessedSpectra = new JRadioButton("Use preprocessed spectra");
private static float commonMassThresholdValue;
private static float recalibrationThresholdValue;
private static double mergeSpectraThresholdValue;
private JLabel commonMassThresholdLabel = new JLabel("<html>Common Mass Window<br>(value between 0.01-0.9 Da)</html>");
private JTextField commonMassThresholdField = new JTextField(String.valueOf(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
commonMassThresholdValue = Float.parseFloat(commonMassThresholdField.getText());
recalibrationThresholdField.requestFocusInWindow();
}
}));
private JLabel recalibrationThresholdLabel = new JLabel("<html>Mass threshold to recalibrate two spectra<br>(value between 0.01-0.9 Da)</html>");
private JTextField recalibrationThresholdField = new JTextField(String.valueOf(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
recalibrationThresholdValue = Float.parseFloat(recalibrationThresholdField.getText());
mergeSpectraThresholdField.requestFocusInWindow();
}
}));
private JLabel mergeSpectraThresholdLabel = new JLabel("<html>Mass threshold to merge spectra<br>(value between 0.01-0.9 Da)</html>");
private JTextField mergeSpectraThresholdField= new JTextField(String.valueOf(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mergeSpectraThresholdValue = Float.parseFloat(mergeSpectraThresholdField.getText());
startButton.requestFocusInWindow();
}
}));
private JTextArea recalibrationStatus = new JTextArea(7,32);
private JScrollPane textAreaScrolling = new JScrollPane(recalibrationStatus);
private JButton startButton = new JButton(new AbstractAction("Recalibrate") {
#Override
public void actionPerformed(ActionEvent arg0) {
if(!isStarted) {
Worker w = new Worker();
w.addPropertyChangeListener(new RecalibrationWorkerPropertyHandler(RecalibrationWorker.this));
w.execute();
isStarted = false;
}
}
});
private JButton stopButton = new JButton(new AbstractAction("Stop") {
#Override
public void actionPerformed(ActionEvent arg0) {
worker.cancel(true);
}
});
public File file;
public String type;
public String resultFilePath;
public RecalibrationWorker(File dataFile, String recalibrationType) {
file = dataFile;
type = recalibrationType;
setLayout(new GridBagLayout());
if("CG".equals(recalibrationType))
setTitle("Crystal Growth Recalibration");
else if("TG".equals(recalibrationType))
setTitle("Topological Greedy Recalibration");
recalibrationParameters = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
radioButtonGroup.add(rawSpectra);
radioButtonGroup.add(preprocessedSpectra);
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(preprocessedSpectra,gc);
gc.gridx = 1;
gc.gridy = 0;
recalibrationParameters.add(rawSpectra,gc);
gc.gridx = 0;
gc.gridy = 1;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(commonMassThresholdLabel, gc);
commonMassThresholdLabel.setLabelFor(commonMassThresholdField);
commonMassThresholdField.setColumns(3);
commonMassThresholdField.setText("");
gc.gridx = 1;
gc.gridy = 1;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
recalibrationParameters.add(commonMassThresholdField, gc);
commonMassThresholdField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
commonMassThresholdValue = Float.parseFloat(commonMassThresholdField.getText());
recalibrationThresholdField.requestFocusInWindow();
}
});
gc.gridx = 0;
gc.gridy = 2;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(recalibrationThresholdLabel, gc);
recalibrationThresholdLabel.setLabelFor(recalibrationThresholdField);
recalibrationThresholdField.setColumns(3);
recalibrationThresholdField.setText("");
gc.gridx = 1;
gc.gridy = 2;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
recalibrationParameters.add(recalibrationThresholdField, gc);
recalibrationThresholdField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
recalibrationThresholdValue = Float.parseFloat(recalibrationThresholdField.getText());
mergeSpectraThresholdField.requestFocusInWindow();
}
});
gc.gridx = 0;
gc.gridy = 3;
gc.ipady = 20;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(mergeSpectraThresholdLabel, gc);
mergeSpectraThresholdLabel.setLabelFor(mergeSpectraThresholdField);
mergeSpectraThresholdField.setText("");
gc.gridx = 1;
gc.gridy = 3;
gc.ipady = 0;
gc.anchor = GridBagConstraints.CENTER;
recalibrationParameters.add(mergeSpectraThresholdField, gc);
mergeSpectraThresholdField.setColumns(3);
mergeSpectraThresholdField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
mergeSpectraThresholdValue = Double.parseDouble(mergeSpectraThresholdField.getText());
startButton.requestFocusInWindow();
}
});
recalibrationParameters.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Parameters"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
gc.gridx = 0;
gc.gridy = 4;
gc.anchor = GridBagConstraints.EAST;
recalibrationParameters.add(startButton, gc);
gc.gridx = 1;
gc.gridy = 4;
gc.anchor = GridBagConstraints.WEST;
recalibrationParameters.add(stopButton, gc);
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.CENTER;
add(recalibrationParameters, gc);
textAreaScrolling.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Recalibration status"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.CENTER;
add(textAreaScrolling, gc);
recalibrationStatus.setWrapStyleWord(true);
recalibrationStatus.setLineWrap(true);
recalibrationStatus.setEditable(false);
setVisible(true);
setLocationRelativeTo(this);
setSize(415, 425);
setResizable(false);
pack();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
// constructor
public RecalibrationWorker()
{
}
public float commonMassThreshold() {
return commonMassThresholdValue;
}
public float recalibrationThreshold() {
return recalibrationThresholdValue;
}
public double mergeSpectraThreshold() {
return mergeSpectraThresholdValue;
}
protected String processCompleted() {
return resultFilePath;
}
protected void processFailed() {
System.out.println("Recalibration failed");
}
class Worker extends SwingWorker<String,String> {
// String resultfilePath;
#Override
public String doInBackground() throws Exception {
InputData inputDataObject1 = new InputData();
if(type == "CG")
{
resultFilePath = inputDataObject1.startRecalibration(file, type);
publish("Recalibration Successful!\nFiles can be found at: " + resultFilePath);
}
else if (type == "TG")
{
resultFilePath = inputDataObject1.startRecalibration(file, type);
publish("Recalibration Successful!\nFiles can be found at: " + resultFilePath);
}
return resultFilePath;
}
public void done() {
try {
get();
} catch (Exception e) {
}
}
#Override
protected void process(java.util.List<String> chunks) {
String value = chunks.get(chunks.size() - 1);
recalibrationStatus.append("\n"+value);
// recalibrationStatus.append(chunks.toString());
}
}
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
/**
* Created by localadm on 27/09/15.
*/
public class RecalibrationWorkerPropertyHandler implements PropertyChangeListener {
private RecalibrationWorker rwObject;
public RecalibrationWorkerPropertyHandler(RecalibrationWorker rwObject) {
this.rwObject = rwObject;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
// System.out.println(evt.getPropertyName());
if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
// int value = (int) evt.getNewValue();
// rwObject.showProgress(value);
} else if ("state".equalsIgnoreCase(evt.getPropertyName())) {
SwingWorker worker = (SwingWorker) evt.getSource();
if (worker.isDone()) {
try {
worker.get();
System.out.println("I am here");
rwObject.processCompleted();
} catch (InterruptedException exp) {
rwObject.processFailed();
} catch (ExecutionException e) {
rwObject.processFailed();
}
}
}
}
}
Since you're using a JDialog to manage the SwingWorker, you can actual use the modal state of the dialog to you advantage.
Essentially, when a dialog is modal, it will block the code execution where the dialog is made visible. It will block until the dialog is hidden, at which time, the code will continue to execute.
So, you can disable the button before the dialog is made visible and re-enable it when it's closed.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Go");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
SomeWorkerDialog worker = new SomeWorkerDialog(TestPane.this);
// This is just so we can see the button ;)
Point point = btn.getLocationOnScreen();
worker.setLocation(worker.getX(), point.y + btn.getHeight());
worker.setVisible(true);
btn.setEnabled(true);
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class SomeWorkerDialog extends JDialog {
private JProgressBar progressBar;
private SomeWorkerSomeWhere worker;
public SomeWorkerDialog(JComponent parent) {
super(SwingUtilities.getWindowAncestor(parent), "Working Hard", DEFAULT_MODALITY_TYPE);
progressBar = new JProgressBar();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(10, 10, 10, 10);
add(progressBar, gbc);
worker = new SomeWorkerSomeWhere();
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
switch (name) {
case "state":
switch (worker.getState()) {
case DONE:
setVisible(false);
break;
}
break;
case "progress":
progressBar.setValue(worker.getProgress());
break;
}
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
worker.execute();
}
#Override
public void windowClosed(WindowEvent e) {
worker.cancel(true);
}
});
pack();
setLocationRelativeTo(parent);
}
}
public class SomeWorkerSomeWhere extends SwingWorker {
#Override
protected Object doInBackground() throws Exception {
for (int index = 0; index < 100 && !isCancelled(); index++) {
setProgress(index);
Thread.sleep(10);
}
return "AllDone";
}
}
}
Update
To get the value returned by the worked, you can add a method to the dialog which returns the calculated value...
public String getValue() throws Exception {
return worker.get()
}
So, once the dialog is closed and the execution of your code continues, you can enable the components you want and call the getValue method
You can also store the result when the state changes and the PropertyChangeListener is notified
The purpose of this program is to allow the tutor to keep a log of his/her students. I'm a newbie to GUI so my code probably isnt the best but I need help with the code for the JButton "SAVE" to take all the information in the log and store it in a .txt file. Line 374 is where my button command is.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
// Declare variables:
// array lists
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor"};
Object[][] data = new Object[25][5];
// table
JTable table = new JTable(data, columnNames) {
// sets the ability of the cells to be edited by the user
#Override
public boolean isCellEditable(int row, int column) {
return false; // returns false, cannot be edited
}
};
// frames
JFrame frame, frame1;
// panels
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
// labels
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp;
// text fields
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp;
// buttons
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
// additionals
int keyCode, rowIndex, rowNumber, noOfStudents;
// button handler
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
// setting/modifying table components
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
// main buttons
btnAdd = new JButton("ADD");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false); // disables the component
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false); // disables the component
btnSort = new JButton("SORT");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
// with button Listeners
// sub buttons
btnAddInput = new JButton("Add");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
// set label names
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("COURSE");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
// set text fields width
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15)); // limits the length of input:
// max of 15
txtID.addKeyListener(keyListener); // accepts only numerals
// main frame
// panel for the table
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
// panel for the main buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// positions the main buttons
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Student Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
// ADD frame
// panel for adding
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
// positions the components for adding
// labels
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
// panel for other necessary buttons
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}// end
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADD")) {
// text fields for Student input data
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + ""); // will preview the ID
// input during Add
txtName.setText(data[rowIndex][1] + ""); // will preview the Name
// input during Add
txtCourse.setText(data[rowIndex][2] + ""); // will preview the
// Course input during
// Add
txtProfessor.setText(data[rowIndex][3] + ""); // will preview the Year
// input during Add
txtHelp.setText(data[rowIndex][4] + ""); // will preview the
// Gender input during
// Add
txtID.setEditable(false); // forbids the user to edit the entered
// ID number
frame1.setTitle("Edit Student data"); // title bar name for edit
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true); // sets the visibility of frame1
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
} catch (FileNotFoundException ex) {
}
}else if (e.getActionCommand().equals("Edit2")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "INCOMPLETE INPUT.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
frame1.dispose();
}
table.updateUI();
} else if (e.getActionCommand().equals("Cancel")) {
frame1.dispose();
}
}
}// end
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
You need to call flush() method once at the end of printing content to file.
Like,
else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
out.flush();
} catch (FileNotFoundException ex) {
}
}
The java.io.Writer.flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
The print method will call write method in class PrintWriter, piece of source code is as follows:
/**
* Prints a String and then terminates the line. This method behaves as
* though it invokes <code>{#link #print(String)}</code> and then
* <code>{#link #println()}</code>.
*
* #param x the <code>String</code> value to be printed
*/
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
We can see in print() method, it will call write() method.
/**
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{#link #write(int)}</code> method.
*
* #param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
I am a student programmer and I really need to fix this code to able to finish my project.
Is there any other way to put a unique name to this for loop labels?
Because whenever a user click one of the labels, the text will change its color. Not all the labels, only the one that user had clicked.
public void addComponentsToPane(final JPanel pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setLayout(new GridBagLayout());
c.insets = new Insets(20, 20, 5, 5);
c.anchor = GridBagConstraints.NORTH;
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
int i;
for (i = 1; i <= 80; i++) {
if (z == 14) {
y++;
x = 0;
z = 0;
}
try {
label = new JLabel("# " + i);
labels();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = x;
c.gridy = y;
pane.add(label, c);
x++;
z++;
set_x = x;
set_y = y;
} catch (Exception e) {
}
}
tableNum = i;
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int UserInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Number of Table:"));
int i;
for (i = tableNum; i <= (tableNum + UserInput) - 1; i++) {
if (z == 14) {
set_y++;
set_x = 0;
z = 0;
}
try {
label = new JLabel("# " + i);
labels();
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = set_x;
c.gridy = set_y;
pane.add(label, c);
set_x++;
z++;
lbl[i] = label;
// lbl[i].setForeground(Color.red);
System.out.print(lbl[i].getText());
// set_x = x;
// set_y = y;
} catch (Exception ex) {
}
}
tableNum = i;
frame.revalidate();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "PLease Input Digits Only", "Input Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
private void labels() {
ImageIcon icon = new ImageIcon(imagePath + labelIconName);
icon.getImage().flush();
label.setIcon(icon);
label.setBackground(Color.WHITE);
label.setPreferredSize(new Dimension(80, 80));
label.setFont(new Font("Serif", Font.PLAIN, 18));
label.setForeground(Color.black);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
// label.setBorder(BorderFactory.createBevelBorder(0));
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// String[] option = {"Available", "Occupied", "Reserved"};
// choose = (String) JOptionPane.showInputDialog(this, "Table :"+label.getText() + , "Choose transaction", JOptionPane.INFORMATION_MESSAGE, null, option, option[0]);
System.out.print(label.getName());
centerScreen();
selectAllMenu();
jDialogMenu.show();
// frame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
}
});
}
i want to set a name for each of the panel. So i can set a foreground to each labels.
You don't need a unique name. You need to add a MouseListener to every label that you create. Then is the mousePressed() event you can change the foreground of the label clicked by using generic code. For example:
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
label.setForeground(...);
}
}
...
label.addMouseListener( ml );