Ok, So I make a JToggleButton:
JToggleButton button = new JToggleButton(new ImageIcon(features[i].getImage())) {
private static final long serialVersionUID = 1L;
#Override
public void paint(Graphics g) {
super.paint(g);
if (isSelected()) {
g.setColor(Color.RED);
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
}
}
};
try {
if (bodyButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getBody().getImage())) {
button.setSelected(true);
}
} else if (eyesButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getEyes().getImage())) {
button.setSelected(true);
}
} else if (glassesButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getGlasses().getImage())) {
button.setSelected(true);
}
} else if (hairButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getHair().getImage())) {
button.setSelected(true);
}
} else if (pantsButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getPants().getImage())) {
button.setSelected(true);
}
} else if (shirtButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getShirt().getImage())) {
button.setSelected(true);
}
} else if (shoesButton.isSelected()) {
if (equals(features[i].getImage(), avatar.getShoes().getImage())) {
button.setSelected(true);
}
}
} catch (Exception e) {}
But I am having problems with it not painting. I setting selected true right after its institated as you can see, but its not painting the button SOMETIMES, Other times it work GREAT! Iknow that it is being set to true because I added a after it.
System.out.println(button.isSelected() + " " +i);
I might override paintComponent() in JToggleButton, or perhaps just use setIcon().
Addendum: Be sure you're running on the EDT and overriding paintComponent() correctly. The following short, complete, compilable example (sscce) works reliably for me. As #camickr suggested, creating an sscce may help isolate a problem you encounter.
import java.awt.*;
import javax.swing.*;
public class NewMain extends JPanel {
public NewMain() {
super(true);
JToggleButton button = new JToggleButton(new ImageIcon("test.gif")) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
}
};
this.add(button);
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(2, 2));
for (int i = 0; i < 4; i++) {
f.add(new NewMain());
}
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
}
I think I stumbled across your problem while trying to solve one of mine. Since you are using setSelected() to change the state of the button, be sure to use setSelectedIcon() to change the icon displayed when selected. You can set it to the same value as setIcon() with expected results.
Related
I'm new to Stackoverflow and tried to follow the rules as much as possible. I haven't been able to solve this problem for hours. When I start the program it seldom starts strangely:
properly started: correct image:
not properly started: white screen:
If you see an error in the code and help me fix it I would appreciate it. any correction
public class MainClass extends JPanel implements Runnable, MouseListener {
enum MenuState {
xMenu1, xMenu2;
}
private MenuState menuState = MenuState.xMenu1;
JFrame frame;
private Image bgImage, playButtonImage, backButtonImage;
private Rectangle playButton, backButton;
public MainClass() {
frame = new JFrame("TEST");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.BLACK);
frame.setFocusable(true);
frame.addMouseListener(this);
frame.add(this);
try {
bgImage = ImageIO.read(getClass().getResourceAsStream("/Data/background.png"));
playButtonImage = ImageIO.read(getClass().getResource("/Data/playButton2.png"));
backButtonImage = ImageIO.read(getClass().getResource("/Data/backButton.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playButton = new Rectangle(900, 400, 214, 78);
backButton = new Rectangle(5, 5, 136, 92);
Thread thread = new Thread(this);
thread.start();
System.out.println("thread started");
}
public static void main(String[] args) {
new MainClass();
}
#Override
public void run() {
while (true) {
System.out.println("run method started");
if (menuState == menuState.xMenu1) {
} else if (menuState == menuState.xMenu2) {
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void paint(Graphics g) {
if (menuState == menuState.xMenu1) {
g.drawImage(playButtonImage, playButton.x, playButton.y, this); // THIS IS THE 77th LINE
} else if (menuState == menuState.xMenu2) {
g.drawImage(bgImage, 0, 0, this);
g.drawImage(backButtonImage, backButton.x, backButton.y, this);
}
}
#Override
public void mousePressed(MouseEvent e) {
if (menuState == menuState.xMenu1) {
if (playButton.intersects(e.getX(), e.getY(), 1, 1)) {
menuState = menuState.xMenu2;
}
} else if (menuState == menuState.xMenu2) {
if (backButton.intersects(e.getX(), e.getY(), 1, 1)) {
menuState = menuState.xMenu1;
}
}
}
}
I would like to make my JToolBar impossible to detach from its container but still let the user drag it to one of the container's sides.
I know about
public void setFloatable( boolean b )
but this won't allow the user to move the JToolBar at all.
Is there any way of doing this without overwriting ToolBarUI?
Also, is there an option to highlight its new position before dropping it?
It's not the most elegant solution, but it works.
public class Example extends JFrame {
BasicToolBarUI ui;
Example() {
JToolBar tb = new JToolBar();
tb.add(new JButton("AAAAA"));
tb.setBackground(Color.GREEN);
ui = (BasicToolBarUI) tb.getUI();
getContentPane().addContainerListener(new Listener());
getContentPane().add(tb, BorderLayout.PAGE_START);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
class Listener implements ContainerListener {
#Override
public void componentAdded(ContainerEvent e) {}
#Override
public void componentRemoved(ContainerEvent e) {
if (ui.isFloating()) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ui.setFloating(false, null);
}
});
}
}
}
public static void main(String[] args) {
new Example();
}
}
Explanation:
Whenever the toolbar is moving to a floating state, it is instructed not do so. The only problem is that you have to wait for the EDT to finish the process for creating the floating window, and only then can you tell it not to float. The result is that you actually see the window created and then hidden.
Note:
I think that overriding the UI for the toolbar is a better solution, though it's possible that with a more intricate approach doing something similar to what I did will also work well.
works for me quite correctly on WinOS, old code from SunForum
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CaptiveToolBar {
private Robot robot;
private JDialog dialog;
private JFrame frame;
public static void main(String[] args) {
//JFrame.setDefaultLookAndFeelDecorated(true);
//JDialog.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CaptiveToolBar().makeUI();
}
});
}
public void makeUI() {
try {
robot = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
final JToolBar toolBar = new JToolBar();
for (int i = 0; i < 3; i++) {
toolBar.add(new JButton("" + i));
}
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.add(toolBar, BorderLayout.NORTH);
final ComponentListener dialogListener = new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
dialog = (JDialog) e.getSource();
setLocations(false);
}
};
toolBar.addHierarchyListener(new HierarchyListener() {
#Override
public void hierarchyChanged(HierarchyEvent e) {
Window window = SwingUtilities.getWindowAncestor(toolBar);
if (window instanceof JDialog) {
boolean listenerAdded = false;
for (ComponentListener listener : window.getComponentListeners()) {
if (listener == dialogListener) {
listenerAdded = true;
break;
}
}
if (!listenerAdded) {
window.addComponentListener(dialogListener);
}
}
}
});
frame.addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
if (dialog != null && dialog.isShowing()) {
setLocations(true);
}
}
});
frame.setVisible(true);
}
private void setLocations(boolean moveDialog) {
int dialogX = dialog.getX();
int dialogY = dialog.getY();
int dialogW = dialog.getWidth();
int dialogH = dialog.getHeight();
int frameX = frame.getX();
int frameY = frame.getY();
int frameW = frame.getWidth();
int frameH = frame.getHeight();
boolean needToMove = false;
if (dialogX < frameX) {
dialogX = frameX;
needToMove = true;
}
if (dialogY < frameY) {
dialogY = frameY;
needToMove = true;
}
if (dialogX + dialogW > frameX + frameW) {
dialogX = frameX + frameW - dialogW;
needToMove = true;
}
if (dialogY + dialogH > frameY + frameH) {
dialogY = frameY + frameH - dialogH;
needToMove = true;
}
if (needToMove) {
if (!moveDialog && robot != null) {
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
dialog.setLocation(dialogX, dialogY);
}
}
}
I'm creating a basic program that is to make a "life bar" that fills when you press the space bar, and when you get to the maximum, you win. Every second it decreases, so just spam the space bar to win. It's in attempt to test for a basic game throug java. My program is caught at this error, giving it a runtime error that I'm unfamiliar with. Here is my code:
import javax.swing.JOptionPane;
import javax.swing.*;
import java.util.*;
import static java.lang.System.*;
import static java.lang.Math.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*; //for files
public class clicker
{
public static void main(String args[])
{
new Clicker(); //Make a window
}
}
class Clicker extends Frame implements KeyListener, MouseListener
{
// global variables
private final static int SCHEIGHT=768,SCWIDTH=1024;
// direction constants
final static int N = 0,NE = 1,E = 2,SE = 3, S = 4, SW = 5, W = 6, NW =7,STILL = 8;
// movement change constants
final int X = 0,Y = 1,Z = 2;
final int TITLE = 30, STATUS = 40;
final static int size = 2;
Image myPic;
private boolean gameNotOver = true;
private boolean keyPressed = false;
private Image myScreen;
private int whichScreen;
private int numScreen;
private int timer;
private int amt;
public Clicker()
{
setSize(SCWIDTH,SCHEIGHT);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
this.setVisible(true);
gameLoop();
}
public void gameLoop()
{
do
{
if (keyPressed)
{
amt++;
out.println(keyPressed + " " +gameNotOver+" "+ "Time "+timer);
this.repaint();
keyPressed = false;
}
if(amt >= 450)
gameNotOver = false;
this.setVisible(true);
//this.repaint();
pause(30);
}
while (gameNotOver);
if(!gameNotOver)
{
pause(5000);
System.exit(0);
}
}
public int getAmt()
{
return amt;
}
public void paint(Graphics pen)
{
if(whichScreen==0)
{
pen.drawImage(myPic,100,200,506,279,this); //Draws the image
pen.setFont(new Font("Timesroman", Font.ITALIC, 50));
pen.drawString("Welcome to the Clicker Test", 200, 75);
pen.setFont(new Font("Timesroman", Font.ITALIC, 40));
pen.drawString("Created by Cody Coulter",150,150);
pen.setFont(new Font("Timesroman", Font.ITALIC, 25));
pause(2000); // 2000 final
whichScreen++;
}
else
{
myScreen =createImage(getSize().width,getSize().height);
Graphics o = myScreen.getGraphics();
doubleBuffer(o);
pen.drawImage(myScreen,0,0,this);
}
}
public void doubleBuffer(Graphics pen) // Draws the window
{
pause (500);
numScreen++;
if (numScreen > 0)
{
setBounds(0,0,SCWIDTH,SCHEIGHT);
Color HPRed = new Color(213, 0, 0);
pen.setColor(Color.BLACK);
setTitle("Clicker Test -- Cody Coulter."+
" To click, press the space bar");
pen.setFont(new Font("Timesroman",Font.PLAIN,48));
pen.drawString("Clicker Test ",350,75);
pen.setFont(new Font("TimesRoman",Font.BOLD,33));
pen.fillRect((SCWIDTH/4), (SCHEIGHT/3), 50, 500);
pen.setColor(HPRed);
pen.fillRect((SCWIDTH/4)-5, (SCHEIGHT/3)+5, 40, amt);
if(!gameNotOver)
{
if(amt > 100)
{
pen.setColor(HPRed);
pen.fillRect(SCWIDTH/4-75, SCHEIGHT/3, SCWIDTH/2+150, SCHEIGHT/3-60);
pen.setColor(Color.GRAY);
pen.fillRect(SCWIDTH/4-65, SCHEIGHT/3+10, SCWIDTH/2+130, SCHEIGHT/3-80);
pen.setColor(Color.YELLOW);
pen.setFont(new Font("Verdana", Font.BOLD, 40));
pen.drawString("You got it!", SCWIDTH/2-290, SCHEIGHT/2-20);
}
}
this.repaint();
}
}
public void keyPressed(KeyEvent e)
{
keyPressed = true;
setTitle(""+ KeyEvent.getKeyText(e.getKeyCode()));
System.out.println("hit + "+ KeyEvent.getKeyText(e.getKeyCode())+ " " + keyPressed);
switch(e.getKeyCode())
{
case KeyEvent.VK_SPACE: amt= amt + 4;
break;
}
}
public void mouseClicked(MouseEvent m)
{
}
public void mouseEntered(MouseEvent m)
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void update(Graphics G)
{
paint(G);
}
public static void pause (long r)
{
try
{
Thread.sleep(r);
}
catch (Exception e)
{
out.println(" sleep error " + e);
}
}
}
I'm new to this forum board, and I am most likely using arbitrary information to solve this particular problem, and am new to programming in general. Any insight, or how to narrow the question would be greatly appreciated.
Again, the error stated is "Exception in thread "main" java.lang.NoClassDefFoundError: clicker (wrong name: Clicker)
Thank You
public class clicker
{
public static void main(String args[])
{
new Clicker(); //Make a window
}
}
You're essentially declaring your class twice. Take the main function and put it in your other clicker class, and delete the lower case one.
class Clicker extends Frame implements KeyListener, MouseListener
{
public static void main(String args[])
{
new Clicker(); //Make a window
}
//.....rest of class.....
}
You main() method should be placed in the Clicker class.
So the solution is :
class Clicker extends Frame implements KeyListener, MouseListener
{
public static void main(String args[])
{
new Clicker(); // Make a window
}
...
}
Also, make sure that your file is named Clicker.java, to match your class's name.
public Clicker(){
setSize(SCWIDTH,SCHEIGHT);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
this.setVisible(true);
//ADD THIS
this.addKeyListener(this);
this.addMouseListener(this);
gameLoop();
}
I want to make a slider in Java, similar to JSlider, but it can have muliple sliders within itself. To be precise, I want to implement the slider used in Fixed Width Functionality in Microsoft Excel(From Data-> Fixed Width).
A normal slider has just one point, which we can drag to various positions. Now if i click within a position at a slider, a new point should get added, and the dragging operation of this point should be independent of the previous ones. Also if I do a double click, the point is removed from the slider.
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.plaf.basic.BasicSliderUI;
public class MultiSlider extends JComponent
{
public static void main(String[] args)
{ // main method just for showing a usage example
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
catch(Exception ex){}
JFrame f=new JFrame();
final MultiSlider slider = new MultiSlider();
slider.setValue(0, 80);
slider.addValue(20);
f.getContentPane().add(slider);
f.setSize(200, 100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public MultiSlider()
{
super.setLayout(null);
addSlider(0);
}
public void setValue(int slider, int value)
{
((JSlider)getComponent(slider)).setValue(value);
}
public void addValue(int value)
{
addSlider(value);
}
#Override
public boolean isOptimizedDrawingEnabled()
{
return false;
}
#Override
public void doLayout()
{
Insets i=getInsets();
int x=i.left, y=i.top, width=getWidth()-x-i.right, height=getHeight()-y-i.bottom;
for(int ix=0, n=getComponentCount(); ix<n; ix++)
getComponent(ix).setBounds(x, y, width, height);
}
class SubSlider extends JSlider
{
private SubSlider active;
#Override
protected void processMouseEvent(MouseEvent e)
{
SubSlider sl=getClosestSlider(e);
if(e.getID()==MouseEvent.MOUSE_PRESSED) active=sl;
else if(e.getID()==MouseEvent.MOUSE_RELEASED) active=null;
if(e.getID()==MouseEvent.MOUSE_CLICKED)
{
if(sl==null && e.getClickCount()==1) addSlider(e.getPoint());
else if(sl!=null && e.getClickCount()==2)
{
removeSlider(sl);
return;
}
}
if(sl!=null) sl.realProcessMouseEvent(e);
}
private void realProcessMouseEvent(MouseEvent e)
{
e.setSource(this);
super.processMouseEvent(e);
}
#Override
protected void processMouseMotionEvent(MouseEvent e)
{
if(e.getID()==MouseEvent.MOUSE_MOVED)
toAllSliders(e);
else
{
if(active==null) active=getClosestSlider(e);
if(active!=null) active.realProcessMouseMotionEvent(e);
}
}
private void realProcessMouseMotionEvent(MouseEvent e)
{
e.setSource(this);
super.processMouseMotionEvent(e);
}
}
final void toAllSliders(MouseEvent e)
{
for(int ix=0, n=getComponentCount(); ix<n; ix++)
((SubSlider)getComponent(ix)).realProcessMouseMotionEvent(e);
}
public void removeSlider(SubSlider sl)
{
if(getComponentCount()<=1) return;// must keep the last slider
remove(sl);
JSlider slider=(JSlider)getComponent(getComponentCount()-1);
slider.setOpaque(true);
slider.setPaintTrack(true);
revalidate();
repaint();
}
final SubSlider getClosestSlider(MouseEvent e)
{
SubSlider s=(SubSlider)getComponent(0);
BasicSliderUI bsUI=(BasicSliderUI)s.getUI();
int value = bsUI.valueForXPosition(e.getX());
if(Math.abs(s.getValue()-value)<=1) return s;
for(int ix=1, n=getComponentCount(); ix<n; ix++)
{
s=(SubSlider)getComponent(ix);
if(Math.abs(s.getValue()-value)<=1) return s;
}
return null;
}
void addSlider(Point point)
{
BasicSliderUI bsUI = (BasicSliderUI)((JSlider)getComponent(0)).getUI();
addSlider(bsUI.valueForXPosition(point.x));
}
void addSlider(int value)
{
final JSlider slider = new SubSlider();
slider.setFocusable(false);
slider.setValue(value);
if(getComponentCount()!=0)
{
slider.setOpaque(false);
slider.setPaintTrack(false);
}
super.add(slider, 0);
revalidate();
repaint();
}
}
This is my code for a simple arrow sequencing application.
It generates a random sequence of size 4 which comprise of UP, DOWN, LEFT and/or RIGHT arrow keys and displays them one at a time. If they user repeats the sequence correctly, it displays another sequence of 5 keys. The size of the sequence keeps incrementing as long as the user enters the correct sequence but decrements if an invalid sequence has been entered.
The problem I'm encountering is, the first execution is flawless, it even displays the sequence the second time, but it doesn't accept my keyboard inputs during the second iteration.
For a better understanding of the problem I have broken it down into the main action performing blocks and the full code as well at the end.
Sequence Generation
for(int flag=1;flag<size;flag++)
{
random = randomGenerator.nextInt(4);
generated[flag]=random;
setVisible(true);
switch(random)
{
case 0:
left();
break;
case 1:
up();
break;
case 2:
right();
break;
case 3:
down();
break;
}
delaybig();
}
User Input Sequence
public void keyPressed(KeyEvent e)
{
if(cflag<=size)
{
if(e.getKeyCode()==37)
{
entered[cflag]=0;
cflag++;
Keys.setText("LEFT");
left();
}
else if(e.getKeyCode()==38)
{
entered[cflag]=1;
cflag++;
Keys.setText("UP");
up();
}
else if(e.getKeyCode()==39)
{
entered[cflag]=2;
cflag++;
Keys.setText("RIGHT");
right();
}
else if(e.getKeyCode()==40)
{
entered[cflag]=3;
cflag++;
Keys.setText("DOWN");
down();
}
else
{
Keys.setText("INVALID");
}
}
Sequence Comparision using Arrays.equals
if(cflag==size)
{
boolean check = Arrays.equals(generated, entered);
if(check)
{
delaysmall();
Keys.setText("PERFECT");
size++;
cflag=1;
delaysmall();
Keys.setText("GO AGAIN");
delaybig();
restart();
}
else
{
delaysmall();
Keys.setText("FAILED");
if(size>5)
{
delaybig();
restart();
size--;
cflag=1;
}
}
}
Looping Thread
public void restart()
{
Thread goagain = new Thread()
{
#Override
public void run()
{
launchframe();
}
};
goagain.start();
}
I've spent quite some time on this to no avail so here is the full code just incase you suspect the error likes elsewhere.
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Arrays;
class ArrowSorrow extends Frame implements KeyListener{
int flag;
Image img;
int random;
int cflag=1,size=5;
boolean ShowImage=true;
int entered[]=new int[50];
int generated[]=new int[50];
TextField Keys=new TextField(8);
Random randomGenerator = new Random();
MediaTracker mt = new MediaTracker(this);
public ArrowSorrow(String title)
{
super(title);
}
public void restart()
{
// Create a new thread
Thread goagain = new Thread()
{
// Override run() to provide the running behavior of this thread.
#Override
public void run()
{
launchframe();
}
};
goagain.start();
}
public void launchframe()
{
for(int flag=1;flag<1;flag++)
generated[flag]=0;
for(int flag=1;flag<1;flag++)
entered[flag]=0;
splash();
add(Keys);
delaybig();
setSize(400,400);
Keys.setEditable(false);
Keys.setText("MEMORIZE");
Keys.addKeyListener(this);
setBackground(Color.black);
setLayout(new FlowLayout());
for(int flag=1;flag<size;flag++)
{
random = randomGenerator.nextInt(4);
generated[flag]=random;
setVisible(true);
switch(random)
{
case 0:
left();
break;
case 1:
up();
break;
case 2:
right();
break;
case 3:
down();
break;
}
delaybig();
}
String sequence=new String("");
for(flag=1;flag<size;flag++)
{
sequence=sequence+(Integer.toString(generated[flag]));
}
Keys.setText(sequence);
delaysmall();
Keys.setText("REPEAT");
delaysmall();
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
}
});
}
public void splash()
{
img = ToolKit.getDefaultToolkit().getImage("image address for splashscreen.jpg");
mt.addImage(img,0);
repaint();
setVisible(true);
}
public void left()
{
img = Toolkit.getDefaultToolkit().getImage("image address for left.jpg");
mt.addImage(img,0);
repaint();
setVisible(true);
}
public void right()
{
img = Toolkit.getDefaultToolkit().getImage("image address for right.jpg");
mt.addImage(img,0);
repaint();
setVisible(true);
}
public void up()
{
img = Toolkit.getDefaultToolkit().getImage("image address for up.jpg");
mt.addImage(img,0);
repaint();
setVisible(true);
}
public void down()
{
img = Toolkit.getDefaultToolkit().getImage("image address down.jpg");
mt.addImage(img,0);
repaint();
setVisible(true);
}
//minor delay
public void delaysmall()
{
try
{
Thread.sleep(600);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
//major delay
public void delaybig()
{
try
{
Thread.sleep(1200);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
public void paint(Graphics g)
{
super.paint(g);
if(img != null)
g.drawImage(img,70,70, this);
else
g.clearRect(0, 0, getSize().width, getSize().height);
}
public void keyPressed(KeyEvent e)
{
if(cflag<size)
{
if(e.getKeyCode()==37)
{
entered[cflag]=0;
cflag++;
Keys.setText("LEFT");
left();
}
else if(e.getKeyCode()==38)
{
entered[cflag]=1;
cflag++;
Keys.setText("UP");
up();
}
else if(e.getKeyCode()==39)
{
entered[cflag]=2;
cflag++;
Keys.setText("RIGHT");
right();
}
else if(e.getKeyCode()==40)
{
entered[cflag]=3;
cflag++;
Keys.setText("DOWN");
down();
}
else
{
Keys.setText("INVALID");
}
}
//comparing generated sequence and user input sequence
if(cflag==size)
{
boolean check = Arrays.equals(generated, entered);
if(check)
{
delaysmall();
Keys.setText("PERFECT");
size++;
cflag=1;
delaysmall();
Keys.setText("GO AGAIN");
delaybig();
restart();
}
else
{
delaysmall();
Keys.setText("FAILED");
if(size>5)
{
delaybig();
restart();
size--;
cflag=1;
}
}
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
}
class ArrowSorrowLaunch{
public static void main(String args[])
{
ArrowSorrow instance=new ArrowSorrow("Arrow Sorrow");
instance.launchframe();
}
}
You call launchFrame to start each iteration of the game. However, you are doing a lot of work in launchFrame that should be done only once. You should move that initialization code out of launchFrame and do it only once. In particular you should not repeatedly call Keys.addKeyListener(this); or add multiple window listeners.
change Thread.sleep(int) to Swing Timer, otherwise you'll bothering with Concurency in Swing
Thread.sleep(int) freeze Swing GUI until ended, during this sleep any Mouse or Key events aren't dispatched or consumed
don't paint directly to the JFrame, put there JPanel or JComponent
for JPanel or JComponent have to use paintComponent instead of paint()
don't use KeyListener, use Keybindings instead, otherwise have to setFocusable()
Solution by OP.
Fix, thanks to Ted Hopp.
Created this new method by moving them out of launchframe()
void oneTime()
{
add(Keys);
setSize(400,400);
Keys.requestFocus();
Keys.setEditable(false);
Keys.setText("MEMORIZE");
Keys.addKeyListener(this);
setBackground(Color.black);
setLayout(new FlowLayout());
launchframe();
}
Replaced
instance.launchframe();//this
instance.oneTime();//with this in main