java Robot right click not working - java

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)

Related

JPanel is SOMETIMES not responding to mouse clicks

I have some custom JPanels that are used as buttons. This works well 90% of the time, however, sometimes the GUI doesn't respond to a mouse click - the mouseClicked event is not triggered and you have to click again (sometimes even more than once) to actually trigger it.
This behavior appears to be random, though I have the feeling that it occurs more frequently after having moved the frame to another monitor.
Here is the code:
public class EatingMouse extends JFrame implements MouseListener {
JPanel contentPane;
int contentPanelWidth, contentPanelHeight;
int mainTabMarginHeight, mainTabMarginWidth;
int subTabMarginHeight, subTabMarginWidth;
Color fontColor = Color.WHITE;
Color tabBackgroundColor = Color.BLACK;
Color tabBackgroundHighlightColor = Color.GRAY;
Color tabBackgroundSelectedColor = Color.LIGHT_GRAY;
TabPanel firstMainTab;
TabPanel secondMainTab;
ArrayList<TabPanel> firstSubTabs;
ArrayList<TabPanel> secondSubTabs;
ArrayList<TabPanel> currentSubTabs;
int clickCounter;
public EatingMouse() {
super("Why do you eat mouse clicks?");
JLayeredPane layeredPane = new JLayeredPane();
firstMainTab = new TabPanel("First Tab", 18);
firstMainTab.addMouseListener(this);
layeredPane.add(firstMainTab, new Integer(100));
secondMainTab = new TabPanel("Second Tab", 18);
secondMainTab.addMouseListener(this);
layeredPane.add(secondMainTab, new Integer(100));
firstSubTabs = new ArrayList<>();
secondSubTabs = new ArrayList<>();
currentSubTabs = new ArrayList<>();
TabPanel tp = new TabPanel("First First Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
firstSubTabs.add(tp);
tp = new TabPanel("Second First Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
firstSubTabs.add(tp);
tp = new TabPanel("First Second Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
secondSubTabs.add(tp);
tp = new TabPanel("Second Second Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
secondSubTabs.add(tp);
contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
contentPane.add(layeredPane);
mainTabMarginWidth = 40;
mainTabMarginHeight = 8;
subTabMarginWidth = 20;
subTabMarginHeight = 10;
selectTabs(0, 1);
clickCounter = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(800, 600));
setVisible(true);
}
public void selectTabs(int mainTab, int subTab) {
boolean hasChanged = false;
if((mainTab == 0) && !firstMainTab.isSelected) {
hasChanged = true;
firstMainTab.setSelected(true);
secondMainTab.setSelected(false);
for(TabPanel tp : currentSubTabs) {
tp.setSelected(false);
tp.setVisible(false);
}
currentSubTabs = firstSubTabs;
for(TabPanel tp : currentSubTabs) {
tp.setVisible(true);
}
currentSubTabs.get(subTab).setSelected(true);
}
else if((mainTab == 1) && !secondMainTab.isSelected) {
hasChanged = true;
firstMainTab.setSelected(false);
secondMainTab.setSelected(true);
for(TabPanel tp : currentSubTabs) {
tp.setSelected(false);
tp.setVisible(false);
}
currentSubTabs = secondSubTabs;
for(TabPanel tp : currentSubTabs) {
tp.setVisible(true);
}
currentSubTabs.get(subTab).setSelected(true);
}
else if((mainTab == 0) && firstMainTab.isSelected) {
hasChanged = true;
for(TabPanel tp : currentSubTabs) {
if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); }
else { tp.setSelected(true); }
}
}
else if((mainTab == 1) && secondMainTab.isSelected) {
hasChanged = true;
for(TabPanel tp : currentSubTabs) {
if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); }
else { tp.setSelected(true); }
}
}
if(hasChanged) {
revalidate();
repaint();
}
}
#Override
public void paint(Graphics graphics) {
super.paint(graphics);
contentPanelWidth = getContentPane().getWidth();
contentPanelHeight = getContentPane().getHeight();
int xOffset = 100;
int yOffset = 100;
FontMetrics mainTabMetrics = graphics.getFontMetrics(firstMainTab.label.getFont());
firstMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(firstMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight));
xOffset += firstMainTab.getBounds().width;
secondMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(secondMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight));
FontMetrics subTabMetrics = graphics.getFontMetrics(currentSubTabs.get(0).label.getFont());
xOffset = 100;
yOffset += firstMainTab.getBounds().height;
for(TabPanel tp : currentSubTabs) {
tp.setBounds(xOffset, yOffset, (subTabMetrics.stringWidth(tp.text) + subTabMarginWidth), (subTabMetrics.getHeight() + subTabMarginHeight));
tp.revalidate();
tp.repaint();
xOffset += tp.getBounds().width;
}
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("click " + clickCounter++);
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) {
secondMainTab.setSelected(false);
if(currentSubTabs.get(1).isSelected) { selectTabs(0, 1); }
else { selectTabs(0, 0); }
}
else if(source == secondMainTab && !secondMainTab.isSelected) {
if(currentSubTabs.get(1).isSelected) { selectTabs(1, 1); }
else { selectTabs(1, 0); }
}
}
#Override
public void mouseEntered(MouseEvent e) {
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundHighlightColor); }
else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundHighlightColor); }
else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) {
((TabPanel)source).setBackground(tabBackgroundHighlightColor);
}
}
#Override
public void mouseExited(MouseEvent e) {
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundColor); }
else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundColor); }
else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) {
((TabPanel)source).setBackground(tabBackgroundColor);
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
public class TabPanel extends JPanel {
JLabel label;
String text;
boolean isSelected;
public TabPanel(String labelText, int fontSize) {
super();
text = labelText;
isSelected = false;
setLayout(new GridBagLayout());
setBackground(tabBackgroundColor);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.1;
gbc.weightx = 0.1;
gbc.insets = new Insets(0,0,0,0);
label = new JLabel("<html><div style=\"text-align:center\"> " + text + "</div></html>", SwingConstants.CENTER);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
label.setForeground(fontColor);
label.setFont(new Font("Arial", Font.BOLD, fontSize));
add(label, gbc);
}
public void setSelected(boolean selected) {
isSelected = selected;
if(selected) { setBackground(tabBackgroundSelectedColor); }
else { setBackground(tabBackgroundColor); }
}
public boolean isSelected() { return isSelected; }
#Override
public String toString() {
return text + " - " + label.getFont().getSize();
}
}
public static void main(String[] args) {
new EatingMouse();
}
}
Please note that I have chosen JPanels as buttons because I want to heavily customize them later, which I didn't get to work with extending JButton.
Thank you for your time reading this and of course I would appreciate any leads on why this is happening and what I can do to improve this code.

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?

Java Tetris 2 player multiplayer GUI not working properly

basically i am working on a tetris game and i want to implement a 2 player versus mode.
for now i have a working single player and now i want to make a gui for a 2 player multiplayer. (i will make a second keylistener and a endGame condition later)
however, when i add both gamepanels (what displays the state of the game after retreiving the state of the game from the boardhandler (1 or 2 depending on which player)) i dont get a correct display/gui.
this is what it looks like:
https://gyazo.com/58f37beab249c975cd4acdb8ae0e0154
this is what it should look like (but i want 2 boards displayed since this screenshot is from singleplayerwindow):
https://gyazo.com/4aecf061109844504a05387fb3d39e8f
anyone know what i am doing wrong and/or how i could fix it ?
thank you <3
package gui;
import tetris.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class MultiPlayerWindow extends JPanel
{
private GameLoop gameLoop1 ;
private GameLoop gameLoop2 ;
private boolean gameLoopHasStarted1 ;
private boolean gameLoopHasStarted2 ;
private BoardHandler bh1 ;
private BoardHandler bh2 ;
private HighScoreList highScoreList;
private HumanInput inputController ;
private HumanInput inputController2 ;
private JPanel scorePanel;
private JPanel rightPanel;
public MultiPlayerWindow( MainMenu mainMenu ){
//create the variables
Board board1 = new Board(10 , 20 ) ;
Board board2 = new Board(10 , 20 ) ;
final HumanInput inputController1 = new HumanInput() ;
final HumanInput inputController2 = new HumanInput() ;
this.bh1 = new BoardHandler(board1 , true) ;
this.bh2 = new BoardHandler(board2 , true) ;
this.highScoreList = new HighScoreList() ;
//behaviour
this.addKeyListener(inputController1);
this.addKeyListener(inputController2);
this.setFocusable(true);
this.requestFocusInWindow() ;
this.setLayout(new GridBagLayout());
//create panels
scorePanel = new JPanel() ;
scorePanel.setLayout(new GridBagLayout());
scorePanel.setSize(Config.LEFTPANEL_SIZE);
rightPanel = new JPanel() ;
rightPanel.setLayout(new GridBagLayout());
rightPanel.setSize(Config.RIGHTPANEL_SIZE);
//create the ScoreBoard
final ScoreBoard scoreBoard = new ScoreBoard() ;
GridBagConstraints d = new GridBagConstraints() ;
d.gridx = 0 ;
d.gridy = 0 ;
scorePanel.add(scoreBoard , d) ;
d.insets = new Insets(30,10,10,0);
//add a timer to update ScoreBoard
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Trying to update score");
scoreBoard.setScore(gameLoop1.getScore());
scoreBoard.setScore(gameLoop2.getScore());
}
}).start();
//create the Highscore Board
HighScoreBoard highScoreBoard = new HighScoreBoard(highScoreList);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.insets = new Insets(30,10,10,0);
scorePanel.add(highScoreBoard, d);
//create the combobox to choose between tetris and pentris
String[] optionStrings = {"Tetris", "Pentris"};
final JComboBox optionList = new JComboBox(optionStrings);
optionList.setSelectedIndex(0);
optionList.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(optionList.getSelectedIndex() == 0)
{
bh1.switchToTetris();
bh2.switchToTetris();
}
else if(optionList.getSelectedIndex() == 1)
{
bh1.switchToPentris();
bh2.switchToPentris();
}
}
});
optionList.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
optionList.requestFocus();
}
#Override
public void focusLost(FocusEvent e) {
}
});
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 2;
d.weightx = 0.5;
d.insets = new Insets(30,10,10,0);
scorePanel.add(optionList, d);
//add the scorePanel
d = new GridBagConstraints();
d.gridx = 1;
d.gridy = 0;
this.add(scorePanel, d);
final GamePanel gamePanel1 = new GamePanel(board1);
final GamePanel gamePanel2 = new GamePanel(board2);
gamePanel1.setSize(Config.GAMEPANEL_SIZE);
gamePanel2.setSize(Config.GAMEPANEL_SIZE);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 0;
this.add(gamePanel1, d);
d = new GridBagConstraints();
d.gridx = 2;
d.gridy = 0;
this.add(gamePanel2, d);
//set the Thread
gameLoop1 = new GameLoop(bh1, inputController1, gamePanel1, highScoreList);
gameLoop2 = new GameLoop(bh2, inputController2, gamePanel2, highScoreList);
gameLoop1.start();
gameLoop2.start();
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
//add the buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(30);
buttonPanel.setLayout(new GridLayout(3,1,10,10));
d = new GridBagConstraints();
d.gridx = 0;
d.weightx = 0.2;
d.gridy = 0;
d.insets = new Insets(200,20,0,20);
rightPanel.add(buttonPanel, d);
//backbutton
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.anchor = GridBagConstraints.SOUTH;
d.insets = new Insets(20, 20, 0, 20);
rightPanel.add(new BackButton(mainMenu), d);
//add the right panel
d = new GridBagConstraints();
d.gridx = 3;
d.gridy = 0;
this.add(rightPanel, d);
final JButton startButton = new JButton("Start");
startButton.requestFocus(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoopHasStarted1 && !gameLoopHasStarted2)
{
try{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run(){
gameLoopHasStarted1 = true;
gameLoopHasStarted2 = true;
gameLoop1.startNewGame();
gameLoop2.startNewGame();
optionList.setEnabled(false);
requestFocusInWindow();
startButton.setEnabled(false);
}
});
}
catch(Exception expenction)
{
expenction.printStackTrace();
}
}
}
});
buttonPanel.add(startButton);
//pause button
final JButton pauseButton = new JButton("Pause ");
buttonPanel.add(pauseButton);
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoop1.isPaused() && !gameLoop2.isPaused()) {
gameLoop1.setPaused(true);
gameLoop2.setPaused(true);
pauseButton.setText("Unpause");
}
else if(gameLoop1.isPaused()&& gameLoop2.isPaused())
{
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause ");
}
}
});
//reset button
JButton resetButton = new JButton("Reset");
buttonPanel.add(resetButton);
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bh1.resetBoard();
bh2.resetBoard();
optionList.setEnabled(true);
if(gameLoop1.isRunning() && gameLoop2.isRunning())
{
gameLoop1.apruptGameEnd();
gameLoop2.apruptGameEnd();
}
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
gamePanel1.repaint();
gamePanel2.repaint();
startButton.setEnabled(true);
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause");
scoreBoard.setScore(0);
}
});
//focuslistener for inputController
this.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
requestFocusInWindow();
}
});
}
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
}
fixed it.
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
this last part was what was messing it up, the rest of the code works fine but was previously then (for some tbh unknown reason) messed up by this. not 100% sure why...

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

How to put name to label?

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

Categories