I have downloaded a snake game project in java and try to modify it. Initially the project contains three java files
i.e "Engine.java" , "Snake.java", "GameBoard.java". And Engine.java have the main() method, and when i run this Engine.java class game starts running.
To improve the user iteractivity towards the project i have created two JFrames :"PlayGame.java", Rules.java
Now this project having five java classes -
Engine.java(containing main() method)
Snake.java
GameBoard.java
PlayGame.java(is a JFrame)
Rules.java(is a JFrame)
PlayGame.java have three buttons
Play - i want when play button get clicked snake game start/run.
Rules - when clicked Rules.java Jframe should be opened
Exit - exits the application
Now what i want is at first "PlayGame.java" JFrame should appear(and this is appearing as the main output of the game project) and throw this game should start i.e when i click play button from PlayGame JFrame game should start
The problem i am facing is when i click play button then gamescreen appears on the window but snake is not moving.
Here is the code that i have included in actionPerformed() method of Play button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame frame = new JFrame("SnakeGame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(true);
Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
frame.getContentPane().add(canvas);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Engine(canvas).startGame();
}
and also i am showing code of startGame() method which is in Engine.java class
public void startGame() {
canvas.createBufferStrategy(2);
Graphics2D g = (Graphics2D)canvas.getBufferStrategy().getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
long start = 0L;
long sleepDuration = 0L;
while(true) {
start = System.currentTimeMillis();
update();
render(g);
canvas.getBufferStrategy().show();
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
sleepDuration = (1500L / UPDATES_PER_SECOND) - (System.currentTimeMillis() - start);
if(sleepDuration > 0) {
try {
Thread.sleep(sleepDuration);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Here also i am attaching the Engine.java class and PlayGame.java in my question for better understandig of problem
Engine.java
package org.psnbtech;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import org.psnbtech.GameBoard.TileType;
import org.psnbtech.Snake.Direction;
public class Engine extends KeyAdapter {
private static final int UPDATES_PER_SECOND = 15;
private static final Font FONT_SMALL = new Font("Arial", Font.BOLD, 20);
private static final Font FONT_LARGE = new Font("Arial", Font.BOLD, 40);
public Canvas canvas;
public GameBoard board;
public Snake snake;
public int score;
public boolean gameOver;
public Engine(Canvas canvas) {
this.canvas = canvas;
this.board = new GameBoard();
this.snake = new Snake(board);
resetGame();
canvas.addKeyListener(this);
//new Engine(canvas).startGame();
}
public void startGame() {
canvas.createBufferStrategy(2);
Graphics2D g = (Graphics2D)canvas.getBufferStrategy().getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
long start = 0L;
long sleepDuration = 0L;
while(true) {
start = System.currentTimeMillis();
update();
render(g);
canvas.getBufferStrategy().show();
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
sleepDuration = (1500L / UPDATES_PER_SECOND) - (System.currentTimeMillis() - start);
if(sleepDuration > 0) {
try {
Thread.sleep(sleepDuration);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
public void update() {
if(gameOver || !canvas.isFocusOwner()) {
return;
}
TileType snakeTile = snake.updateSnake();
if(snakeTile == null || snakeTile.equals(TileType.SNAKE)) {
gameOver = true;
} else if(snakeTile.equals(TileType.FRUIT)) {
score += 10;
spawnFruit();
}
}
public void render(Graphics2D g) {
board.draw(g);
g.setColor(Color.WHITE);
if(gameOver) {
g.setFont(FONT_LARGE);
String message = new String("Your Score: " + score);
g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 250);
g.setFont(FONT_SMALL);
message = new String("Press Enter to Restart the Game");
g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 350);
} else {
g.setFont(FONT_SMALL);
g.drawString("Score:" + score, 10, 20);
}
}
public void resetGame() {
board.resetBoard();
snake.resetSnake();
score = 0;
gameOver = false;
spawnFruit();
}
public void spawnFruit() {
int random = (int)(Math.random() * ((GameBoard.MAP_SIZE * GameBoard.MAP_SIZE) - snake.getSnakeLength())); // if '*' replace by '/' then only one fruit is there for snake
int emptyFound = 0;
int index = 0;
while(emptyFound < random) {
index++;
if(board.getTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE).equals(TileType.EMPTY)) { // if '/' replaced by '*' then nothing displays on the board
emptyFound++;
}
}
board.setTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE, TileType.FRUIT); // it also show nothing when replacing '/' by '/'
}
#Override
public void keyPressed(KeyEvent e) {
if((e.getKeyCode() == KeyEvent.VK_UP)||(e.getKeyCode() == KeyEvent.VK_W)) {
snake.setDirection(Direction.UP);
}
if((e.getKeyCode() == KeyEvent.VK_DOWN)||(e.getKeyCode() == KeyEvent.VK_S)) {
snake.setDirection(Direction.DOWN);
}
if((e.getKeyCode() == KeyEvent.VK_LEFT)||(e.getKeyCode() == KeyEvent.VK_A)) {
snake.setDirection(Direction.LEFT);
}
if((e.getKeyCode() == KeyEvent.VK_RIGHT)||(e.getKeyCode() == KeyEvent.VK_D)) {
snake.setDirection(Direction.RIGHT);
}
if(e.getKeyCode() == KeyEvent.VK_ENTER && gameOver) {
resetGame();
}
}
public static void main(String[] args) {
new PlayGame().setVisible(true);
/**JFrame frame = new JFrame("SnakeGame");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(false);
Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
frame.getContentPane().add(canvas);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Engine(canvas).startGame();*/
}
}
PlayGame.java
package org.psnbtech;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class PlayGame extends javax.swing.JFrame {
public PlayGame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/GUID-4ED364DF-2D44-40F5-9F05-31D451F15EF1-low.png"))); // NOI18N
jButton2.setText("Rules");
jButton2.setMaximumSize(new java.awt.Dimension(89, 39));
jButton2.setMinimumSize(new java.awt.Dimension(89, 39));
jButton2.setPreferredSize(new java.awt.Dimension(89, 41));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/exit (1).png"))); // NOI18N
jButton3.setText("Exit");
jButton3.setPreferredSize(new java.awt.Dimension(89, 41));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/play.png"))); // NOI18N
jButton1.setText("Play");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(277, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(27, 27, 27))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jButton1)
.addGap(35, 35, 35)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(75, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
new Rules().setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame frame = new JFrame("SnakeGame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(true);
Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
//canvas.addKeyListener((KeyListener) this);
frame.getContentPane().add(canvas);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Engine(canvas).startGame();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Taht happens because you call
new PlayGame().setVisible(true);
and
frame.setVisible(true);
Show just the first frame and on button click the second.
The recommended approach is to use just one frame always but multiple panels 1. where game is rendered and 2. options pane. Swap them e.g. by using CardLayout.
Also don't use Canvas use JPanel instead overriding paintComponent() method.
Try the follwing:
JFrameAdd ja = new JFrameAdd();
ja.setVisible(true);
ja.setLocationRelativeTo(null);
Hope it will help!
Related
I am trying to make an app for communicating between different running instances of a thread. I have a jFrame that has a jTextField and a jButton. In the jTextField I type the number of threads that I want to run and after I press the jButton the threads run. Each thread contains a jFrame with a jButton. So if I type 3 in the jTextField and then press OK, three different jFrames pop out that have an own jButton. If I press the jButton in one of the jFrames of the threads, the jButton is set to disabled (setEnabled(false)). This should happen to each jButton of the jFrames from within the threads when pressed but the one from the last jFrame that is still not pressed.
This is the window class for the thread:
public class Window extends JFrame implements Runnable {
JFrame jr;
JButton bt;
public void run() {
jr=new JFrame();
bt=new jButton();
bt.setTitle("Press Me");
jr.setLayout(new FlowLayout());
jr.add(bt);
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bt.setEnabled(false);
}
});
jr.setVisible(true);
}
}
Now this is how I run multiple instances of this thread. i is the number of the thread instances that is taken from the jTextField:
( int i=Integer.parseInt(jTextField1.gettext()) )
for (int a=0;a<i;a++) {
Runnable thr=new Window(a);
executor.execute(thr);
}
This is what I want to do: After I press the jButton on every jFrame that is within the thread instances and it is set to setEnabled(false) I get to the last jFrame that is popped up whose jButton is still unpressed. When I press this last JButton I want that all the JButtons on every jFrame to be set back to setEnabled(true). How can I do that?
This is the main class it works 100 % now!
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (Integer.parseInt(jTextField1.getText()));
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
THIS IS THE WINDOW CLASS, WORKS 100 %:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public JFrame jr;
public JButton bt;
public JLabel l;
public JLabel l2;
public Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
My classes:
1) The Window class (Fereastra means window, deblocat means unlocked, buton activ means Button is enabled)
package concurenta;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public static JFrame jr;
public static JButton bt;
public static JLabel l;
public static JLabel l2;
public static Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
2) The Main Class(a.k.a Hauptklasse, okApasat means ok is pressed):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package concurenta;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (int) (Math.random() * (Integer.parseInt(jTextField1.getText()) - 3)) + 3;
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
It's easy to create HTML link locations like this sample, but now I'm talking about Java swing.
Lets assume I've created 5 JButtons: firstButton, secondButton, thirdButton, fourthButton and fifthButton.
Then I put all text information in a JTextArea txtInform.
When I click firstButton, information for firstButton will be displayed to the top of txtInform.
When I click secondButton, information for secondButton will be displayed to the top of txtInform.
And so forth for the next buttons. All buttons must work like this sample.
How can I do that?
Note: I know how to create components (like JButton, JTextArea, etc) in java swing. Please don't tell me only to read the tutorial of Swing Class API or other java docs. I have read the Swing Class API tutorial and java docs but I don't find any specific tutorial for this problem yet. If you ever read specific tutorial like what I'm asking here, please let me know.
Edit:
Updated: What I really need is to scroll to a position in a text area when the button clicked.
Below is the my code so far, I created it in netbeans. I use hightlight from here.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui_001;
import java.awt.Color;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
/**
*
* #author MyScript
*/
public class sampleFrame extends javax.swing.JFrame {
/**
* Creates new form sampleFrame
*/
public sampleFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
firstButton = new javax.swing.JButton();
secondButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
txtInform = new javax.swing.JTextArea();
thirdButton = new javax.swing.JButton();
fourthButton = new javax.swing.JButton();
fifthButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
firstButton.setText("First Button");
firstButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
firstButtonActionPerformed(evt);
}
});
secondButton.setText("Second Button");
secondButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
secondButtonActionPerformed(evt);
}
});
txtInform.setText("*First*");
txtInform.append("\n");
txtInform.append("All first information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("**Second**");
txtInform.append("\n");
txtInform.append("All second information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("***Third***");
txtInform.append("\n");
txtInform.append("All third information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("****Fourth****");
txtInform.append("\n");
txtInform.append("All fourth information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("*****Fifth*****");
txtInform.append("\n");
txtInform.append("All fifth information are here..");
txtInform.setColumns(20);
txtInform.setLineWrap(true);
txtInform.setRows(5);
txtInform.setWrapStyleWord(true);
jScrollPane1.setViewportView(txtInform);
thirdButton.setText("Third Button");
thirdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
thirdButtonActionPerformed(evt);
}
});
fourthButton.setText("Fourth Button");
fourthButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fourthButtonActionPerformed(evt);
}
});
fifthButton.setText("Fifth Button");
fifthButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fifthButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(secondButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(firstButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(thirdButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fourthButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fifthButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(64, 64, 64)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(71, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(firstButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(secondButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(thirdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fourthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fifthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(44, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(90, Short.MAX_VALUE))
);
setSize(new java.awt.Dimension(595, 477));
setLocationRelativeTo(null);
}// </editor-fold>
private void secondButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "**Second**";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void firstButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "*First*";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void fifthButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "*****Fifth*****";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void fourthButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "****Fourth****";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void thirdButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "***Third***";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new sampleFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton fifthButton;
private javax.swing.JButton firstButton;
private javax.swing.JButton fourthButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton secondButton;
private javax.swing.JButton thirdButton;
private javax.swing.JTextArea txtInform;
// End of variables declaration
}
Here is your code with some changes. When pressing a button, the text area will be scrolled to the location of the text and only that text will be highlighted.
public class SampleFrame extends JFrame {
private static JTextArea txtInform = new JTextArea();
private static final String TEXT = "*First*\nAll first information are here..\n\n\n\n" +
"**Second**\nAll second information are here..\n\n\n\n" +
"***Third***\nAll third information are here..\n\n\n\n" +
"****Fourth****\nAll fourth information are here..\n\n\n\n" +
"*****Fifth*****\nAll fifth information are here..";
public SampleFrame() {
initComponents();
}
private void initComponents() {
JScrollPane jScrollPane1 = new JScrollPane(txtInform);
JButton firstButton = new JButton("First Button");
JButton secondButton = new JButton("Second Button");
JButton thirdButton = new JButton("Third Button");
JButton fourthButton = new JButton("Fourth Button");
JButton fifthButton = new JButton("Fifth Button");
firstButton.addActionListener(new MyActionListener("*First*"));
secondButton.addActionListener(new MyActionListener("**Second**"));
thirdButton.addActionListener(new MyActionListener("***Third***"));
fourthButton.addActionListener(new MyActionListener("****Fourth****"));
fifthButton.addActionListener(new MyActionListener("*****Fifth*****"));
txtInform.setText(TEXT);
txtInform.setColumns(20);
txtInform.setRows(5);
txtInform.setLineWrap(true);
txtInform.setWrapStyleWord(true);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(secondButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(firstButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(thirdButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fourthButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fifthButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(64, 64, 64)
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 265,
GroupLayout.PREFERRED_SIZE).addContainerGap(71, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(firstButton, GroupLayout.PREFERRED_SIZE, 30,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(secondButton, GroupLayout.PREFERRED_SIZE, 31,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(thirdButton, GroupLayout.PREFERRED_SIZE, 31,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fourthButton, GroupLayout.PREFERRED_SIZE, 32,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fifthButton, GroupLayout.PREFERRED_SIZE, 32,
GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(44, Short.MAX_VALUE)
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 305,
GroupLayout.PREFERRED_SIZE).addContainerGap(90, Short.MAX_VALUE)));
setSize(new java.awt.Dimension(595, 477));
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private class MyActionListener implements ActionListener {
private int offset, length;
private final Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE);
private MyActionListener(String chapter) {
offset = TEXT.indexOf(chapter);
length = chapter.length();
}
public void actionPerformed(ActionEvent e) {
txtInform.setCaretPosition(offset);
txtInform.getHighlighter().removeAllHighlights();
try {
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SampleFrame().setVisible(true);
}
});
}
}
Class names start with uppercase per Java naming conventions.
Make your code present a logical order of the lines. It's clearer to initialize all buttons one after the other and not shove in the middle a scroll pane initialization.
Don't create fields when you can create local variables (all your buttons and scroll pane).
Prepare a single string with the text that should be displayed instead of calling append for every line (if you are not doing that already).
Create 1 action listener for all the buttons since it has a similar function for all of them - reusable code.
You'll profit a lot if you write the GUI yourself and not with a builder.
Simple example
public class Main extends JPanel implements ActionListener{
JTextField textField = null;
public static void main(final String[] args) {
Main main = new Main();
main.textField= new JTextField("Sample");
JButton btn1 = new JButton("Button1");
btn1.addActionListener(main);
JButton btn2 = new JButton("Button2");
btn2.addActionListener(main);
main.add(main.textField);
main.add(btn1);
main.add(btn2);
JFrame frame = new JFrame();
frame.setTitle("Simple example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.add(main);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(e.getActionCommand());
repaint();
}
}
I am creating 4 threads and each thread is associated with a UI.
The UI performs a long running task, for that I have used a SwingWorker.
But the problem that arises is instead of running as a multithreaded app, it is running in queue.
Interesting to note that when I remove the SwingWorker it behaves and runs as multithreaded.
My code is as:
NewClass
package thread;
public class NewClass
{
public static void main(String[] args) throws Exception
{
for(int i=0; i<4 ; i++)
{
new ThreadFront().startsThread();
Thread.sleep(2000);
}
}
}
class ThreadFront implements Runnable
{
private Thread t;
public ThreadFront()
{
t = new Thread(this, "");
}
public void startsThread()
{
t.start();
}
#Override
public void run()
{
try
{
UI ui = new UI();
ui.startThread();
}
catch(Exception ae)
{
ae.printStackTrace();
}
}
}
UI class
package thread;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
public class UI extends javax.swing.JFrame
{
public UI()
{
initComponents();
setVisible(true);
}
public void startThread() throws Exception
{
new SwingWorker<Integer, Integer>()
{
#Override
protected Integer doInBackground() throws Exception
{
for(int i=0; i<10;i++)
{
jTextArea1.append(""+i);
Thread.sleep(3000);
}
return 0;
}
#Override
protected void process(List<Integer> chunks)
{
for(Integer message : chunks)
{
jProgressBar1.setValue(message);
jProgressBar1.repaint();
}
}
#Override
protected void done()
{
try
{
get();
}
catch(final Exception ex)
{
ex.printStackTrace();
}
}
}.execute();
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel2 = new javax.swing.JLabel();
jobid_field = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
work_field = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
session_field = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
jPanel2.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(255, 255, 255)));
jPanel2.setForeground(new java.awt.Color(204, 204, 204));
jLabel1.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel1.setText("iZoneX Math Process");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 304, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(86, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel3.setBackground(new java.awt.Color(204, 204, 204));
jPanel3.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(255, 255, 255)));
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(255, 255, 204));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 0, 0));
jTextArea1.setLineWrap(true);
jTextArea1.setRows(5);
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
jLabel2.setText("Job ID. :");
jLabel4.setText("Processing: ");
jLabel3.setText("Session ID: ");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jobid_field, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(session_field, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(work_field, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jobid_field, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addComponent(session_field, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(work_field, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1.add(jPanel3, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void formWindowClosing(java.awt.event.WindowEvent evt) {
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JLabel jobid_field;
private javax.swing.JLabel session_field;
private javax.swing.JLabel work_field;
// End of variables declaration
}
What would be the alternative to worker Threads in Swing in that case?
Um, no, this is not how multithreading works in Swing.
There is a single UI thread (known as the Event Dispatching Thread), all updates and interactions with the UI are expected to be done from within the context of the EDT, so doing things like...
#Override
public void run()
{
try
{
UI ui = new UI();
ui.startThread();
}
catch(Exception ae)
{
ae.printStackTrace();
}
}
And...
#Override
protected Integer doInBackground() throws Exception
{
for(int i=0; i<10;i++)
{
jTextArea1.append(""+i);
Thread.sleep(3000);
}
return 0;
}
Are actually breaking this rule.
Instead, each UI should have its own SwingWorker (as it does now), but should be created from within the context of the EDT.
Each SwingWorker should be calling publish in order to push the results of the doInBackground method back to the EDT.
SwingWorker has its own progress support via the PropertyChange support
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MultiThreadedUI {
public static void main(String[] args) {
new MultiThreadedUI();
}
public MultiThreadedUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
final List<TestPane> panes = new ArrayList<>(5);
for (int index = 0; index < 5; index++) {
panes.add(new TestPane(Integer.toString(index)));
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1));
for (TestPane pane : panes) {
frame.add(pane);
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
for (TestPane pane : panes) {
pane.makeItSo();
}
}
});
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
private JProgressBar pb;
private String name;
public TestPane(String name) {
this.name = name;
textArea = new JTextArea(10, 5);
pb = new JProgressBar();
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
add(pb, BorderLayout.SOUTH);
}
public void makeItSo() {
BackgroundWorker worker = new BackgroundWorker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
pb.setValue((Integer)evt.getNewValue());
}
}
});
worker.execute();
}
protected class BackgroundWorker extends SwingWorker<Integer, Integer> {
#Override
protected void process(List<Integer> chunks) {
for (Integer value : chunks) {
textArea.append(name + ": " + value + "\n");
}
}
#Override
protected Integer doInBackground() throws Exception {
int delay = (int)(Math.random() * 3000);
for (int i = 0; i < 10; i++) {
publish(i);
setProgress((int) (Math.round(((double) i / (double) 9) * 100)));
Thread.sleep(delay);
}
return 0;
}
}
}
}
I am building an JavaFx application in which I have a text file and a audio mp3 file which reads it out. When I play the audio using MediaPlayer object and display the text from the text file. Is there any way to highlight each word as they are being played ? I know how subtitles are encoded and kept in a separated file but here it has to be done for each word. i.e. each word on the text file should have metadata how long it should be kept highlighted offset from the beginning of the mp3 file.
Another way is to calculate using a formula and length of text and audio file and find approximate time each world should be kept highlighted but this cam make highlighting out of sync.
Is there any standard way or standard metadata format in which I can encode the information how much time a word should be kept highlighted as the narration audio plays ?
I used straight logic for this. This stuff cannot be automatic (can be, but requires endless effort), so first you need to ask user to set the timings. Display the .txt file, and play the song in background. With the help of this, user highlights the words, and now you obtain the timings with the help of System.Current time in millisecs, and store the timings in an array or a list. When it is done, now you play the karaoke. Highlight the words, as per the timings.The words will get highlighted on the press of ESC key. Change the .txt file as per your need.
Please ignore my bad style of coding :p
Here is a demo of that in Swing:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.*;
public class newh extends JFrame
implements DocumentListener {
public static int[] arry=new int[1000];
static int first=0,last=0,scan=0,acount=0;int flag=1,point=0,j=0;long value,stat;
private JTextField entry;private boolean fir=true;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
private JLabel status;
private JTextArea textArea;
private JFrame frame;
long start;
final static Color HILIT_COLOR = Color.YELLOW;
final static Color ERROR_COLOR = Color.PINK;
final static String CANCEL_ACTION = "cancel-search";
final static String SMALL_ICON = "cancel-search";
final Color entryBg;
final Highlighter hilit;
final Highlighter.HighlightPainter painter;
private long start2;
JButton startButton;
public newh() throws FileNotFoundException {
initComponents();
String[] a=new String[1000];
InputStream in = getClass().getResourceAsStream("lyri.txt");
try {
textArea.read(new InputStreamReader(in), null);
} catch (IOException e) {
e.printStackTrace();
}
hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
textArea.setHighlighter(hilit);
entryBg = entry.getBackground();
entry.getDocument().addDocumentListener(this);
InputMap im = entry.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap am = entry.getActionMap();
im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION);
am.put(CANCEL_ACTION, new CancelAction());
}
/** This method is called from within the constructor to
* initialize the form.
*/
private void initComponents() {
entry = new JTextField();
textArea = new JTextArea();
textArea.setBackground(Color.ORANGE);
status = new JLabel();
jLabel1 = new JLabel();
frame = new JFrame();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("TextFieldDemo");
textArea.setColumns(20);
textArea.setLineWrap(true);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
jScrollPane1 = new JScrollPane(textArea);
final JFrame jar=new JFrame();
jLabel1.setText("Enter text to search:");
startButton = new JButton("Start");jar.add(startButton);
jar.setVisible(true);jar.pack();
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
ColoredTextTest.start();
} catch (InterruptedException ex) {
Logger.getLogger(newh.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(newh.class.getName()).log(Level.SEVERE, null, ex);
}
setVisible(false);
jar.setVisible(false);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
//Create a parallel group for the horizontal axis
ParallelGroup hGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
//Create a sequential and a parallel groups
SequentialGroup h1 = layout.createSequentialGroup();
ParallelGroup h2 = layout.createParallelGroup(GroupLayout.Alignment.CENTER);
//Add a container gap to the sequential group h1
h1.addContainerGap();
//Add a scroll pane and a label to the parallel group h2
h2.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE);
h2.addComponent(status, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE);
//Create a sequential group h3
SequentialGroup h3 = layout.createSequentialGroup();
h3.addComponent(jLabel1);
h3.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED);
h3.addComponent(entry, GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE);
//Add the group h3 to the group h2
h2.addGroup(h3);
//Add the group h2 to the group h1
h1.addGroup(h2);
h1.addContainerGap();
//Add the group h1 to the hGroup
hGroup.addGroup(GroupLayout.Alignment.TRAILING, h1);
//Create the horizontal group
layout.setHorizontalGroup(hGroup);
//Create a parallel group for the vertical axis
ParallelGroup vGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
//Create a sequential group v1
SequentialGroup v1 = layout.createSequentialGroup();
//Add a container gap to the sequential group v1
v1.addContainerGap();
//Create a parallel group v2
ParallelGroup v2 = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
v2.addComponent(jLabel1);
v2.addComponent(entry, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE);
//Add the group v2 tp the group v1
v1.addGroup(v2);
v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
v1.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE);
v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
v1.addComponent(status);
v1.addContainerGap();
//Add the group v1 to the group vGroup
vGroup.addGroup(v1);
layout.setVerticalGroup(vGroup);
pack();
}
#SuppressWarnings("empty-statement")
public void search() throws BadLocationException {
int i;
start=System.currentTimeMillis();
arry[point]=(int) (start - start2-10);
point++;
if(fir==true)
{fir=false;point=0;}
start2=start;
String s = textArea.getText();
char[] words=s.toCharArray();
for(i=last;words[i]!=' '&&words[i]!='\n';i++,last=i)
{
}
try {
hilit.addHighlight(first, last, painter);
last++; first=last;
} catch (BadLocationException ex) {
Logger.getLogger(newh.class.getName()).log(Level.SEVERE, null, ex);
}
}
void message(String msg) {
}
// DocumentListener methods
public void insertUpdate(DocumentEvent ev) {
// search();
}
public void removeUpdate(DocumentEvent ev) {
// search();
}
public void changedUpdate(DocumentEvent ev) {
}
public void keyTyped(KeyEvent e) throws BadLocationException {
}
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
class CancelAction extends AbstractAction {
public void actionPerformed(ActionEvent ev) {
try {
search();
} catch (BadLocationException ex) {
Logger.getLogger(newh.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) throws UnsupportedAudioFileException, IOException, LineUnavailableException, InterruptedException {
start();
}
public void setvisiblet()
{
setVisible(true);
}
public void setvisiblef()
{
setVisible(false);
}
public static void start()
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
try {
new newh().setVisible(true);
} catch (FileNotFoundException ex) {
Logger.getLogger(newh.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
class ColoredTextTest extends javax.swing.JFrame {
private String[] words=new String[1000];
private JScrollPane sc;
String sentence="";
int stringIndex = 0;
int index = 0;
Timer timer;
StyledDocument doc;
/** Creates new form textdisplay */
#SuppressWarnings("static-access")
public ColoredTextTest() throws FileNotFoundException, IOException {
initComponents();
doc = new DefaultStyledDocument();
jTextPane1.setDocument(doc);
javax.swing.text.Style style = jTextPane1.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
File file = new File("lyri.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
sentence+=line;
sentence+='\n';
}
br.close();
int j=0;
Scanner input = new Scanner(new File("lyri.txt"));
file = new File("lyri.txt");
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while(input.hasNext()) {
words[j] = input.next(); System.out.println(words[j]);j++;words[j]=" ";j++;
}
jTextPane1.setText(sentence);
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 0, 0));
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
jPanel1.setBorder(javax.swing.BorderFactory.createMatteBorder(3, 3, 3, 3, new java.awt.Color(0, 204, 204)));
jPanel1.setInheritsPopupMenu(true);
jButton1.setBackground(new java.awt.Color(255, 255, 0));
jButton1.setFont(new java.awt.Font("Virtual DJ", 0, 14));
jButton1.setForeground(new java.awt.Color(0, 255, 255));
jButton1.setText("Back");
jButton1.setOpaque(false);
jButton2.setBackground(new java.awt.Color(255, 255, 0));
jButton2.setFont(new java.awt.Font("Virtual DJ", 0, 14));
jButton2.setForeground(new java.awt.Color(0, 255, 255));
jButton2.setText("Pause");
jButton2.setOpaque(false);
jButton3.setBackground(new java.awt.Color(255, 255, 0));
jButton3.setFont(new java.awt.Font("Virtual DJ", 1, 14));
jButton3.setForeground(new java.awt.Color(0, 255, 255));
jButton3.setText("Play");
jButton3.setOpaque(false);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setBackground(new java.awt.Color(255, 255, 0));
jButton4.setFont(new java.awt.Font("Virtual DJ", 0, 14));
jButton4.setForeground(new java.awt.Color(0, 255, 255));
jButton4.setText("close");
jButton4.setOpaque(false);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jSeparator1.setBackground(new java.awt.Color(51, 255, 255));
jTextPane1.setBackground(new java.awt.Color(0, 0, 0));
jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jTextPane1.setForeground(new java.awt.Color(0, 255, 255));
jTextPane1.setVerifyInputWhenFocusTarget(false);
jScrollPane1.setViewportView(jTextPane1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)
.addGap(23, 23, 23))
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-988)/2, (screenSize.height-710)/2, 988, 710);
}// </editor-fold>
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
setVisible(false);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
this.sc=jScrollPane1;
JScrollBar verticalScrollBar = sc.getVerticalScrollBar();
JScrollBar horizontalScrollBar = sc.getHorizontalScrollBar();
verticalScrollBar.setValue(verticalScrollBar.getMinimum());
horizontalScrollBar.setValue(horizontalScrollBar.getMinimum());
dotimer();
}
public void dotimer()
{
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("index"+stringIndex);
doc.setCharacterAttributes(stringIndex, 1, jTextPane1.getStyle("Red"), true);
stringIndex++;
try {
if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ")|| doc.getText(stringIndex, 1).equals("\n")) {
index++;
}
} catch (BadLocationException ex) {
Logger.getLogger(ColoredTextTest.class.getName()).log(Level.SEVERE, null, ex);
}
if (index < 600) {
double delay = newh.arry[index];
timer.setDelay((int) (delay / words[index].length()));
} else {
timer.stop();
System.err.println("Timer stopped");
}
}
};
timer = new Timer(newh.arry[index], actionListener);
timer.setInitialDelay(0); System.out.println("done.........");
timer.start();
}
public static void main(String args[]) throws InterruptedException, InvocationTargetException {
start();
}
public static void start() throws InterruptedException, InvocationTargetException
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new ColoredTextTest().setVisible(true);
} catch (FileNotFoundException ex) {
Logger.getLogger(ColoredTextTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ColoredTextTest.class.getName()).log(Level.SEVERE, null, ex);
}
ColoredTextTest y = null;
try {
y = new ColoredTextTest();
} catch (FileNotFoundException ex) {
Logger.getLogger(ColoredTextTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ColoredTextTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextPane jTextPane1;
}
I need to move a Label-control on the form.
I have created a "Java Desktop Application" in NetBeans 6.1.
I have added the following code:
But the label is not moving.
Why?
/*
* DesktopApplication1View.java
*/
package desktopapplication1;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* The application's main frame.
*/
public class DesktopApplication1View extends FrameView {
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
jLabel1.isOptimizedDrawingEnabled();
jLabel1.requestFocusInWindow();
}
#Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = DesktopApplication1.getApplication().getMainFrame();
aboutBox = new DesktopApplication1AboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
DesktopApplication1.getApplication().show(aboutBox);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
mainPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplication1.DesktopApplication1.class).getContext().getResourceMap(DesktopApplication1View.class);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jLabel1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jLabel1KeyPressed(evt);
}
});
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(jLabel1)
.addContainerGap(215, Short.MAX_VALUE))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jLabel1)
.addContainerGap(155, Short.MAX_VALUE))
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(desktopapplication1.DesktopApplication1.class).getContext().getActionMap(DesktopApplication1View.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 226, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>
private void jLabel1KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
int keyCode = evt.getKeyCode();
int xPos = jLabel1.getX();
int yPos = jLabel1.getY();
switch(keyCode)
{
case KeyEvent.VK_UP:
jLabel1.setLocation(xPos, --yPos);
break;
case KeyEvent.VK_DOWN:
jLabel1.setLocation(xPos, ++yPos);
break;
case KeyEvent.VK_LEFT:
jLabel1.setLocation(--xPos, yPos);
break;
case KeyEvent.VK_RIGHT:
jLabel1.setLocation(++xPos, yPos);
break;
}
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
}
Take a look at the Swing tutorial.
1) Only components that have focus can receive KeyEvents. By default a JLabel is not focusable so it will never receive a KeyEvent. A better way to do this is to use Key Bindings. See the section from the Swing tutorial on Key Bindings.
2) If you fix 1, then the label might move, but it won't stay in its new position if the frame is resized, because the layout manager will be invoked and will reposition the label based on its rules.
Read the section from the Swing tutorial on Using Layout Managers. If you really need the label to be in a random position then you will need to use Absolute Positioning which is also discussed in the tutorial.