I'm trying to make a WebCam example in Java but it doesn't work. Repaint method for JPanel doesn't call paintComponent. When I call repaint anywhere, it doesn't update the image but the program still keeps running:
This is my example:
public class JFrameExample extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private CameraPanel cameraPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameExample frame = new JFrameExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 200, 900, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
cameraPanel = new CameraPanel();
cameraPanel.setBackground(Color.RED);
cameraPanel.setBounds(10, 52, 640, 480);
contentPane.add(cameraPanel);
JButton btnActivar = new JButton("Activar");
btnActivar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startCamera();
}
});
btnActivar.setBounds(10, 11, 89, 23);
contentPane.add(btnActivar);
}
private void startCamera(){
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture eyeCamera = new VideoCapture(0);
if(eyeCamera.isOpened()){
while(true){
Mat frame = new Mat();
eyeCamera.read(frame);
cameraPanel.setimage(matToBufferedImage(frame));
cameraPanel.setSize(new Dimension(frame.width(),frame.height()));
contentPane.repaint();
cameraPanel.repaint();
this.repaint();
}
}
}
public static BufferedImage matToBufferedImage(Mat matrix) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int) matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for (int i = 0; i < data.length; i = i + 3) {
b = data[i];
data[i] = data[i + 2];
data[i + 2] = b;
}
break;
default:
return null;
}
BufferedImage image2 = new BufferedImage(cols, rows, type);
image2.getRaster().setDataElements(0, 0, cols, rows, data);
return image2;
}
}
CameraPanel
public class CameraPanel extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage image;
public CameraPanel() {
super();
}
public BufferedImage getimage() {
return image;
}
public void setimage(BufferedImage newimage) {
image = newimage;
System.out.println("setImage method");
}
#Override
protected void paintComponent(Graphics grafics) {
System.out.println("paintComponent method");
super.paintComponent(grafics);
if(image != null)
grafics.drawImage(image, 10, 10, 50, 50, this);
}
}
I could not try because your app is not runnable. But maybe runnig while(true) {} part in a Thread can solve your problem.
Thread paintThread = new Thread(new Runnable(){
public void run() {
while(true){
Mat frame = new Mat();
eyeCamera.read(frame);
cameraPanel.setimage(matToBufferedImage(frame));
cameraPanel.setSize(new Dimension(frame.width(),frame.height()));
contentPane.repaint();
cameraPanel.repaint();
this.repaint();
}
}
}
paintThread.start();
Related
I need to use a thread to change the position of my JLabel (movingDisplay) every second when I click on my button (btnDisplay) and for the thread to stop when I click on my other button (btnDStop). I have a class called MoveDisplay that implements Runnable and does this action when I click on btnDisplay. After MoveDisplay has randomized x and y for my JLabel, it's supposed to send x and y back to my main class where it updates the position of the JLabel. I have a method in my mainclass to update the JLabel position however I get a NullPointerException when trying to do so. In fact it doesn't work changing any component at all from MoveDisplay class.
public class Main {
public static void main(String[] args) {
GUIFrame test = new GUIFrame();
}
}
MoveDisplay class:
public class MoveDisplay implements Runnable {
private GUIFrame gui;
private boolean moving = true;
private Thread thread;
public void run() {
gui = new GUIFrame();
if (moving) {
Random rand = new Random();
while (moving) {
int x = rand.nextInt(150) + 1;
int y = rand.nextInt(150) + 1;
gui.moveDisplay(x, y, 100, 100);
try {
thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
}
public void start() {
thread = new Thread(new MoveDisplay());
thread.start();
}
public void stop() {
thread.interrupt();
System.out.println("Stopped");
}
}
GUIFrame class:
public class GUIFrame {
private JFrame frame; // The Main window
private JLabel movingDisplay;
private boolean playing = true;
private boolean moving = true;
private MoveDisplay moveDisplay = new MoveDisplay();
/**
* Starts the application
*/
public void Start() {
frame = new JFrame();
frame.setBounds(0, 0, 494, 437);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setTitle("Multiple Thread Demonstrator");
InitializeGUI(); // Fill in components
frame.setVisible(true);
frame.setResizable(false); // Prevent user from change size
frame.setLocationRelativeTo(null); // Start middle screen
}
public void InitializeGUI() {
// The moving display outer panel
JPanel pnlDisplay = new JPanel();
Border b2 = BorderFactory.createTitledBorder("Display Thread");
pnlDisplay.setBorder(b2);
pnlDisplay.setBounds(12, 118, 222, 269);
pnlDisplay.setLayout(null);
// Add buttons and drawing panel to this panel
btnDisplay = new JButton("Start Display");
btnDisplay.setBounds(10, 226, 121, 23);
pnlDisplay.add(btnDisplay);
btnDStop = new JButton("Stop");
btnDStop.setBounds(135, 226, 75, 23);
pnlDisplay.add(btnDStop);
pnlMove = new JPanel();
pnlMove.setBounds(10, 19, 200, 200);
Border b21 = BorderFactory.createLineBorder(Color.black);
pnlMove.setBorder(b21);
pnlDisplay.add(pnlMove);
// Then add this to main window
frame.add(pnlDisplay);
movingDisplay = new JLabel("DisplayThread");
pnlMove.add(movingDisplay);
btnDStop.setEnabled(false);
btnDisplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = true;
btnDisplay.setEnabled(false);
btnDStop.setEnabled(true);
startMoveDisplay();
}
});
btnDStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = false;
btnDisplay.setEnabled(true);
btnDStop.setEnabled(false);
startMoveDisplay();
}
});
}
public void startMoveDisplay() {
if(moving) {
moveDisplay.start();
}
else {
moveDisplay.stop();
}
}
public void moveDisplay(int x, int y, int a, int b) {
movingDisplay.setBounds(10,10,150,150);
}
}
I've checked the code and in the MoveDisplay.run() you were creating a new frame, but in it's constructor the panel wasn't initialized, which triggered the NPE. Because of this I've refactored the GUIFrame constructor to initialeze all components (invoked the Start() method) and removed the new frame's initialization from the run method. Here are the modified classed
public class MoveDisplay {
private GUIFrame gui;
private volatile boolean moving;
public MoveDisplay(GUIFrame gui) {
this.gui = gui;
}
public void start() {
moving = true;
Random rand = new Random();
while (moving) {
int x = rand.nextInt(150) + 1;
int y = rand.nextInt(150) + 1;
gui.moveDisplay(x, y, 100, 100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stop() {
moving = false;
}
}
And here is the new frame class
public class GUIFrame {
private JFrame frame; // The Main window
private JLabel movingDisplay;
private boolean playing = true;
private boolean moving = true;
private MoveDisplay moveDisplay;
public GUIFrame() {
Start();
}
/**
* Starts the application
*/
private void Start() {
frame = new JFrame();
frame.setBounds(0, 0, 494, 437);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setTitle("Multiple Thread Demonstrator");
InitializeGUI(); // Fill in components
frame.setVisible(true);
frame.setResizable(false); // Prevent user from change size
frame.setLocationRelativeTo(null); // Start middle screen
moveDisplay = new MoveDisplay(this);
}
public void InitializeGUI() {
// The moving display outer panel
JPanel pnlDisplay = new JPanel();
Border b2 = BorderFactory.createTitledBorder("Display Thread");
pnlDisplay.setBorder(b2);
pnlDisplay.setBounds(12, 118, 222, 269);
pnlDisplay.setLayout(null);
// Add buttons and drawing panel to this panel
JButton btnDisplay = new JButton("Start Display");
btnDisplay.setBounds(10, 226, 121, 23);
pnlDisplay.add(btnDisplay);
JButton btnDStop = new JButton("Stop");
btnDStop.setBounds(135, 226, 75, 23);
pnlDisplay.add(btnDStop);
JPanel pnlMove = new JPanel();
pnlMove.setBounds(10, 19, 200, 200);
Border b21 = BorderFactory.createLineBorder(Color.black);
pnlMove.setBorder(b21);
pnlDisplay.add(pnlMove);
// Then add this to main window
frame.add(pnlDisplay);
movingDisplay = new JLabel("DisplayThread");
pnlMove.add(movingDisplay);
btnDStop.setEnabled(false);
btnDisplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = true;
btnDisplay.setEnabled(false);
btnDStop.setEnabled(true);
startMoveDisplay();
}
});
btnDStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
moving = false;
btnDisplay.setEnabled(true);
btnDStop.setEnabled(false);
startMoveDisplay();
}
});
}
public void startMoveDisplay() {
if(moving) {
new Thread(new Runnable() {
#Override
public void run() {
moveDisplay.start();
}
}).start();
} else {
moveDisplay.stop();
}
}
public void moveDisplay(int x, int y, int a, int b) {
movingDisplay.setBounds(x, y, a, b);
}
}
You have to get a reference to the existing GUIFrame instance instead of creating a new one, try this:
MoveDisplay
public class MoveDisplay implements Runnable {
private GUIFrame gui;
Random rand = new Random();
volatile boolean moving;
public MoveDispaly(GUIFrame gui){
this.gui = gui;
}
public void run() {
while (moving) {
int x = rand.nextInt(150) + 1;
int y = rand.nextInt(150) + 1;
try {
SwingUtilities.invokeAndWait(new Runnable(){
public void run(){
gui.moveDisplay(x, y, 100, 100);
}
});
thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
public void start() {
moving = true;
thread = new Thread(new MoveDisplay());
thread.start();
}
public void stop() {
moving = false;
}
}
GUIFrame
public class GUIFrame{
MoveDisplay moveDisplay = new MoveDisplay(this);
...
}
Also, you have to run the part of the code that changes the GUI on the EDT thread.
Is not a good idea to stop a thread by interrupting it, you can stop it by setting the moving variable to false.
Maybe you can also use the Singleton Pattern to get the original instance of GUIFrame:
public static class instanceClassA {
private static instanceClassA = null;
public static instanceClassA(){
if(instance == null){
instance = instanceClassA();
}
return instance;
}
}
So far I have this:
The logic is that:
a.)I will press the keybutton 'S' then the game will start
b.)The JTextArea will show the conversation of the users(note: I didn't disable it for debugging purposes)
c.)The JTextField will be the field the user will type text.
I have these working code:
package game;
//import
public class Game extends JFrame {
public static final String SERVER_IP = "localhost";
public static final int WIDTH = 1200;
public static final int HEIGHT = 800;
public static final int SCALE = 1;
private final int FPS = 60;
private final long targetTime = 1000 / FPS;
private BufferedImage backBuffer;
public KeyboardInput input;
private Stage stage;
public String username = "";
public GameClient client;
public static Game game;
public static String message = "";
private Tank tank;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
public Game() throws HeadlessException {
setSize(1000, 1000);
addWindowListener(new WinListener());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
//setUndecorated(false);
addKeyListener(input);
setVisible(true);
}
public void init() {
this.game = this;
input = new KeyboardInput();
//this.setSize(WIDTH, HEIGHT);
//this.setLocationRelativeTo(null);
//this.setResizable(false);
Dimension expectedDimension = new Dimension(900, 50);
Dimension expectedDimension2 = new Dimension(100, 50);
jButton1 = new JButton("jButton1");
jTextArea1 = new JTextArea(6,6);
jTextArea1.setBounds(0,200,200,200);
jTextArea1.setBackground(Color.BLUE);
//jTextArea1.setFocusable(false);
jTextField1 = new JTextField("jTextField1");
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.add(jTextField1);
panel2.add(jButton1);
panel2.setBackground(Color.BLACK); // for debug only
panel2.setPreferredSize(expectedDimension);
panel2.setMaximumSize(expectedDimension);
panel2.setMinimumSize(expectedDimension);
jPanel1 = new JPanel();
jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
jPanel1.add(jTextArea1);
jPanel1.add(panel2);
jPanel1.setBackground(Color.RED); // for debug only
jPanel1.setPreferredSize(expectedDimension2);
jPanel1.setMaximumSize(expectedDimension2);
jPanel1.setMinimumSize(expectedDimension2);
jScrollPane1 = new JScrollPane(jPanel1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setContentPane(jScrollPane1);
System.out.println("init");
revalidate();
client = new GameClient(SERVER_IP, this);
backBuffer = new BufferedImage(800* SCALE,600 * SCALE, BufferedImage.TYPE_INT_RGB);
}
public Stage getStage() {
return stage;
}
public class WinListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
}
public void disconnect() {
Packet01Disconnect p = new Packet01Disconnect(username);
p.writeData(client);
client.closeSocket();
System.exit(0);
}
private Font font = new Font("Munro Small", Font.PLAIN, 96);
private Font font2 = new Font("Munro Small", Font.PLAIN, 50);
private Font fontError = new Font("Munro Small", Font.PLAIN, 25);
private int op = 0;
public void updateMenu() {
if (input.up.isPressed()) {
if (op == 1) {
op = 0;
} else {
op++;
}
input.up.toggle(false);
} else if (input.down.isPressed()) {
if (op == 0) {
op = 1;
} else {
op--;
}
input.down.toggle(false);
} else if (input.enter.isPressed() && op == 0) {
runningMenu = false;
input.enter.toggle(false);
} else if (input.enter.isPressed() && op == 1) {
System.exit(0);
}
}
public void drawMenu() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setFont(font);
bbg.setColor(Color.white);
bbg.drawString("Sample", 189, 180);
bbg.setFont(font2);
if (op == 0) {
bbg.setColor(Color.red);
bbg.drawString("Start", 327, 378);
bbg.setColor(Color.white);
bbg.drawString("Quit", 342, 425);
} else if (op == 1) {
bbg.setColor(Color.white);
bbg.drawString("Start", 327, 378);
bbg.setColor(Color.red);
bbg.drawString("Quit", 342, 425);
}
g.drawImage(backBuffer, 0, 0, this);
}
public void draw() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.black);
bbg.fillRect(0, 0, WIDTH, HEIGHT);
stage.drawStage(bbg, this);
for (Tank t : stage.getPlayers()) {
t.draw(bbg, SCALE, this);
}
g.drawImage(backBuffer, 0, 0, this);
}
public void update() {
tank.update(stage);
stage.update();
}
private long time = 0;
public void updateLogin() {
if (username.length() < 8) {
if (input.letter.isPressed()) {
username += (char) input.letter.getKeyCode();
input.letter.toggle(false);
}
}
if (input.erase.isPressed() && username.length() > 0) {
username = username.substring(0, username.length() - 1);
input.erase.toggle(false);
}
if (input.enter.isPressed() && username.length() > 0) {
input.enter.toggle(false);
time = System.currentTimeMillis();
Packet00Login packet = new Packet00Login(username, 0, 0, 0);
packet.writeData(client);
}
if (message.equalsIgnoreCase("connect server success")) {
time = 0;
runningLogin = false;
return;
}
if (message.equalsIgnoreCase("Username already exists")) {
drawLogin();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
message = "";
username = "";
time = 0;
}
if (message.equalsIgnoreCase("Server full")) {
drawLogin();
try {
Thread.sleep(2000);
} catch (Exception e) {
}
System.exit(0);
}
if (time != 0 && message.equals("") && (System.currentTimeMillis() - time) >= 5000) {
message = "cannot connect to the server";
drawLogin();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
message = "";
time = 0;
}
}
public void drawLogin() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.black);
bbg.fillRect(0, 0, 800, 600);
bbg.setColor(Color.red);
bbg.setFont(fontError);
bbg.drawString(message, 100, 100);
bbg.setFont(font2);
bbg.setColor(Color.white);
bbg.drawString("Username", 284, 254);
bbg.setColor(Color.red);
bbg.drawString(username, 284, 304);
g.drawImage(backBuffer, 0, 0, this);
}
public static String waitPlayers = "Waiting for others players";
public String auxWaitPlayers = waitPlayers;
public static int quantPlayers = 0;
public class StringWait extends Thread {
public void run() {
while (true) {
try {
waitPlayers = "waiting for others players";
Thread.sleep(1000);
waitPlayers = "waiting for others players.";
Thread.sleep(1000);
waitPlayers = "waiting for others players..";
Thread.sleep(1000);
waitPlayers = "waiting for others players...";
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
public void updateWaitPlayers() {
if (quantPlayers == 1) {
runningWaitPlayer = false;
}
}
public void drawWaitPlayers() {
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.black);
bbg.fillRect(0, 0, 800, 600);
bbg.setColor(Color.white);
bbg.setFont(fontError);
bbg.drawString(waitPlayers, 100, 100);
g.drawImage(backBuffer, 0, 0, this);
}
public boolean runningMenu = true, runningLogin = true, runningWaitPlayer = true, runningGame = true;
public int op2 = 0;
public void start() {
long start;
long elapsed;
long wait;
init();
while (true) {
runningGame = true;
runningMenu = true;
runningWaitPlayer = true;
runningLogin = true;
switch (op2) {
//..
}
}
public void setGameState(boolean state) {
//...
}
public static void main(String[] args) throws InterruptedException {
Game g = new Game();
Thread.sleep(1000);
g.start();
}
}
And these is my objective interface:
I hope someone will help me with my problem.
Set the "main" containers layout manager to BorderLayout
On to this, add the GameInterface in the BorderLayout.CENTER position
Create another ("interaction") container and set it's layout manager to BorderLayout, add this to the "main" container's BorderLayout.SOUTH position
Wrap the JTextArea in a JScrollPane and add it to the BorderLayout.CENTER position of your "interaction" container
Create another container ("message"), this could use a GridBagLayout. On to this add the JTextField (with GridBagConstraints#weightx set to 0 and GridBagConstraints#weightx set to 1) and add the button to the next cell (GridBagConstraints#gridx set to 1 and GridBagConstraints#weightx set to 0)
For more details, see:
Laying Out Components Within a Container
How to Use Borders
How to Use GridBagLayout
Note:
Graphics g = getGraphics(); is NOT how custom painting should be done. Instead, override the paintComponent of a component like JPanel and perform your custom painting there!
For more details see
Painting in AWT and Swing
Performing Custom Painting
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel master = new JPanel(new BorderLayout());
master.setBackground(Color.BLUE);
JPanel gameInterface = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
gameInterface.setBackground(Color.MAGENTA);
master.add(gameInterface);
JPanel interactions = new JPanel(new BorderLayout());
interactions.add(new JScrollPane(new JTextArea(5, 20)));
JTextField field = new JTextField(15);
JButton btn = new JButton("Button");
JPanel message = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
message.add(field, gbc);
gbc.gridx = 1;
gbc.weightx = 0;
message.add(btn, gbc);
interactions.add(message, BorderLayout.SOUTH);
master.add(interactions, BorderLayout.SOUTH);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(master);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
i have made an application that loads image from specific directory, loads all images in stack, when i am clicking on next button next image loads.
i have also added JSlider that change Brightness of Loaded Image but it doesn't work.
i don't know why but i am not getting exact problem.
my code :
public class PictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
float fval=1;
public PictureEditor()
{
JPanel panel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu("Tools");
final JSlider slider1;
slider1 = new JSlider(JSlider.HORIZONTAL,0,4,1);
slider1.setToolTipText("Slide To Change Brightness");
slider1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
slider1.setMajorTickSpacing(1);
slider1.setPaintLabels(true);
slider1.setPaintTicks(true);
slider1.setPaintTrack(true);
slider1.setAutoscrolls(true);
slider1.setBounds(50, 55, 200, 50);
slider1.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
System.out.println("Before");
fval=slider1.getValue();
chgBrt(fval);
repaint();
}
});
TitledBorder title;
title = BorderFactory.createTitledBorder("Operations");
title.setTitleJustification(TitledBorder.LEFT);
JButton RT90 = new JButton("");
JButton RT180 = new JButton("");
JButton RTM90 = new JButton("");
JButton RTM180 = new JButton("");
JButton NEXT = new JButton("");
Image img = null;
Image imgn = null;
try
{
img = ImageIO.read(getClass().getResource("/images/images_Horizontal.png"));
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
RT90.setIcon(new ImageIcon(img));
RT180.setIcon(new ImageIcon(img));
RTM90.setIcon(new ImageIcon(img));
RTM180.setIcon(new ImageIcon(img));
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(slider1);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.setBorder(title);
buttonPane.add(RT90);
buttonPane.add(RT180);
buttonPane.add(RTM90);
buttonPane.add(RTM180);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
Action nextpictureaction = new AbstractAction("Next Picture")
{
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e)
{
nextImage();
}
};
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
panel.add(label,BorderLayout.CENTER);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
}
public Stack<File> getFilesInFolder(String startPath)
{
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles())
{
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0)
{
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes)
{
if (extension.equals(filetype))
{
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage()
{
try
{
a=ImageIO.read(pictures.pop().getAbsoluteFile());
}
catch (IOException e1)
{
e1.printStackTrace();
}
final ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
#SuppressWarnings("null")
public void chgBrt(float f)
{
Graphics g = null;
Graphics2D g2d=(Graphics2D)g;
try
{
BufferedImage dest=changeBrightness(a,(float)fval);
System.out.println("Change Bright");
int w = a.getWidth();
int h = a.getHeight();
g2d.drawImage(dest,w,h,this);
ImageIO.write(dest,"jpeg",new File("/images/dest.jpg"));
System.out.println("Image Write");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public BufferedImage changeBrightness(BufferedImage src,float val)
{
RescaleOp brighterOp = new RescaleOp(val, 0, null);
return brighterOp.filter(src,null); //filtering
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PictureEditor();
}
});
}
}
anyone who can guide me and tell me where i am wrong ??
You may be able to adapt the approach shown in this RescaleTest, which varies the scaleFactor passed to RescaleOp to a value between zero and twice the slider's maximum.
JProgressBar in JProgressBar.VERTICAL mode rotates painted String.
Is it possible to save string HORIZONTAL?
Another option is to use a BorderLayout + JLabel
or if you are using Java 1.7.0, you can use a JLayer
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.LayerUI;
public class ProgressBarLabelTest {
private static JProgressBar makeProgressBar1(BoundedRangeModel model) {
JProgressBar progressBar = new JProgressBar(model) {
private JLabel label = new JLabel("000/100", SwingConstants.CENTER);
private ChangeListener changeListener = null;
#Override public void updateUI() {
removeAll();
if(changeListener!=null) removeChangeListener(changeListener);
super.updateUI();
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
setLayout(new BorderLayout());
changeListener = new ChangeListener() {
#Override public void stateChanged(ChangeEvent e) {
int iv = (int)(100 * getPercentComplete());
label.setText(String.format("%03d/100", iv));
}
};
addChangeListener(changeListener);
add(label);
label.setBorder(BorderFactory.createEmptyBorder(0,4,0,4));
}
});
}
#Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
Insets i = label.getInsets();
d.width = label.getPreferredSize().width + i.left + i.right;
return d;
}
};
initProgressBar(progressBar);
return progressBar;
}
private static JComponent makeProgressBar2(BoundedRangeModel model) {
final JLabel label = new JLabel("000/100");
label.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
LayerUI<JProgressBar> layerUI = new LayerUI<JProgressBar>() {
private final JPanel rubberStamp = new JPanel();
#Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Dimension d = label.getPreferredSize();
int x = (c.getWidth() - d.width) / 2;
int y = (c.getHeight() - d.height) / 2;
JLayer jlayer = (JLayer)c;
JProgressBar progress = (JProgressBar)jlayer.getView();
int iv = (int)(100 * progress.getPercentComplete());
label.setText(String.format("%03d/100", iv));
SwingUtilities.paintComponent(
g, label, rubberStamp, x, y, d.width, d.height);
}
};
JProgressBar progressBar = new JProgressBar(model) {
#Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
Insets i = label.getInsets();
d.width = label.getPreferredSize().width + i.left + i.right;
return d;
}
};
initProgressBar(progressBar);
return new JLayer<JProgressBar>(progressBar, layerUI);
}
public JComponent makeUI() {
final BoundedRangeModel m = new DefaultBoundedRangeModel();
JProgressBar progressBar0 = new JProgressBar(m);
initProgressBar(progressBar0);
progressBar0.setStringPainted(true);
JPanel p = new JPanel();
p.add(progressBar0);
p.add(makeProgressBar1(m));
p.add(makeProgressBar2(m));
p.add(new JButton(new AbstractAction("+10") {
private int i = 0;
#Override public void actionPerformed(ActionEvent e) {
m.setValue(i = (i>=100) ? 0 : i + 10);
}
}));
return p;
}
private static void initProgressBar(JProgressBar progressBar) {
progressBar.setOrientation(SwingConstants.VERTICAL);
progressBar.setStringPainted(false);
progressBar.setForeground(Color.GREEN);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ProgressBarLabelTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
It is a true-Hack but if works for me:
I lookup in the Stack if UI asks for orientation while printing the label, if so I return another orientation.
JProgressBar progress = new JProgressBar(){
#Override
public int getOrientation() {
for( StackTraceElement elem : new Throwable().getStackTrace() ) {
if(elem.getMethodName().equals( "paintText" ) || (elem.getMethodName().equals( "paintString" ))) {
return JProgressBar.HORIZONTAL;
}
}
return JProgressBar.VERTICAL;
}
};
You can override paintString() in a custom BasicProgressBarUI. A related example is seen here.