BasicScrollBarUI? How to use it - java

I am working on a code editor for Minecraft, and I am not very happy with the normal UI design in Java. I managed to change the buttons, but it doesn't really work for scroll bars. Could you please help me?
This is my ButtonUI class.
public class UIButton extends BasicButtonUI implements MouseListener {
private Color hoverColor;
private Color normalColor;
private Color pressedColor;
public UIButton(ColorSheme cs) {
super();
if (cs == ColorSheme.WHITE_BLUE_GRAY) {
hoverColor = new Color(212, 211, 255);
normalColor = new Color(184, 183, 206);
pressedColor = new Color(197, 196, 228);
}else if (cs == ColorSheme.GREEN_GRAY) {
hoverColor = new Color(22, 179, 103);
normalColor = new Color(9, 126, 101);
pressedColor = new Color(17, 158, 102);
}else if (cs == ColorSheme.RED_GRAY) {
hoverColor = new Color(204, 86, 88);
normalColor = new Color(171, 79, 91);
pressedColor = new Color(187, 82, 90);
}else if (cs == ColorSheme.BLUE_GRAY) {
hoverColor = new Color(126, 176, 191);
normalColor = new Color(104, 134, 179);
pressedColor = new Color(111, 148, 183);
}
}
#Override
public void installUI(JComponent c) {
super.installUI(c);
c.addMouseListener(this);
c.setBorder(null);
c.setFont(Main.getDefaultFont());
}
#Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removeMouseListener(this);
}
#Override
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
changeButtonColor((JButton) b, normalColor);
}
#Override
public void mouseClicked(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), hoverColor);
}
#Override
public void mousePressed(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), pressedColor);
}
#Override
public void mouseReleased(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), normalColor);
}
#Override
public void mouseEntered(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), hoverColor);
}
#Override
public void mouseExited(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), normalColor);
}
private void changeButtonColor(JButton b, Color c) {
b.setBackground(c);
}
}
And this is my UIScrollBarUI class.
public class UIScrollBar extends BasicScrollBarUI implements MouseListener {
private Color hoverColor;
private Color normalColor;
private Color pressedColor;
public UIScrollBar(ColorSheme cs) {
super();
if (cs == ColorSheme.WHITE_BLUE_GRAY) {
hoverColor = new Color(212, 211, 255);
normalColor = new Color(184, 183, 206);
pressedColor = new Color(197, 196, 228);
}else if (cs == ColorSheme.GREEN_GRAY) {
hoverColor = new Color(22, 179, 103);
normalColor = new Color(9, 126, 101);
pressedColor = new Color(17, 158, 102);
}else if (cs == ColorSheme.RED_GRAY) {
hoverColor = new Color(204, 86, 88);
normalColor = new Color(171, 79, 91);
pressedColor = new Color(187, 82, 90);
}else if (cs == ColorSheme.BLUE_GRAY) {
hoverColor = new Color(126, 176, 191);
normalColor = new Color(104, 134, 179);
pressedColor = new Color(111, 148, 183);
}
}
#Override
public void installUI(JComponent c) {
super.installUI(c);
c.addMouseListener(this);
c.setBorder(null);
}
#Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removeMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.print("Entered");
changeBarColor(e.getComponent(), hoverColor);
}
#Override
public void mouseExited(MouseEvent e) {
System.out.print("Exited");
}
private void changeBarColor(Component c, Color co) {
c.setBackground(co);
}
}

First of all, if you are not happy with the "normal" UI design, you should consider changing Look And Feel.
I personally hate MetalLookAndFeel, and i'm used to set a system dependent look and feel for my swing applications.
Check this link for further details.
If you just want to change track and/or thumb color, you can override BasicScrollBarUI paintThumb and paintTrack methods.
Scrollbar's buttons can be changed as well.
Try this example (screenshot below):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicScrollBarUI;
public class Main
{
public static void main (String [] a) {
SwingUtilities.invokeLater (new Runnable () {
#Override public void run () {
try {
UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
createAndShowGUI ();
}
catch (Exception e) {
JOptionPane.showMessageDialog (null, "An unexpected error occurred : " + e.getClass ().getSimpleName (), "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
private static void createAndShowGUI () {
JFrame frame = new JFrame ("Test ScrollBar");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setContentPane (new CustomScrollPane ());
frame.pack ();
frame.setLocationRelativeTo (null);
frame.setVisible (true);
}
}
class CustomScrollPane extends JScrollPane
{
public CustomScrollPane () {
super (VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS);
Image imageThumb = createImage (16, 16, Color.RED);
Image imageThumbPressed = createImage (16, 16, Color.MAGENTA);
Image imageTrack = createImage (16, 16, Color.YELLOW);
// Adding some test labels
JPanel view = new JPanel (new GridLayout (10, 5, 20, 50));
for (int i = 0; i < 50; i++) view.add (new JLabel ("Test Label " + String.valueOf (i)));
setViewportView (view);
setHorizontalScrollBar (new CustomScrollBar (JScrollBar.HORIZONTAL, imageThumb, imageThumbPressed, imageTrack));
setVerticalScrollBar (new CustomScrollBar (JScrollBar.VERTICAL, imageThumb, imageThumbPressed, imageTrack));
// Setting preferred size for convenience. Not a good practice !
setPreferredSize (new Dimension (200, 200));
}
private Image createImage (int width, int height, Color color) {
BufferedImage image = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics ();
g.setColor (color);
g.fillRect (0, 0, width, height);
g.dispose ();
return image;
}
}
class CustomScrollBar extends JScrollBar
{
private boolean isThumbPressed;
public CustomScrollBar (final int orientation, final Image thumb, final Image thumbPressed, final Image track) {
super (orientation);
addMouseListener (new MouseAdapter () {
public void mousePressed (MouseEvent e) {
isThumbPressed = true;
}
public void mouseReleased (MouseEvent e) {
isThumbPressed = false;
}
});
setUI (new BasicScrollBarUI () {
#Override protected void paintThumb (Graphics g, JComponent c, Rectangle r) {
if (isThumbPressed) g.drawImage (thumbPressed, r.x, r.y, r.width, r.height, null);
else g.drawImage (thumb, r.x, r.y, r.width, r.height, null);
}
#Override protected void paintTrack (Graphics g, JComponent c, Rectangle r) {
g.drawImage(track, r.x, r.y, r.width, r.height, null);
}
});
}
}

Related

Graphics Object not displaying to screen

So the answer to this might be completely obvious, but I just can't see it. Why is my Graphics object not displaying what I tell it to? I'm fairly certain I'm honoring Swing concurrency and such but perhaps not. Here's my JPanel code:
package com.kraken.towerdefense.graphics;
import com.kraken.towerdefense.TowerDefense;
import com.kraken.towerdefense.listener.KeyHandler;
import com.kraken.towerdefense.listener.MouseMotionHandler;
import com.kraken.towerdefense.scene.Scene;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
public class Screen extends JPanel implements Runnable {
Thread thread = new Thread(this);
private int FPS = 0;
public Scene scene;
TowerDefense tD;
private boolean running = false;
public RoundRectangle2D.Float playGame, quitGame;
public boolean playGameHighlighted, quitGameHighlighted;
#Override
public void run() {
long lastFrame = System.currentTimeMillis();
int frames = 0;
running = true;
while (running) {
repaint();
frames++;
if (System.currentTimeMillis() - 1000 >= lastFrame) {
FPS = frames;
frames = 0;
lastFrame = System.currentTimeMillis();
}
}
System.exit(0);
}
public Screen(TowerDefense tD) {
thread.start();
addKeyListener(new KeyHandler(this));
addMouseMotionListener(new MouseMotionHandler(this));
this.tD = tD;
scene = Scene.MENU;
}
#Override
public void paintComponent(Graphics g2) {
super.paintComponent(g2);
playGame = new RoundRectangle2D.Float((getWidth() / 2) - 200, (getHeight() / 2) - 100, 400, 100, 10, 10);
quitGame = new RoundRectangle2D.Float((getWidth() / 2) - 200, (getHeight() / 2) + 20, 400, 100, 10, 10);
Graphics2D g = (Graphics2D) g2.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.clearRect(0, 0, getWidth(), getHeight());
g.drawString("FPS: " + FPS, 10, 10);
if (scene == Scene.MENU) {
if (playGameHighlighted) {
g.setColor(new Color(255, 152, 56));
} else {
g.setColor(new Color(4, 47, 61));
}
g.fill(playGame);
if (quitGameHighlighted) {
g.setColor(new Color(255, 152, 56));
} else {
g.setColor(new Color(4, 47, 61));
}
g.fill(quitGame);
g.setColor(Color.WHITE);
g.setFont(new Font("Gisha", Font.PLAIN, 20));
g.drawString("Play", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Play") / 2), (getHeight() / 2) - 45);
g.drawString("Quit", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Quit") / 2), (getHeight() / 2) + 75);
}
}
public class KeyTyped {
public void keyESC() {
running = false;
}
}
}
And here's my Scene Enum:
package com.kraken.towerdefense.scene;
public enum Scene {
MENU,
GAME
}
I'm pretty sure I don't need to supply the JFrame code, but if necessary I will. Any other solutions to problems in my code you could give would be greatly appreciated. Thanks!
EDIT 1
Here's my MouseMotionListener class:
package com.kraken.towerdefense.listener;
import com.kraken.towerdefense.graphics.Screen;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MouseMotionHandler implements MouseMotionListener {
Screen screen;
public MouseMotionHandler(Screen screen) {
this.screen = screen;
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
if (screen.playGame.contains(e.getPoint())) {
screen.playGameHighlighted = true;
} else {
screen.playGameHighlighted = false;
}
if (screen.quitGame.contains(e.getPoint())) {
screen.quitGameHighlighted = true;
} else {
screen.playGameHighlighted = false;
}
}
}
Here's my JFrame code:
package com.kraken.towerdefense;
import com.kraken.towerdefense.graphics.Screen;
import javax.swing.*;
public class TowerDefense extends JFrame {
public static void main(String[] args) {
new TowerDefense();
}
public TowerDefense() {
setExtendedState(MAXIMIZED_BOTH);
setUndecorated(true);
setTitle("Tower Defense");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
Screen screen = new Screen(this);
this.add(screen);
setVisible(true);
}
}
And here's my KeyListener code:
package com.kraken.towerdefense.listener;
import com.kraken.towerdefense.graphics.Screen;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyHandler implements KeyListener {
private Screen screen;
private Screen.KeyTyped keyTyped;
public KeyHandler(Screen screen) {
this.screen = screen;
keyTyped = screen.new KeyTyped();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 27) {
keyTyped.keyESC();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
So those are all my classes, I hope that helps
So, I gutted your code to make it run and was capable of displaying...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GraphicsTest {
public static void main(String[] args) {
new GraphicsTest();
}
public GraphicsTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Screen());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public enum Scene {
MENU,
GAME
}
public class Screen extends JPanel implements Runnable {
Thread thread = new Thread(this);
private int FPS = 0;
public Scene scene;
private boolean running = false;
#Override
public void run() {
long lastFrame = System.currentTimeMillis();
int frames = 0;
running = true;
scene = Scene.MENU;
while (running) {
repaint();
frames++;
if (System.currentTimeMillis() - 1000 >= lastFrame) {
FPS = frames;
frames = 0;
lastFrame = System.currentTimeMillis();
}
}
System.exit(0);
}
public Screen() {
thread.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0, 0, getWidth(), getHeight());
g.drawString("FPS: " + FPS, 10, 10);
if (scene == Scene.MENU) {
g.setColor(Color.BLACK);
g.fillRoundRect((getWidth() / 2) - 100, (getHeight() / 2) - 50, 200, 100, 25, 25);
}
}
}
}
So that suggests that the problem you're describing is some where else.
To me this;
g.clearRect(0, 0, tD.getWidth(), tD.getHeight());
looks suspicious, as you're relying on the TowerDefense properties when you should relying on the components own width/height properties (apart from clearRect actually not been required in this context).
This further makes me suspicious that you're not actually adding the Screen component to anything that is displayable
The other possible problem is you're making use of an appropriate layout manager, but since your Screen class doesn't supply any preferredSize hints, this would be an additional issue which you're not demonstrating
Updated based on changes to the original question
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import javafx.scene.Scene;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
public class TowerDefense extends JFrame {
public static void main(String[] args) {
new TowerDefense();
}
public TowerDefense() {
// setExtendedState(MAXIMIZED_BOTH);
// setUndecorated(true);
setTitle("Tower Defense");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// setResizable(false);
Screen screen = new Screen(this);
this.add(screen);
pack();
setVisible(true);
}
public enum Scene {
MENU,
GAME
}
public class Screen extends JPanel implements Runnable {
Thread thread = new Thread(this);
private int FPS = 0;
public Scene scene;
TowerDefense tD;
private boolean running = false;
public RoundRectangle2D.Float playGame, quitGame;
public boolean playGameHighlighted, quitGameHighlighted;
#Override
public void run() {
// long lastFrame = System.currentTimeMillis();
// int frames = 0;
//
// running = true;
//
// while (running) {
// repaint();
//
// frames++;
//
// if (System.currentTimeMillis() - 1000 >= lastFrame) {
// FPS = frames;
// frames = 0;
//
// lastFrame = System.currentTimeMillis();
// }
// }
//
// System.exit(0);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public Screen(TowerDefense tD) {
thread.start();
addKeyListener(new KeyHandler(this));
addMouseMotionListener(
new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
playGameHighlighted = playGame.contains(e.getPoint());
quitGameHighlighted = quitGame.contains(e.getPoint());
repaint();
}
});
this.tD = tD;
scene = Scene.MENU;
}
#Override
public void paintComponent(Graphics g2) {
super.paintComponent(g2);
playGame = new RoundRectangle2D.Float((getWidth() / 2) - 200, (getHeight() / 2) - 100, 400, 100, 10, 10);
quitGame = new RoundRectangle2D.Float((getWidth() / 2) - 200, (getHeight() / 2) + 20, 400, 100, 10, 10);
Graphics2D g = (Graphics2D) g2.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.clearRect(0, 0, getWidth(), getHeight());
g.drawString("FPS: " + FPS, 10, 10);
if (scene == Scene.MENU) {
if (playGameHighlighted) {
g.setColor(new Color(255, 152, 56));
} else {
g.setColor(new Color(4, 47, 61));
}
g.draw(playGame);
if (quitGameHighlighted) {
g.setColor(new Color(255, 152, 56));
} else {
g.setColor(new Color(4, 47, 61));
}
g.draw(quitGame);
g.setColor(Color.WHITE);
g.setFont(new Font("Gisha", Font.PLAIN, 20));
g.drawString("Play", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Play") / 2), (getHeight() / 2) - 45);
g.drawString("Quit", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Quit") / 2), (getHeight() / 2) + 75);
}
}
public class KeyTyped {
public void keyESC() {
running = false;
}
}
}
public class KeyHandler implements KeyListener {
private Screen screen;
private Screen.KeyTyped keyTyped;
public KeyHandler(Screen screen) {
this.screen = screen;
keyTyped = screen.new KeyTyped();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 27) {
keyTyped.keyESC();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
}

Why JLabels disappeare?

Task: There are 2 labels which connect with each other by line, user must be able to move each of the labels with mouse and the connection between lables must move accordingly.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class BackgroundJPanel extends JPanel {
BackgroundJPanel() {
this.setBounds(0, 0, 200, 200);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(0, 0, 198, 198);
g.setColor(Color.black);
g.drawRect(0, 0, 198, 198);
}
}
class LinkJPanel extends JPanel {
JLabel[] labels = null;
LinkJPanel(JLabel[] labelsIn) {
labels = labelsIn;
this.setBounds(0, 0, 200, 200);
this.setOpaque(false);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(labels[0].getX(), labels[0].getY(),
labels[1].getX(), labels[1].getY());
}
}
class LabelJPanel extends JPanel {
AllPanel allPanel = null;
LabelJPanel(AllPanel allPanelIn) {
allPanel = allPanelIn;
this.setOpaque(false);
JLabel[] labels = allPanel.labels;
labels[0] = new JLabel("11");
this.add(labels[0]);
labels[1] = new JLabel("22");
this.add(labels[1]);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
this.addMouseMotionListener(myMouseAdapter);
this.addMouseListener(myMouseAdapter);
}
class MyMouseAdapter extends MouseAdapter {
JLabel labelToMove = null;
int startDeltaX = -1;
int startDeltaY = -1;
JLabel whichLabel(MouseEvent e) {
for (JLabel label : allPanel.labels) {
int deltaX = e.getX() - label.getX();
int deltaY = e.getY() - label.getY();
if ((deltaX >= 0)
&& (deltaX < label.getPreferredSize().width)
&& (deltaY >= 0)
&& (deltaY < label.getPreferredSize().height)) {
return label;
}
}
return null;
}
#Override
public void mousePressed(MouseEvent e) {
labelToMove = whichLabel(e);
if (labelToMove != null) {
startDeltaX = labelToMove.getX() - e.getX();
startDeltaY = labelToMove.getY() - e.getY();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (labelToMove != null) {
updateLocation(e);
}
}
#Override
public void mouseReleased(MouseEvent e) {
labelToMove = null;
}
public void updateLocation(MouseEvent e) {
int newXCoord = e.getX() + startDeltaX;
int newYCoord = e.getY() + startDeltaY;
labelToMove.setBounds(newXCoord, newYCoord,
labelToMove.getPreferredSize().width,
labelToMove.getPreferredSize().height);
//allPanel.backgroundJPanel.repaint();
allPanel.linkJPanel.repaint();
}
}
}
class AllPanel extends JPanel {
BackgroundJPanel backgroundJPanel = null;
LinkJPanel linkJPanel = null;
LabelJPanel labelJPanel = null;
JLabel[] labels = null;
AllPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(200, 200));
labels = new JLabel[2];
backgroundJPanel = new BackgroundJPanel();
this.add(backgroundJPanel);
linkJPanel = new LinkJPanel(labels);
this.add(linkJPanel);
labelJPanel = new LabelJPanel(this);
this.add(labelJPanel);
this.setComponentZOrder(backgroundJPanel, 2);
this.setComponentZOrder(linkJPanel, 1);
this.setComponentZOrder(labelJPanel, 0);
}
}
class MyFrame extends JFrame {
MyFrame() {
this.setTitle("Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new AllPanel());
this.pack();
this.setVisible(true);
this.setResizable(false);
}
}
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyFrame();
}
});
}
}
I use 3 JPanel - one for background, one for draw connection line, one for drawing 2 labels. JPanel for drawing labels has MouseMotion and Mouse listeners. When some mouse action appears code check which one of the label must be move and then change that label coordinates and repaint JPanel with connection line.
All work fine until I try also repaint JPanel with background. If I uncomment the line
//allPanel.backgroundJPanel.repaint();
after action JLabels and line start disappeare.
Can someone explane why this happen?

JApplet - Wont draw image when boolean is true

I have 4 tiles: Blue, red, green, and yellow. When the mouse moves over the tile I want it to light up (just change the image to a light colored one). Instead nothing happens.
I have done some simple debugging and know for a fact that the images are imported correctly and mouseOverTile[0] is turning true.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
public class MainGame extends JApplet implements MouseListener, Runnable
{
private static final long serialVersionUID = 1L;
Thread animator = null;
Image blue, blueLit, red, redLit, green, greenLit, yellow, yellowLit;
boolean takingTurn;
boolean[] mouseOverTile = new boolean[4];
public void init()
{
setSize(500, 500);
blue = new ImageIcon("Images/Blue.png").getImage();
blueLit = new ImageIcon("Images/Blue_Lit.png").getImage();
red = new ImageIcon("Images/Red.png").getImage();
redLit = new ImageIcon("Images/Red_Lit.png").getImage();
green = new ImageIcon("Images/Green.png").getImage();
greenLit = new ImageIcon("Images/Green_Lit.png").getImage();
yellow = new ImageIcon("Images/Yellow.png").getImage();
yellowLit = new ImageIcon("Images/Yellow_Lit.png").getImage();
Arrays.fill(mouseOverTile, false);
takingTurn = true;
addMouseListener(this);
}
public void start()
{
if(animator == null)
{
animator = new Thread(this);
}
}
public void stop()
{
animator = null;
}
#Override
public void run()
{
while(Thread.currentThread() == animator)
{
try
{
Thread.sleep(1);
repaint();
}
catch(Exception e)
{ }
}
}
public void paint(Graphics g)
{
if(!mouseOverTile[0])
{
g.drawImage(blue, 50, 50, this);
} else g.drawImage(blueLit, 50, 50, this);
if(!mouseOverTile[1])
{
g.drawImage(red, 260, 50, this);
} else g.drawImage(redLit, 260, 50, this);
if(!mouseOverTile[2])
{
g.drawImage(green, 50, 260, this);
} else g.drawImage(greenLit, 50, 260, this);
if(!mouseOverTile[3])
{
g.drawImage(yellow, 260, 260, this);
} else g.drawImage(yellowLit, 260, 260, this);
}
#Override
public void mouseClicked(MouseEvent e)
{
System.out.println("Mouse X: " + e.getX());
System.out.println("Mouse Y: " + e.getY());
}
#Override
public void mouseEntered(MouseEvent e)
{
if(takingTurn)
{
if(e.getX() > 50 && e.getX() < 250)
{
mouseOverTile[0] = true;
System.out.println(mouseOverTile[0]);
}
}
}
#Override
public void mouseExited(MouseEvent e)
{
if(takingTurn)
{
if(e.getX() < 50 || e.getX() > 250)
{
mouseOverTile[0] = false;
System.out.println(mouseOverTile[0]);
}
}
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
You have not updated the view.
Call repaint() when you made some changes.
For example in your code inside mouseEntered(...) :
#Override
public void mouseEntered(MouseEvent e)
{
if(takingTurn)
{
if(e.getX() > 50 && e.getX() < 250)
{
mouseOverTile[0] = true;
System.out.println(mouseOverTile[0]);
repaint();
}
}
}

Update LookAndFeel Values On The Fly

I want to be able to update the LookAndFeel attributes of my Swing GUI on the fly. In this case, I have a simple Swing/Awt game running what starts out as the Nimbus LookAndFeel. At various points after start up I want to change (let us say) just one detail: the background color of my application.
I can change the background color by doing this:
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.RED);
SwingUtilities.updateComponentTreeUI(SomeGame.this);
break;
}
}
This "works" in that the background color of the app changes correctly and the program doesn't crash. But on the command line I get error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.synth.SynthLookAndFeel.paintRegion(SynthLookAndFeel.java:371)
at javax.swing.plaf.synth.SynthLookAndFeel.update(SynthLookAndFeel.java:335)
Obviously, something is null, but I can not figure out what it is or how to fix it. There must be something I don't understand. I have looked at other StackOverflow questions about setting background colors in Nimbus and overriding the LookAndFeel information after startup.
When I call getLookAndFeelDefaults() do I need to specify the rest of the defaults as well?
Have there been changes in how this works between Java 1.6 and 1.7?
all code for Java6, have to change Nimbus imports for Java7
Nimbus has a few suprises, one of them is that is possible (without dirty hacks, I'm leaving comments for those hacks) to change Background for JPanel only one time
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
public class ButtonTest {
private JFrame frame;
private JPanel panel;
private JButton opaqueButton1;
private JButton opaqueButton2;
private SoftJButton softButton1;
private SoftJButton softButton2;
private Timer alphaChanger;
public void createAndShowGUI() {
opaqueButton1 = new JButton("Opaque Button");
opaqueButton2 = new JButton("Opaque Button");
softButton1 = new SoftJButton("Transparent Button");
softButton2 = new SoftJButton("Transparent Button");
opaqueButton1.setBackground(Color.GREEN);
softButton1.setBackground(Color.GREEN);
panel = new JPanel();
panel.setLayout(new java.awt.GridLayout(2, 2, 10, 10));
panel.add(opaqueButton1);
panel.add(softButton1);
panel.add(opaqueButton2);
panel.add(softButton2);
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
frame = new JFrame();
frame.add(panel);
frame.setLocation(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
alphaChanger = new Timer(50, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
softButton2.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(3500, new ActionListener() {
private final LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
if (laf[index].getClassName().equals("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel")) {
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.orange);
SwingUtilities.updateComponentTreeUI(frame);
} else {
panel.setBackground(Color.yellow);
SwingUtilities.updateComponentTreeUI(frame);
}
opaqueButton1.setText(laf[index].getClassName());
softButton1.setText(laf[index].getClassName());
frame.pack();
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private static class SoftJButton extends JButton {
private static final JButton lafDeterminer = new JButton();
private static final long serialVersionUID = 1L;
private boolean rectangularLAF;
private float alpha = 1f;
SoftJButton() {
this(null, null);
}
SoftJButton(String text) {
this(text, null);
}
SoftJButton(String text, Icon icon) {
super(text, icon);
setOpaque(false);
setFocusPainted(false);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
#Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
}
#Override
public void updateUI() {
super.updateUI();
lafDeterminer.updateUI();
rectangularLAF = lafDeterminer.isOpaque();
}
}
}
but for JComponent it is possible to change its Color, Font, etc by calling UIManager.getLookAndFeel().uninitialize();, but this does not work for containers
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
public class NimbusTestButtonsBackground extends JFrame {
private static final long serialVersionUID = 1L;
private javax.swing.JButton button;
public NimbusTestButtonsBackground() {
button = new javax.swing.JButton();
button.setText("Text");
add(button);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.pack();
Timer t = new Timer(1000, new ActionListener() {
private Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
try {
LookAndFeel lnf = UIManager.getLookAndFeel().getClass().newInstance();
UIDefaults uiDefaults = lnf.getDefaults();
uiDefaults.put("nimbusBase", c);
UIManager.getLookAndFeel().uninitialize();
UIManager.setLookAndFeel(lnf);
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
UIDefaults defaults = UIManager.getDefaults();
defaults.put("Button.background", c);
SwingUtilities.updateComponentTreeUI(button);
}
});
t.start();
}
public static void main(String args[]) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
return;
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NimbusTestButtonsBackground().setVisible(true);
}
});
}
}
then I see (this way as most comfortable, easiest, etc..) overriding paintComponent for JPanel as best the best way
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class ChangePanelBackgroundNimbus {
private JFrame frame = new JFrame();
public ChangePanelBackgroundNimbus() {
GradientPane pane = new GradientPane();
pane.setLayout(new GridLayout(6, 4, 10, 10));
for (int i = 1; i <= 24; i++) {
pane.add(createButton(i));
}
pane.setOpaque(false);
frame.add(pane);
RepaintManager.setCurrentManager(new RepaintManager() {
#Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Container con = c.getParent();
while (con instanceof JComponent) {
if (!con.isVisible()) {
return;
}
if (con instanceof GradientPane) {
c = (JComponent) con;
x = 0;
y = 0;
w = con.getWidth();
h = con.getHeight();
}
con = con.getParent();
}
super.addDirtyRegion(c, x, y, w, h);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
//frame.setSize(400, 300);
frame.pack();
frame.setVisible(true);
}
private JButton createButton(final int text) {
JButton button = new JButton(Integer.toString(text));
return button;
}
class GradientPane extends JPanel {
private static final long serialVersionUID = 1L;
private final int h = 150;
private BufferedImage img = null;
private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB);
public GradientPane() {
paintBackGround(new Color(150, 250, 150));
Timer t = new Timer(500, new ActionListener() {
private Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
paintBackGround(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
}
});
t.start();
}
public void paintBackGround(Color g) {
Graphics2D g2 = shadow.createGraphics();
g2.setPaint(g);
g2.fillRect(0, 0, 1, h);
g2.setComposite(AlphaComposite.DstIn);
g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h, new Color(0.4f, 0.8f, 0.8f, 0.5f)));
g2.fillRect(0, 0, 1, h);
g2.dispose();
}
#Override
public void paintComponent(Graphics g) {
if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) {
img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = img.createGraphics();
super.paintComponent(g2);
Rectangle bounds = this.getVisibleRect();
g2.scale(bounds.getWidth(), -1);
g2.drawImage(shadow, bounds.x, -bounds.y - h, null);
g2.scale(1, -1);
g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h, null);
g2.dispose();
g.drawImage(img, 0, 0, null);
repaint();
}
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ChangePanelBackgroundNimbus ml = new ChangePanelBackgroundNimbus();
}
});
}
}

Drawing rectangle on a JPanel

I want to draw a recangle on a JPanel. Am able to draw with the following code.
public class DrawingColor extends JFrame
{
public static void main(String[] args)
{
DrawingColor d = new DrawingColor();
}
public DrawingColor()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new MyComponent());
setSize(400,400);
setVisible(true);
}
public class MyComponent extends JComponent
{
#Override
public void paint(Graphics g)
{
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10, 10, height, width);
g.setColor(Color.gray);
g.fillRect(11, 11, height, width);
g.setColor(Color.red);
g.drawOval(250, 20, height, width);
g.setColor(Color.magenta);
g.fillOval(249, 19, height, width);
}
}
}
But getContentPane().add(new MyComponent());
Instead of this statement,I need to add one base panel to the frame. On the base panel I want to add the MyComponent panel.
JPanel basePanel = new JPanel();
basePanel = new MyComponent();
getContentPane().add(basePanel);
If I do like this, the rectangle is not getting visible. any idea?
And also I need to change the size of the rectangle at runtime. is it possible?
1) for Swing JComponent you have to use paintComponent() instead of paint() method
2) your JComponent doesn't returns PreferredSize
for example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Graphics2D");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
CustomComponents cc = new CustomComponents();
/*cc.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentResized(ComponentEvent event) {
setSize(Math.min(getPreferredSize().width, getWidth()),
Math.min(getPreferredSize().height, getHeight()));
}
});*/
add(cc, BorderLayout.CENTER);
CustomComponents cc1 = new CustomComponents();
add(cc1, BorderLayout.EAST);
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getSize());
//setMaximumSize(getMaximumSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent main = new CustomComponent();
main.display();
}
}
class CustomComponents extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(800, 600);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
Since you wanted to change the Dimensions of your Rectangle at run time, try this code for that :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RectangleTest extends JFrame {
private int x;
private int y;
private static JButton buttonFullSize;
private static JButton buttonHalfSize;
public RectangleTest() {
x = 0;
y = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel basePanel = new JPanel();
basePanel.setLayout(new BorderLayout());
final MyComponent component = new MyComponent(400, 400);
component.setOriginAndSize(0, 0, 100, 100);
buttonFullSize = new JButton("DRAW FULL SIZE");
buttonFullSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
component.setOriginAndSize(x++, y++,
(basePanel.getHeight() / 4), (basePanel.getWidth() / 4));
}
});
buttonHalfSize = new JButton("DRAW HALF SIZE");
buttonHalfSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
component.setOriginAndSize(x++, y++,
(basePanel.getHeight() / 8), (basePanel.getWidth() / 8));
}
});
basePanel.add(buttonHalfSize, BorderLayout.PAGE_START);
basePanel.add(component, BorderLayout.CENTER);
basePanel.add(buttonFullSize, BorderLayout.PAGE_END);
setContentPane(basePanel);
pack();
setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RectangleTest();
}
});
}
}
class MyComponent extends JComponent {
private int x;
private int y;
private int width;
private int height;
private int compWidth;
private int compHeight;
MyComponent(int w, int h) {
this.compWidth = w;
this.compHeight = h;
}
public void setOriginAndSize(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(compWidth, compHeight));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(x, y, width, height);
g.setColor(Color.RED);
g.drawOval(x, y, width, height);
g.setColor(Color.MAGENTA);
g.fillOval(x, y, width, height);
}
}
I had tried drawing a square and circle, dynamically varying the size at runtime....attaching the complete code ..if it helps.
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
import java.*;
import java.awt.Canvas;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class DisplayCanvas extends Canvas
{
static boolean clip = false;
static boolean clipfurther = false;
static boolean isReset = false, isSlider = false;
int w, h;
static int wi = 300, hi = 300;
public DisplayCanvas()
{
//setSize(300, 300);
setBounds(20, 40, 300, 300);
setBackground(Color.white);
}
public void paint(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
w = getSize().width;
h = getSize().height;
if(clip)
{
// Ellipse2D e = new Ellipse2D.Float(w/4.0f,h/4.0f,w/2.0f,h/2.0f);
Rectangle2D r = null;
if(isSlider)
{
r = new Rectangle2D.Float((w)/(4.0f), (h)/(4.0f), wi/2.0f, hi/2.0f);
// isSlider=false;
}
else
r = new Rectangle2D.Float(w/4.0f, h/4.0f, wi/2.0f, hi/2.0f);
//g2.setClip(e);
System.out.println("Width : "+ wi +" Height : "+ hi);
g2.setClip(r);
System.out.println(g2.getClipBounds());
if(shape.selectedcolor == "red")
{
g2.setColor(Color.red);
}
else if(shape.selectedcolor == "blue")
{
g2.setColor(Color.BLUE);
}
else if(shape.selectedcolor == "yellow")
{
g2.setColor(Color.yellow);
}
//g2.setColor(Color.RED);
g2.fillRect(0, 0, w, h);
}
else if(clipfurther)
{
//Rectangle r = new Rectangle(w/4, h/4, w/4, h/4);
Ellipse2D r = new Ellipse2D.Float(w/4.0f, h/4.0f, wi/2.0f, hi/2.0f);
g2.clip(r);
//g2.setColor(Color.green);
//g2.setColor(Color.getColor(shape.selectedcolor));
if(shape.selectedcolor == "red")
{
g2.setColor(Color.red);
}
else if(shape.selectedcolor == "blue")
{
g2.setColor(Color.BLUE);
}
else if(shape.selectedcolor == "yellow")
{
g2.setColor(Color.yellow);
}
g2.fillRect(0, 0, w, h);
}
}
}
class RadioListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == shape.circle)
{
shape.selectedcolor = shape.selectedcolor_reset;
System.out.println("Inside circle "+ shape.selectedcolor_reset);
System.out.println("2222222222");
DisplayCanvas.clip = true;
DisplayCanvas.clipfurther = false;
shape.canvas.repaint();
}
if (e.getSource() == shape.square)
{
shape.selectedcolor = shape.selectedcolor_reset;
System.out.println("333333333333333");
DisplayCanvas.clip = false;
DisplayCanvas.clipfurther = true;
shape.canvas.repaint();
}
}
}
class shape extends JFrame implements ActionListener
{
static String fname;
static JPanel panel, draw;
static Container contentpane, draw_pane;
static JFrame frame;
static JLayeredPane layer, draw_layer;
static JTextField user;
static JButton reset, cancel;
static JLabel file1, file2;
static JTextField text1;
static JRadioButton circle, square;
static JInternalFrame iframe, errmessage;
static JComboBox colors;
static JEditorPane sqc;
static JScrollPane scroller;
static JSlider slider;
String colors_array[]={"...", "red", "blue", "yellow"};
static DisplayCanvas canvas;
static String selectedcolor, selectedcolor_reset;
shape()
{
canvas=new DisplayCanvas();
panel= new JPanel();
panel.setBounds(20,20,250,140);
//panel.setLayout(new FlowLayout(10, 10, 10));
panel.setLayout(null);
contentpane = getContentPane();
contentpane.add(canvas);
//draw_pane=getContentPane();
layer = new JLayeredPane();
layer.setBounds(50,245,300,205);
layer.setForeground(Color.blue);
draw_layer = new JLayeredPane();
draw_layer.setBounds(200, 200, 80, 30);
draw_layer.setForeground(Color.BLACK);
draw = new JPanel();
draw.setBounds(20, 20, 250, 300);
draw.setLayout(null);
reset = new JButton("RESET");
reset.setBounds(360, 60, 100, 25);
circle = new JRadioButton("Square");
circle.setBounds(400, 100, 100, 40);
circle.setActionCommand("encryption");
square = new JRadioButton("Circle");
square.setBounds(330,100, 60, 40);
square.setActionCommand("decryption");
colors = new JComboBox(colors_array);
colors.setBounds(405, 140, 80, 30);
colors.setVisible(true);
file1 = new JLabel(" Select Color :");
file1.setBounds(320, 130, 150, 50);
//defining the Button Group for the Radio Buttons
ButtonGroup group = new ButtonGroup();
group.add(circle);
group.add(square);
cancel = new JButton("Exit");
cancel.setBounds(365, 250, 85, 25);
file2 = new JLabel("SIZE :");
file2.setBounds(336, 180, 150, 50);
setslider(0, 100, 100, 25, 5);
slider.setBounds(386, 190, 100, 50);
slider.setVisible(true);
panel.add(file2);
panel.add(layer);
panel.add(circle);
panel.add(square);
panel.add(colors);
panel.add(slider);
panel.add(file1);
panel.add(reset);
panel.add(cancel);
//panel.add(new CircleDraw());
//draw.add(draw_layer);
// draw_pane.add(draw);
contentpane.add(panel);
// contentpane.add(draw);
// contentpane.add(scroller);
RadioListener radio = new RadioListener();
circle.addActionListener(radio);
square.addActionListener(radio);
reset.addActionListener(this);
cancel.addActionListener(this);
colors.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JComboBox cb = (JComboBox)ae.getSource();
selectedcolor = (String)cb.getSelectedItem();
System.out.println(selectedcolor);
selectedcolor_reset = selectedcolor;
System.out.println("SELECTED "+ cb.getSelectedIndex());
canvas.repaint();
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel)
{
System.exit(0);
}
if (e.getSource() == reset)
{
System.out.println("111111111");
DisplayCanvas.clip = true;
DisplayCanvas.clipfurther = false;
DisplayCanvas.isReset = true;
shape.selectedcolor = "...";
System.out.println(" PREVIOUS " + selectedcolor_reset);
DisplayCanvas.hi = DisplayCanvas.wi = 300;
canvas.repaint();
}
}
public class SliderListener implements ChangeListener
{
public SliderListener()
{
}
public void stateChanged(ChangeEvent e)
{
JSlider slider = (JSlider)e.getSource();
System.out.println(slider.getValue());
DisplayCanvas.wi = slider.getValue() * 3;
DisplayCanvas.hi = DisplayCanvas.wi;
DisplayCanvas.isSlider = true;
canvas.repaint();
}
}
public void setslider(int min,int max,int init,int mjrtk,int mintk)
{
slider = new JSlider(JSlider.HORIZONTAL, min, max, init);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(mjrtk);
slider.setMinorTickSpacing(mintk);
slider.setPaintLabels(true);
slider.addChangeListener((ChangeListener) new SliderListener());
}
}
public class display
{
static JFrame frame;
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
frame=new shape();
frame.setBounds(380, 200, 500, 400);
frame.setTitle("SHAPE AND COLOR");
frame.setVisible(true);
}
}

Categories

Resources