How to put name to label? - java

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 );

Related

java Robot right click not working

I am building a virtual controller so a buddy with a disability can play PC games. WASD are working fine. But I also need it to simulate right-click. I have BUTTON3_DOWN_MASK in my mousePressed and mouseReleased events but it does not actually do anything.
My code is below. I know it is sloppy but I am trying to figure this out first:
public class GameController2 extends JFrame implements MouseListener, MouseMotionListener, ComponentListener{
public JLabel CoordsLabel;
public JLabel buttonWA;
public JLabel buttonW;
public JLabel buttonWD;
public JLabel buttonA;
public JLabel buttonD;
public JLabel buttonAS;
public JLabel buttonS;
public JLabel buttonSD;
public JFrame controlFrame;
public int mMovedX;
public int mMovedY;
public Robot robot;
public ImageIcon cIconOver, cIcon, rIcon, rIconOver, brIcon, brIconOver, bIcon, bIconOver, blIcon, blIconOver, lIcon, lIconOver, tlIcon, tlIconOver, tIcon, tIconOver, trIcon, trIconOver;
public int fWidth;
public int fHeight;
public ArrayList<JLabel> buttons;
public int gX = 0;
public int gY = 0;
public Icon origImg;
public GameController2(){
controlFrame = new JFrame();
GridBagLayout gridbag = new GridBagLayout();
controlFrame.setLayout(gridbag);
controlFrame.setSize(300,300);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
tlIcon = new ImageIcon("tlIconTest.png");
buttonWA = new JLabel();
buttonWA.setName("buttonWA");
//buttonWA.setBackground(Color.BLACK);
buttonWA.setOpaque(true);
buttonWA.addMouseListener(this);
buttonWA.addMouseMotionListener(this);
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
gridbag.setConstraints(buttonWA, c);
controlFrame.add(buttonWA);
buttonWA.setIcon(tlIcon);
tIcon = new ImageIcon("tIconTest.png");
buttonW = new JLabel("W");
buttonW.setName("buttonW");
buttonW.setBackground(Color.BLACK);
buttonW.setOpaque(true);
buttonW.addMouseListener(this);
buttonW.addMouseMotionListener(this);
c.gridx = 1;
c.gridy = 0;
gridbag.setConstraints(buttonW, c);
controlFrame.add(buttonW);
buttonW.setIcon(tIcon);
trIcon = new ImageIcon("trIconTest.png");
buttonWD = new JLabel("W+D");
buttonWD.setName("buttonWD");
buttonWD.setBackground(Color.BLACK);
buttonWD.setOpaque(true);
buttonWD.addMouseListener(this);
buttonWD.addMouseMotionListener(this);
c.gridx = 2;
c.gridy = 0;
gridbag.setConstraints(buttonWD, c);
controlFrame.add(buttonWD);
buttonWD.setIcon(trIcon);
lIcon = new ImageIcon("lIconTest.png");
buttonA = new JLabel("A");
buttonA.setName("buttonA");
buttonA.setBackground(Color.BLACK);
buttonA.setOpaque(true);
buttonA.addMouseListener(this);
buttonA.addMouseMotionListener(this);
c.gridx = 0;
c.gridy = 1;
gridbag.setConstraints(buttonA, c);
controlFrame.add(buttonA);
buttonA.setIcon(lIcon);
cIcon = new ImageIcon("rMouseOrig.png");
CoordsLabel = new JLabel();
CoordsLabel.setName("CoordsLabel");
//CoordsLabel.setBackground(Color.BLACK);
CoordsLabel.setOpaque(true);
CoordsLabel.addMouseListener(this);
CoordsLabel.addMouseMotionListener(this);
c.gridx = 1;
c.gridy = 1;
gridbag.setConstraints(CoordsLabel, c);
controlFrame.add(CoordsLabel);
CoordsLabel.setIcon(cIcon);
rIcon = new ImageIcon("rIconTest.png");
buttonD = new JLabel();
buttonD.setBackground(Color.BLACK);
buttonD.setOpaque(true);
buttonD.setName("buttonD");
buttonD.addMouseListener(this);
buttonD.addMouseMotionListener(this);
c.gridx = 2;
c.gridy = 1;
gridbag.setConstraints(buttonD, c);
controlFrame.add(buttonD);
buttonD.setIcon(rIcon);
blIcon = new ImageIcon("blIconTest.png");
buttonAS = new JLabel();
buttonAS.setBackground(Color.BLACK);
buttonAS.setOpaque(true);
buttonAS.setName("buttonAS");
buttonAS.addMouseListener(this);
buttonAS.addMouseMotionListener(this);
c.gridx = 0;
c.gridy = 2;
gridbag.setConstraints(buttonAS, c);
controlFrame.add(buttonAS);
buttonAS.setIcon(blIcon);
bIcon = new ImageIcon("bIconTest.png");
buttonS = new JLabel("S");
buttonS.setName("buttonS");
buttonS.setBackground(Color.BLACK);
buttonS.setOpaque(true);
buttonS.addMouseListener(this);
buttonS.addMouseMotionListener(this);
c.gridx = 1;
c.gridy = 2;
gridbag.setConstraints(buttonS, c);
controlFrame.add(buttonS);
buttonS.setIcon(bIcon);
brIcon = new ImageIcon("brIconTest.png");
buttonSD = new JLabel("");
buttonSD.setBackground(Color.BLACK);
buttonSD.setOpaque(true);
buttonSD.setName("buttonSD");
buttonSD.addMouseListener(this);
buttonSD.addMouseMotionListener(this);
c.gridx = 2;
c.gridy = 2;
gridbag.setConstraints(buttonSD, c);
//controlFrame.add(buttonSD);
buttonSD.setIcon(brIcon);
controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlFrame.setVisible(true);
controlFrame.setFocusableWindowState(false);
rIconOver = new ImageIcon("rIconOverTest.png");
brIconOver = new ImageIcon("brIconOverTest.png");
bIconOver = new ImageIcon("bIconOverTest.png");
blIconOver = new ImageIcon("blIconOverTest.png");
lIconOver = new ImageIcon("lIconOverTest.png");
tlIconOver = new ImageIcon("tlIconOverTest.png");
tIconOver = new ImageIcon("tIconOverTest.png");
trIconOver = new ImageIcon("trIconOverTest.png");
cIconOver = new ImageIcon("rMouseOver.png");
try{
robot = new Robot();
} catch (AWTException e){
e.printStackTrace();
}
}
#Override
public void componentResized(ComponentEvent e){
//
}
#Override
public void componentHidden(ComponentEvent e){
//
}
#Override
public void componentShown(ComponentEvent e){
//
}
#Override
public void componentMoved(ComponentEvent e){
//
}
#Override
public void mouseEntered(MouseEvent e){
JLabel label = (JLabel)e.getSource();
String name = label.getName();
if(name == "buttonSD"){
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_D);
origImg = buttonSD.getIcon();
buttonSD.setIcon(brIconOver);
} else if(name == "buttonS"){
robot.keyPress(KeyEvent.VK_S);
origImg = buttonS.getIcon();
buttonS.setIcon(bIconOver);
} else if (name == "buttonWD"){
robot.keyPress(KeyEvent.VK_D);
robot.keyPress(KeyEvent.VK_W);
origImg = buttonWD.getIcon();
buttonWD.setIcon(trIconOver);
} else if(name == "buttonW"){
robot.keyPress(KeyEvent.VK_W);
origImg = buttonW.getIcon();
buttonW.setIcon(tIconOver);
} else if(name == "buttonWA"){
robot.keyPress(KeyEvent.VK_W);
robot.keyPress(KeyEvent.VK_A);
origImg = buttonWA.getIcon();
buttonWA.setIcon(tlIconOver);
}else if(name == "buttonA"){
robot.keyPress(KeyEvent.VK_A);
origImg = buttonA.getIcon();
buttonA.setIcon(lIconOver);
} else if(name == "buttonAS"){
robot.keyPress(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_S);
origImg = buttonAS.getIcon();
buttonAS.setIcon(blIconOver);
} else if(name == "buttonD"){
robot.keyPress(KeyEvent.VK_D);
origImg = buttonD.getIcon();
buttonD.setIcon(rIconOver);
} else if(name == "CoordsLabel"){
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_D);
}
System.out.println(label);
}
#Override
public void mouseMoved(MouseEvent m){
//
}
#Override
public void mouseDragged(MouseEvent e){
//
}
#Override
public void mouseExited(MouseEvent e){
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_D);
if((JLabel)e.getSource() != CoordsLabel){
JLabel tmpLabel = (JLabel)e.getSource();
tmpLabel.setIcon(origImg);
}
}
#Override
public void mouseReleased(MouseEvent e){
robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
}
#Override
public void mousePressed(MouseEvent e){
robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
}
#Override
public void mouseClicked(MouseEvent e){
//
}
public static void main(String args[]){
new GameController2();
}
}
Actually, it is working. It can be seen if you add some debug information like this:
#Override
public void mouseReleased(MouseEvent e){
System.out.println("ReleasingMouseButton: " + e.getButton());
robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
}
#Override
public void mousePressed(MouseEvent e){
System.out.println("PressingMouseButton: " + e.getButton());
robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
}
Now if you click one of labels, you will see that you will be trapped in click-release event loop. So robot in fact is clicking for you like you wanted (or rather like you programmed it to do so).
Slice of output:
ReleasingMouseButton: 3 PressingMouseButton: 3 ReleasingMouseButton: 3
PressingMouseButton: 3 ReleasingMouseButton: 3 PressingMouseButton: 3
ReleasingMouseButton: 3 PressingMouseButton: 3 ReleasingMouseButton: 3
PressingMouseButton: 3 ReleasingMouseButton: 3 PressingMouseButton: 3
ReleasingMouseButton: 3 PressingMouseButton: 3 ReleasingMouseButton: 3
PressingMouseButton: 3 ReleasingMouseButton: 3 PressingMouseButton: 3
ReleasingMouseButton: 3 PressingMouseButton: 3 ReleasingMouseButton: 3
PressingMouseButton: 3
I doubt that this is what you wanted, so you will need to add some extra logic to it (eg, checking which mouse button was clicked)

I can't make my program to wait until GUI has finished gathering requested info (Java)

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?

Issue with KeyListener

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

Application not displaying GUI and won't quit Java

So I'm creating a game in Java and I ran into a little problem. Whenever I run the application the GUI does not show on the screen and the only way to close the application is to use the Windows Task Manager. In the application, you choose a username and click an enter button which creates a new window in which the game is played. But after you click the button, none of the GUI loads and you can't close the application.
Basically, when you click the button, a method is called that disposes the current window and starts the game window. The code for that method is below:
public void login(String name) {
String[] args={};
dispose();
SingleplayerGUI.main(args);
}
And here is the code of the SingleplayerGUI class:
public SingleplayerGUI(String userName, Singleplayer sp) {
this.userName = userName;
setResizable(false);
setTitle("Console Clash Singleplayer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(880, 550);
setLocationRelativeTo(null);
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
} catch (IOException e1) {
e1.printStackTrace();
}
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 28, 815, 30, 7 }; // SUM = 880
gbl_contentPane.rowHeights = new int[] { 25, 485, 40 }; // SUM = 550
contentPane.setLayout(gbl_contentPane);
history = new JTextPane();
history.setEditable(false);
JScrollPane scroll = new JScrollPane(history);
caret = (DefaultCaret) history.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.insets = new Insets(0, 0, 5, 5);
scrollConstraints.fill = GridBagConstraints.BOTH;
scrollConstraints.gridx = 0;
scrollConstraints.gridy = 0;
scrollConstraints.gridwidth = 2;
scrollConstraints.gridheight = 2;
scrollConstraints.weightx = 1;
scrollConstraints.weighty = 1;
scrollConstraints.insets = new Insets(0, 0, 5, -64);
contentPane.add(scroll, scrollConstraints);
txtMessage = new JTextField();
txtMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
}
});
GridBagConstraints gbc_txtMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(0, 0, 0, 25);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(txtMessage, gbc_txtMessage);
chat = new JTextPane();
chat.setEditable(false);
JScrollPane chatscroll = new JScrollPane(chat);
caret = (DefaultCaret) chat.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints chatscrollConstraints = new GridBagConstraints();
chatscrollConstraints.insets = new Insets(0, 0, 5, 5);
chatscrollConstraints.fill = GridBagConstraints.BOTH;
chatscrollConstraints.gridx = 0;
chatscrollConstraints.gridy = 0;
chatscrollConstraints.gridwidth = 2;
chatscrollConstraints.gridheight = 2;
chatscrollConstraints.weightx = 1;
chatscrollConstraints.weighty = 1;
chatscrollConstraints.insets = new Insets(150, 600, 5, -330);
contentPane.add(chatscroll, chatscrollConstraints);
chatMessage = new JTextField();
final String name = this.userName;
chatMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
chatconsole(name + ": " + chatMessage.getText());
}
}
});
GridBagConstraints gbc_chatMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(000, 600, 000, -330);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(chatMessage, gbc_txtMessage);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
});
GridBagConstraints gbc_btnSend = new GridBagConstraints();
gbc_btnSend.insets = new Insets(0, 0, 0, 275);
gbc_btnSend.gridx = 2;
gbc_btnSend.gridy = 2;
gbc_btnSend.weightx = 0;
gbc_btnSend.weighty = 0;
contentPane.add(btnSend, gbc_btnSend);
list = new JList();
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 600, 330, -330);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
gbc_list.gridwidth = 2;
gbc_list.gridheight = 2;
JScrollPane p = new JScrollPane();
p.setViewportView(list);
contentPane.add(p, gbc_list);
list.setFont(new Font("Verdana", 0, 24));
System.out.println("HEY");
setVisible(true);
new SwingWorker<Void, String>() {
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()) {
String line = s.nextLine();
publish(line);
}
return null;
}
#Override protected void process(java.util.List<String> chunks) {
for (String line : chunks) {
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), line + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
}
}.execute();
Singleplayer spp = new Singleplayer();
Singleplayer.startOfGame();
setVisible(true);
}
public static void console(String message, Color color) {
txtMessage.setText("");
try {
StyledDocument doc = history.getStyledDocument();
Style style = history.addStyle("", null);
StyleConstants.setForeground(style, color);
doc.insertString(doc.getLength(), message + "\r\n", style);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void console(String message) {
txtMessage.setText("");
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public void chatconsole(String message) {
chatMessage.setText("");
try {
Document doc = chat.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void single() {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
public static void main(String[] args) {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
And the singleplayer class:
public static void startOfGame(){
System.out.println("HEY");
SingleplayerGUI.console("Welcome to Console Clash Pre Alpha Version 1!");
SingleplayerGUI.console("Created by Drift");
SingleplayerGUI.console("Published by Boring Games");
SingleplayerGUI.console("");
SingleplayerGUI.console("");
menuScreen();
}
static void menuScreen() {
Scanner scan = new Scanner(System.in);
System.out.println("To play the game, type 'start'. To quit, type 'quit'.");
String menu = scan.nextLine();
if (menu.equals("start")) {
start();
} else if (menu.equals("quit")) {
quit();
} else {
menuScreen();
}
}
private static void quit() {
SingleplayerGUI.console("You quit the game.");
}
private static void start() {
SingleplayerGUI.console("You started the game.");
}
So far I've figured out that the problem most likey occurs when adding the outPipe to the console. Would I be able to fix this or am I just not able to use outPipes with this application?
Thanks in advance for your help.
The setVisible() method is invoked twice.. Remove the second setVisible() call after the Singleplayer.startOfGame(); line in SingleplayerGUI constructor.

Tutoring Log, Confuse don code for a JButton

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);
}

Categories