Buttons are being hidden by background image - java

I have set a background image on a JPanel but when i try to add buttons and selects to the custom background panel the buttons are hidden until i move the mouse over the buttons. I have included the code snippets below.
Below is my customized JPanel
package au.com.tankwarz.view.custompanels;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class BackgroundPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1659728640545162103L;
public BackgroundPanel()
{
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(loadBackgroundImage(), 0, 0, this);
g2d.dispose();
}
private static BufferedImage loadBackgroundImage()
{
BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a gradient from top to bottom
GradientPaint gp = new GradientPaint( 0, 0, Color.BLACK, 0, 600, new Color(0, 0, 255).darker( ).darker() );
g2d.setPaint( gp );
g2d.fillRect( 0, 0, 800, 600 );
g2d.dispose();
return bi;
}
}
And here is where i try to use it to display the panel with the buttons on it.
package au.com.tankwarz.view;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.jdesktop.application.Application;
import au.com.tankwarz.view.custompanels.BackgroundPanel;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
public class NewGamePanel extends BackgroundPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel numberOfPlayersLable;
private JComboBox numberOfPlayersCB;
private JButton cancelButton;
private JButton createPlayersButton;
private JComboBox numberOfTanksCB;
private JLabel numberOfTanksLable;
private JComboBox numberOfRoundsCB;
private JLabel numberOfRounds;
public static final String[] numberOfPlayersCBValues = new String[] { "Two", "Three", "Four" };
public static final String[] numberOfRoundsCBValues = new String[] { "One", "Two", "Three", "Four" };
public static final String[] numberOfTanksCBValues = new String[] { "One", "Two", "Three", "Four" };
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//new NewGamePanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new NewGamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public NewGamePanel() {
super();
initGUI();
}
private void initGUI() {
try {
AnchorLayout thisLayout = new AnchorLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(800, 600));
this.setSize(800, 600);
this.setOpaque(true);
this.setName("this");
{
numberOfPlayersLable = new JLabel();
this.add(numberOfPlayersLable, new AnchorConstraint(144, 320, 201, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfPlayersLable.setName("numberOfPlayersLable");
numberOfPlayersLable.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfPlayersCBModel =
new DefaultComboBoxModel(numberOfPlayersCBValues);
numberOfPlayersCB = new JComboBox();
this.add(numberOfPlayersCB, new AnchorConstraint(125, 697, 219, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfPlayersCB.setModel(numberOfPlayersCBModel);
numberOfPlayersCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
numberOfRounds = new JLabel();
this.add(numberOfRounds, new AnchorConstraint(298, 371, 355, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfRounds.setName("numberOfRounds");
numberOfRounds.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfRoundsCBModel =
new DefaultComboBoxModel(numberOfRoundsCBValues);
numberOfRoundsCB = new JComboBox();
this.add(numberOfRoundsCB, new AnchorConstraint(283, 697, 366, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfRoundsCB.setModel(numberOfRoundsCBModel);
numberOfRoundsCB.setName("numberOfRoundsCB");
numberOfRoundsCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
numberOfTanksLable = new JLabel();
this.add(numberOfTanksLable, new AnchorConstraint(453, 320, 509, 77, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfTanksLable.setName("numberOfTanksLable");
numberOfTanksLable.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
ComboBoxModel numberOfTanksCBModel =
new DefaultComboBoxModel(numberOfTanksCBValues);
numberOfTanksCB = new JComboBox();
this.add(numberOfTanksCB, new AnchorConstraint(437, 697, 520, 386, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
numberOfTanksCB.setModel(numberOfTanksCBModel);
numberOfTanksCB.setPreferredSize(new java.awt.Dimension(60, 40));
}
{
createPlayersButton = new JButton();
this.add(createPlayersButton, new AnchorConstraint(795, 758, 878, 511, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
createPlayersButton.setName("createPlayersButton");
createPlayersButton.setPreferredSize(new java.awt.Dimension(99, 25));
}
{
cancelButton = new JButton();
this.add(cancelButton, new AnchorConstraint(795, 248, 878, 128, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
cancelButton.setName("cancelButton");
cancelButton.setPreferredSize(new java.awt.Dimension(48, 25));
}
Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCreatePlayersButtonActionListener(ActionListener actionListener)
{
createPlayersButton.addActionListener(actionListener);
}
public void setCancelButtonActionListener(ActionListener actionListener)
{
cancelButton.addActionListener(actionListener);
}
public JComboBox getNumberOfPlayersCB()
{
return numberOfPlayersCB;
}
public void setNumberOfPlayersCB(JComboBox numberOfPlayersCB)
{
this.numberOfPlayersCB = numberOfPlayersCB;
}
public JComboBox getNumberOfTanksCB()
{
return numberOfTanksCB;
}
public void setNumberOfTanksCB(JComboBox numberOfTanksCB)
{
this.numberOfTanksCB = numberOfTanksCB;
}
public JComboBox getNumberOfRoundsCB()
{
return numberOfRoundsCB;
}
public void setNumberOfRoundsCB(JComboBox numberOfRoundsCB)
{
this.numberOfRoundsCB = numberOfRoundsCB;
}
}
Any help would be appreciate as i have been struggling with this for a while.

Don't change the state of the component from within any paintXxx method, this could cause a repaint event to be triggered, repeating the process until your CPU is running hot.
Never change the opacity state of the component from within any paintXxx, this will cause a cascading series of repaint's as Swing suddenly starts trying to figure out what components are now visible behind the current one...
Don't dispose of a Graphics context you didn't create, doing so could prevent what ever you paint after it not to be rendered on some systems.
Try not to create the background image on each paint cycle, this is not only expensive from memory point of view, but also expensive from a time point of view
I'm not sure why you flipping the opacity state, you don't really want it to be transparent. Simply call super.paintComponent to prepare the graphics state and then draw your image on top.
You should also avoid using setPreferredSize, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details...
Just illustrate the point, this is what you code produces (after I corrected the paint issues)
This is what my test code produces
Updated with test code
import com.apple.eawt.Application;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BackgroundPanel extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//new NewGamePanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new NewGamePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public BackgroundPanel() {
}
private static BufferedImage bi;
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(loadBackgroundImage(), 0, 0, this);
g2d.dispose();
}
private static BufferedImage loadBackgroundImage() {
if (bi == null) {
bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a gradient from top to bottom
GradientPaint gp = new GradientPaint(0, 0, Color.BLACK, 0, 600, new Color(0, 0, 255).darker().darker());
g2d.setPaint(gp);
g2d.fillRect(0, 0, 800, 600);
g2d.dispose();
}
return bi;
}
public static class NewGamePanel extends BackgroundPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel numberOfPlayersLable;
private JComboBox numberOfPlayersCB;
private JButton cancelButton;
private JButton createPlayersButton;
private JComboBox numberOfTanksCB;
private JLabel numberOfTanksLable;
private JComboBox numberOfRoundsCB;
private JLabel numberOfRounds;
public static final String[] numberOfPlayersCBValues = new String[]{"Two", "Three", "Four"};
public static final String[] numberOfRoundsCBValues = new String[]{"One", "Two", "Three", "Four"};
public static final String[] numberOfTanksCBValues = new String[]{"One", "Two", "Three", "Four"};
public NewGamePanel() {
super();
initGUI();
}
private void initGUI() {
try {
GridBagLayout thisLayout = new GridBagLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(800, 600));
this.setSize(800, 600);
this.setOpaque(true);
this.setName("this");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
{
numberOfPlayersLable = new JLabel();
this.add(numberOfPlayersLable, gbc);
numberOfPlayersLable.setName("numberOfPlayersLable");
}
{
ComboBoxModel numberOfPlayersCBModel
= new DefaultComboBoxModel(numberOfPlayersCBValues);
numberOfPlayersCB = new JComboBox();
this.add(numberOfPlayersCB, gbc);
numberOfPlayersCB.setModel(numberOfPlayersCBModel);
}
{
numberOfRounds = new JLabel();
this.add(numberOfRounds, gbc);
numberOfRounds.setName("numberOfRounds");
}
{
ComboBoxModel numberOfRoundsCBModel
= new DefaultComboBoxModel(numberOfRoundsCBValues);
numberOfRoundsCB = new JComboBox();
this.add(numberOfRoundsCB, gbc);
numberOfRoundsCB.setModel(numberOfRoundsCBModel);
numberOfRoundsCB.setName("numberOfRoundsCB");
}
{
numberOfTanksLable = new JLabel();
this.add(numberOfTanksLable, gbc);
numberOfTanksLable.setName("numberOfTanksLable");
}
{
ComboBoxModel numberOfTanksCBModel
= new DefaultComboBoxModel(numberOfTanksCBValues);
numberOfTanksCB = new JComboBox();
this.add(numberOfTanksCB, gbc);
numberOfTanksCB.setModel(numberOfTanksCBModel);
}
{
createPlayersButton = new JButton();
this.add(createPlayersButton, gbc);
createPlayersButton.setName("createPlayersButton");
}
{
cancelButton = new JButton();
this.add(cancelButton, gbc);
cancelButton.setName("cancelButton");
}
// Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCreatePlayersButtonActionListener(ActionListener actionListener) {
createPlayersButton.addActionListener(actionListener);
}
public void setCancelButtonActionListener(ActionListener actionListener) {
cancelButton.addActionListener(actionListener);
}
public JComboBox getNumberOfPlayersCB() {
return numberOfPlayersCB;
}
public void setNumberOfPlayersCB(JComboBox numberOfPlayersCB) {
this.numberOfPlayersCB = numberOfPlayersCB;
}
public JComboBox getNumberOfTanksCB() {
return numberOfTanksCB;
}
public void setNumberOfTanksCB(JComboBox numberOfTanksCB) {
this.numberOfTanksCB = numberOfTanksCB;
}
public JComboBox getNumberOfRoundsCB() {
return numberOfRoundsCB;
}
public void setNumberOfRoundsCB(JComboBox numberOfRoundsCB) {
this.numberOfRoundsCB = numberOfRoundsCB;
}
}
}

Related

Image and cursor are not matched in mouseEntered

I am developing the game GUI now.
But I have a small problem during programming.
I make a button to start and centered the button.
And I override mouseEntered and mouseExited.
When I run the program, Image is positioned center but cursor reacted from a distance.
I don't know why image and cursor are not matched...
This is my Main code.
package PoET;
public class Main {
public static final int SCREEN_WIDTH=600;
public static final int SCREEN_HEIGHT=800;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Display();
}
}
And this is my Display code.
package PoET;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Display extends JFrame {
private Image screenImage;
private Graphics screenGraphic;
private Image explainImage = new ImageIcon(Main.class.getResource("../images/explainSample.jpg")).getImage();
private Image introBackground = new ImageIcon(Main.class.getResource("../images/background.jpg")).getImage();
private JLabel menuBar = new JLabel(new ImageIcon(Main.class.getResource("../images/menuBar.png")));
private ImageIcon quitButtonBasicImage = new ImageIcon(Main.class.getResource("../images/quitButtonBasic.png"));
private ImageIcon quitButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/quitButtonPressed.png"));
private ImageIcon startButtonBasicImage = new ImageIcon(Main.class.getResource("../images/startButtonBasic.png"));
private ImageIcon startButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/startButtonEntered.png"));
private ImageIcon developerButtonBasicImage = new ImageIcon(Main.class.getResource("../images/developerButtonBasic.png"));
private ImageIcon developerButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/developerButtonEntered.png"));
private ImageIcon goButtonBasicImage = new ImageIcon(Main.class.getResource("../images/startButtonBasic.png"));
private ImageIcon goButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/startButtonEntered.png"));
private JButton quitButton = new JButton(
quitButtonBasicImage);
private JButton startButton = new JButton(
startButtonBasicImage);
private JButton developerButton = new JButton(
developerButtonBasicImage);
private JButton goButton = new JButton(
new ImageIcon(Main.class.getResource("../images/startButtonEntered.png")));
private int mouseX, mouseY;
private boolean isExplainScreen=false;
public Display() {
setUndecorated(true);
setTitle("RogueLike PoET");
setSize(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBackground(new Color(0, 0, 0, 0));
setLayout(null);
//quitButton.setBounds(560, 30, 30, 30);
quitButton.setBounds(400, 200, 30, 30);
quitButton.setBorderPainted(false);
quitButton.setContentAreaFilled(false);
quitButton.setFocusPainted(false);
quitButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
quitButton.setIcon(quitButtonEnteredImage);
quitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
quitButton.setIcon(quitButtonBasicImage);
quitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
add(quitButton);
menuBar.setBounds(0, 0, 600, 30);
menuBar.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseX=e.getX();
mouseY=e.getY();
}
});
menuBar.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int x=e.getXOnScreen();
int y=e.getYOnScreen();
setLocation(x-mouseX,y-mouseY);
}
});
add(menuBar);
startButton.setBounds(150, 540, 300, 60);
startButton.setBorderPainted(false);
startButton.setContentAreaFilled(false);
startButton.setFocusPainted(false);
startButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
startButton.setIcon(startButtonEnteredImage);
startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
startButton.setIcon(startButtonBasicImage);
startButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mousePressed(MouseEvent e) {
startButton.setVisible(false);
goButton.setVisible(true);
introBackground=new ImageIcon(Main.class.getResource("../images/background2.jpg")).getImage();
isExplainScreen=true;
}
});
add(startButton);
developerButton.setBounds(150, 610, 300, 60);
developerButton.setBorderPainted(false);
developerButton.setContentAreaFilled(false);
developerButton.setFocusPainted(false);
developerButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
developerButton.setIcon(developerButtonEnteredImage);
developerButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
developerButton.setIcon(developerButtonBasicImage);
developerButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mousePressed(MouseEvent e) {
developerButton.setVisible(false);
goButton.setVisible(true);
introBackground=new ImageIcon(Main.class.getResource("../images/background2.jpg")).getImage();
isExplainScreen=false;
}
});
add(developerButton);
goButton.setVisible(false);
goButton.setBounds(150, 720, 300, 60);
goButton.setBorderPainted(false);
goButton.setContentAreaFilled(false);
goButton.setFocusPainted(false);
goButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
goButton.setIcon(goButtonEnteredImage);
goButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
goButton.setIcon(goButtonBasicImage);
goButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mousePressed(MouseEvent e) {
goButton.setVisible(false);
introBackground=new ImageIcon(Main.class.getResource("../images/background2.jpg")).getImage();
isExplainScreen=true;
}
});
add(goButton);
Music introMusic = new Music("introMusic.mp3", true);
introMusic.start();
}
public void paint(Graphics g) {
screenImage = createImage(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
screenGraphic = screenImage.getGraphics();
screenDraw(screenGraphic);
g.drawImage(screenImage, 0, 0, null);
}
public void screenDraw(Graphics g) {
g.drawImage(introBackground, 0, 0, null);
paintComponents(g);
if(isExplainScreen) {
g.drawImage(explainImage, 50, 50,null);
}
this.repaint();
}
}
So I stripped back your example, removed the MouseListeners and just set the cursor of the buttons and it works fine - I reset the buttons to paint their border and contents so I could see their extent, and the cursor changes when ever the mouse enters/exist the area they cover without issue
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Display extends JFrame {
public static final int SCREEN_WIDTH = 600;
public static final int SCREEN_HEIGHT = 800;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Display();
}
private Image screenImage;
private Graphics screenGraphic;
// private Image explainImage = new ImageIcon(Main.class.getResource("../images/explainSample.jpg")).getImage();
// private Image introBackground = new ImageIcon(Main.class.getResource("../images/background.jpg")).getImage();
// private JLabel menuBar = new JLabel(new ImageIcon(Main.class.getResource("../images/menuBar.png")));
//
// private ImageIcon quitButtonBasicImage = new ImageIcon(Main.class.getResource("../images/quitButtonBasic.png"));
// private ImageIcon quitButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/quitButtonPressed.png"));
//
// private ImageIcon startButtonBasicImage = new ImageIcon(Main.class.getResource("../images/startButtonBasic.png"));
// private ImageIcon startButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/startButtonEntered.png"));
// private ImageIcon developerButtonBasicImage = new ImageIcon(Main.class.getResource("../images/developerButtonBasic.png"));
// private ImageIcon developerButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/developerButtonEntered.png"));
//
// private ImageIcon goButtonBasicImage = new ImageIcon(Main.class.getResource("../images/startButtonBasic.png"));
// private ImageIcon goButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/startButtonEntered.png"));
private JButton quitButton = new JButton(
"Quote");
private JButton startButton = new JButton(
"Start");
private JButton developerButton = new JButton(
"Developer");
private JButton goButton = new JButton(
new ImageIcon("Go"));
private int mouseX, mouseY;
private boolean isExplainScreen = false;
public Display() {
setUndecorated(true);
setTitle("RogueLike PoET");
setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// setBackground(new Color(0, 0, 0, 0));
setLayout(null);
//quitButton.setBounds(560, 30, 30, 30);
quitButton.setBounds(400, 200, 30, 30);
// quitButton.setBorderPainted(false);
// quitButton.setContentAreaFilled(false);
quitButton.setFocusPainted(false);
quitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(quitButton);
startButton.setBounds(150, 540, 300, 60);
// startButton.setBorderPainted(false);
// startButton.setContentAreaFilled(false);
startButton.setFocusPainted(false);
startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(startButton);
developerButton.setBounds(150, 610, 300, 60);
// developerButton.setBorderPainted(
// false);
// developerButton.setContentAreaFilled(
// false);
developerButton.setFocusPainted(
false);
developerButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(developerButton);
goButton.setVisible(
false);
goButton.setBounds(
150, 720, 300, 60);
// goButton.setBorderPainted(
// false);
// goButton.setContentAreaFilled(
// false);
goButton.setFocusPainted(
false);
goButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(goButton);
}
public void paint(Graphics g) {
screenImage = createImage(SCREEN_WIDTH, SCREEN_HEIGHT);
screenGraphic = screenImage.getGraphics();
screenDraw(screenGraphic);
g.drawImage(screenImage, 0, 0, null);
}
public void screenDraw(Graphics g) {
// g.drawImage(introBackground, 0, 0, null);
paintComponents(g);
if (isExplainScreen) {
// g.drawImage(explainImage, 50, 50, null);
}
this.repaint();
}
}
Observations
Don't override paint of a top level container like a JFrame. JFrame is a compound component (it has a series of child components which make up it's core functionality), overriding paint can have an adverse affect on how those components get painted. Unlike top level containers, Swing components are double buffered by default.
Also, the "viewable" area the "window" area are two different concepts. For more details see How to get the EXACT middle of a screen, even when re-sized
Also, you could be painting beneath the windows decorations (I know, it's a undecorated window, but it's still a bad habit)
Don't try and put ALL your logic into a single class/paint method. Instead, break down your screens into separate components and use something like CardLayout to switch between them
This...
setSize(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
is generally a bad idea. Better to let the child components dictate their preferred sizes and simply pack the window around them
Don't call setVisible(true); before you've established the basic UI, otherwise it's possible for some components not to be painted
I'm not sure what befit you're hoping to get from setBackground(new Color(0, 0, 0, 0));, but based on your current design, it seems like a waste
Don't call this.repaint(); or perform any other operation inside the paint chain which might trigger a repaint. This will set you for a infinite loop which will eventually consume all your CPU cycles
setLayout(null); is ill advised - there is a lot going into how components get laid out, you're in for a lot of work to reproduce it
Instead, it might look something like (as a starting point)...
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Display());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Display extends JPanel {
// private Image explainImage = new ImageIcon(Main.class.getResource("../images/explainSample.jpg")).getImage();
// private Image introBackground = new ImageIcon(Main.class.getResource("../images/background.jpg")).getImage();
// private JLabel menuBar = new JLabel(new ImageIcon(Main.class.getResource("../images/menuBar.png")));
//
// private ImageIcon quitButtonBasicImage = new ImageIcon(Main.class.getResource("../images/quitButtonBasic.png"));
// private ImageIcon quitButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/quitButtonPressed.png"));
//
// private ImageIcon startButtonBasicImage = new ImageIcon(Main.class.getResource("../images/startButtonBasic.png"));
// private ImageIcon startButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/startButtonEntered.png"));
// private ImageIcon developerButtonBasicImage = new ImageIcon(Main.class.getResource("../images/developerButtonBasic.png"));
// private ImageIcon developerButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/developerButtonEntered.png"));
//
// private ImageIcon goButtonBasicImage = new ImageIcon(Main.class.getResource("../images/startButtonBasic.png"));
// private ImageIcon goButtonEnteredImage = new ImageIcon(Main.class.getResource("../images/startButtonEntered.png"));
private JButton quitButton = new JButton(
"Quote");
private JButton startButton = new JButton(
"Start");
private JButton developerButton = new JButton(
"Developer");
private JButton goButton = new JButton(
new ImageIcon("Go"));
private int mouseX, mouseY;
private boolean isExplainScreen = false;
public Display() {
setLayout(null);
//quitButton.setBounds(560, 30, 30, 30);
quitButton.setBounds(400, 200, 30, 30);
// quitButton.setBorderPainted(false);
// quitButton.setContentAreaFilled(false);
quitButton.setFocusPainted(false);
quitButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(quitButton);
startButton.setBounds(150, 540, 300, 60);
// startButton.setBorderPainted(false);
// startButton.setContentAreaFilled(false);
startButton.setFocusPainted(false);
startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(startButton);
developerButton.setBounds(150, 610, 300, 60);
// developerButton.setBorderPainted(
// false);
// developerButton.setContentAreaFilled(
// false);
developerButton.setFocusPainted(
false);
developerButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(developerButton);
goButton.setVisible(
false);
goButton.setBounds(
150, 720, 300, 60);
// goButton.setBorderPainted(
// false);
// goButton.setContentAreaFilled(
// false);
goButton.setFocusPainted(
false);
goButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
add(goButton);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 800);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(introBackground, 0, 0, null);
// This should be done else where
// if (isExplainScreen) {
// // g.drawImage(explainImage, 50, 50, null);
// }
//this.repaint();
}
}
}

Display buttons one at time [duplicate]

I created a JFrame, and it contains a JPanel. I created a number of JLabels. I can add the JLabels to the JPanel, and display them correctly. But I want to implement them so as they displayed sequentially; a time delay between each JLabel to be displayed.
After searching the StackOverfLow, I tried some code, but it has no effect!. So How to use a timer to make components(Labels) displayed one after the other by setting a time delay.
I Don't want a fix for my code particularly in the answer. Just show how to display any type of components in a delayed manner, each component displayed after a period of time. That is all. I provided my code to show my effort in trying to solve the problem.
First this is a subclass of JLabel to use: (No problems with it)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
public class DLabel extends JLabel
{
Dimension size = new Dimension(70, 75);
Font font = new Font(Font.SANS_SERIF, 12, 35);
public DLabel(String t)
{
this.setPreferredSize(size);
this.setBorder(BorderFactory.createBevelBorder(1, Color.white, Color.black));
this.setVerticalAlignment(JLabel.CENTER);
this.setHorizontalAlignment(JLabel.CENTER);
this.setText(t);
this.setFont(font);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = new Color(226, 218, 145);
Color color2 = color1.brighter();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
super.paintComponent(g);
}
}
The other class that use the DLabel class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
public class DelayedLabels extends JPanel
{
static JFrame frame;
Timer timer; //timer to be used for dealy
DLabel card_1; //Defining the DLabels
DLabel card_2;
DLabel card_3;
JLabel[] labelsArray;
public DelayedLabels()
{
this.setLayout(null);
card_1 = new DLabel("1");
card_2 = new DLabel("2");
card_3 = new DLabel("3");
labelsArray = new DLabel[3]; //create the array
createLabelsArray(); //add the Labels Objects to labelsArray
setLabelsLocations(labelsArray); // set the locations of the Labels to be displayed on the JPanel
addLabelsToPanel(labelsArray); //The adding of the Labels to the JPanel
}
private void createLabelsArray()
{
labelsArray[0] = card_1;
labelsArray[1] = card_2;
labelsArray[2] = card_3;
}
private void setLabelsLocations(JLabel[] labels)
{
int length = labels.length;
int gap = 10;
int counter = 10;
for (int i = 0; i < length; i++)
{
labels[i].setBounds(170, counter, 60, 70);
counter = counter + labels[i].getBounds().height + gap;
}
}
private void addLabelsToPanel(JLabel[] labels)
{
for (int i = 0; i < labels.length; i++)
{
frame.revalidate();
frame.repaint();
this.add(labels[i]);
timer = new Timer(1000, timerAction); //timer to use with 1000 milliseconds
timer.start();
}
}
private ActionListener timerAction = new ActionListener() //action to be invoked after each label added
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.revalidate();
frame.repaint();
}
};
private static void createAndShowGUI()
{
frame = new JFrame();
frame.setSize(600, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DelayedLabels demo = new DelayedLabels();
demo.setOpaque(true);
frame.add(demo);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DelayedLabels extends JPanel {
static JFrame frame;
Timer timer; //timer to be used for dealy
JLabel card_1; //Defining the JLabels
JLabel card_2;
JLabel card_3;
JLabel[] labelsArray;
ActionListener listener;
public DelayedLabels() {
listener = new ActionListener() {
int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
Component c = DelayedLabels.this.getTopLevelAncestor();
DelayedLabels.this.add(labelsArray[i++]);
c.validate();
c.repaint();
if (i==labelsArray.length) {
timer.stop();
}
}
};
this.setLayout(new GridLayout(0, 1, 20, 20));
card_1 = new JLabel("Label 1");
card_2 = new JLabel("Label 2");
card_3 = new JLabel("Label 3");
labelsArray = new JLabel[3]; //create the array
createLabelsArray(); //add the Labels Objects to labelsArray
timer = new Timer(1000,listener);
timer.start();
}
private void createLabelsArray() {
labelsArray[0] = card_1;
labelsArray[1] = card_2;
labelsArray[2] = card_3;
}
private static void createAndShowGUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DelayedLabels demo = new DelayedLabels();
demo.setOpaque(true);
frame.add(demo, BorderLayout.PAGE_START);
frame.pack();
frame.setSize(200, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}

Change JLabel colour repeatedly each time when JButton pressed

I'm trying to make a traffic light program, changing the foreground colour of JLabel from red to yellow to green, everytime I press JButton (i.e once i press JButton, JLabel turns red, then when i again press JButton it turns yellow and so on). But somehow the colour changes only once to red & nothing happens on further pressing JButton. Any kind of help would be appreciated. Thanks.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
You're using the same actionCommand, B for each if block, and so all of the blocks will always run, and the last block will be the one seen.
e.g.,
int x = 1;
if (x == 1) {
// do something
}
if (x == 1) {
// do something else
}
all blocks will be done!
Either change the actionCommands used, or don't use actionCommand String but rather an incrementing int index. Also, don't use MouseListeners for JButtons but rather ActionListeners.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Traffic2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"};
private Map<String, Color> stringColorMap = new HashMap<>();
private JLabel label = new JLabel("", SwingConstants.CENTER);
private int index = 0;
public Traffic2() {
stringColorMap.put("Red", Color.red);
stringColorMap.put("Blue", Color.blue);
stringColorMap.put("Orange", Color.orange);
stringColorMap.put("Yellow", Color.YELLOW);
stringColorMap.put("Green", Color.GREEN);
stringColorMap.put("Cyan", Color.CYAN);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
index++;
index %= STRINGS.length;
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
}
}));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Traffic2 mainPanel = new Traffic2();
JFrame frame = new JFrame("Traffic2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to add time delay between adding components to JFrame?

I created a JFrame, and it contains a JPanel. I created a number of JLabels. I can add the JLabels to the JPanel, and display them correctly. But I want to implement them so as they displayed sequentially; a time delay between each JLabel to be displayed.
After searching the StackOverfLow, I tried some code, but it has no effect!. So How to use a timer to make components(Labels) displayed one after the other by setting a time delay.
I Don't want a fix for my code particularly in the answer. Just show how to display any type of components in a delayed manner, each component displayed after a period of time. That is all. I provided my code to show my effort in trying to solve the problem.
First this is a subclass of JLabel to use: (No problems with it)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
public class DLabel extends JLabel
{
Dimension size = new Dimension(70, 75);
Font font = new Font(Font.SANS_SERIF, 12, 35);
public DLabel(String t)
{
this.setPreferredSize(size);
this.setBorder(BorderFactory.createBevelBorder(1, Color.white, Color.black));
this.setVerticalAlignment(JLabel.CENTER);
this.setHorizontalAlignment(JLabel.CENTER);
this.setText(t);
this.setFont(font);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = new Color(226, 218, 145);
Color color2 = color1.brighter();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
super.paintComponent(g);
}
}
The other class that use the DLabel class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
public class DelayedLabels extends JPanel
{
static JFrame frame;
Timer timer; //timer to be used for dealy
DLabel card_1; //Defining the DLabels
DLabel card_2;
DLabel card_3;
JLabel[] labelsArray;
public DelayedLabels()
{
this.setLayout(null);
card_1 = new DLabel("1");
card_2 = new DLabel("2");
card_3 = new DLabel("3");
labelsArray = new DLabel[3]; //create the array
createLabelsArray(); //add the Labels Objects to labelsArray
setLabelsLocations(labelsArray); // set the locations of the Labels to be displayed on the JPanel
addLabelsToPanel(labelsArray); //The adding of the Labels to the JPanel
}
private void createLabelsArray()
{
labelsArray[0] = card_1;
labelsArray[1] = card_2;
labelsArray[2] = card_3;
}
private void setLabelsLocations(JLabel[] labels)
{
int length = labels.length;
int gap = 10;
int counter = 10;
for (int i = 0; i < length; i++)
{
labels[i].setBounds(170, counter, 60, 70);
counter = counter + labels[i].getBounds().height + gap;
}
}
private void addLabelsToPanel(JLabel[] labels)
{
for (int i = 0; i < labels.length; i++)
{
frame.revalidate();
frame.repaint();
this.add(labels[i]);
timer = new Timer(1000, timerAction); //timer to use with 1000 milliseconds
timer.start();
}
}
private ActionListener timerAction = new ActionListener() //action to be invoked after each label added
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.revalidate();
frame.repaint();
}
};
private static void createAndShowGUI()
{
frame = new JFrame();
frame.setSize(600, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DelayedLabels demo = new DelayedLabels();
demo.setOpaque(true);
frame.add(demo);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DelayedLabels extends JPanel {
static JFrame frame;
Timer timer; //timer to be used for dealy
JLabel card_1; //Defining the JLabels
JLabel card_2;
JLabel card_3;
JLabel[] labelsArray;
ActionListener listener;
public DelayedLabels() {
listener = new ActionListener() {
int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
Component c = DelayedLabels.this.getTopLevelAncestor();
DelayedLabels.this.add(labelsArray[i++]);
c.validate();
c.repaint();
if (i==labelsArray.length) {
timer.stop();
}
}
};
this.setLayout(new GridLayout(0, 1, 20, 20));
card_1 = new JLabel("Label 1");
card_2 = new JLabel("Label 2");
card_3 = new JLabel("Label 3");
labelsArray = new JLabel[3]; //create the array
createLabelsArray(); //add the Labels Objects to labelsArray
timer = new Timer(1000,listener);
timer.start();
}
private void createLabelsArray() {
labelsArray[0] = card_1;
labelsArray[1] = card_2;
labelsArray[2] = card_3;
}
private static void createAndShowGUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DelayedLabels demo = new DelayedLabels();
demo.setOpaque(true);
frame.add(demo, BorderLayout.PAGE_START);
frame.pack();
frame.setSize(200, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}

JDialog setLocation ignored

Edited with a SSCCE and a workaround
I want to programmatically change the location of a JDialog.
public class SSCCE {
public static void main(String[] pArgs) {
JDialog dialog = new JDialog();
dialog.setSize(300, 300);
dialog.setLocation(10, 10);
dialog.setVisible(true);
}
}
However, this is not working, the new dialog is always located in the center of the screen. I suspect it has something todo with my L&F (Windows 7 64bit, jdk 1.6_30), when setting the dialog to be undecorated,
public class SSCCEWorksButUndecorated {
public static void main(String[] pArgs) {
JDialog dialog = new JDialog();
dialog.setSize(300, 300);
dialog.setLocation(10, 10);
dialog.setUndecorated(true);
dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
dialog.setVisible(true);
}
}
The location is excalty where I specified.
But I need a decorated dialog, has anyone else seen this problem before or am I missing something?
Workaround by settings location after setVisible() for modal dialogs
public class SSCCEWorkaroundForModalDialogs {
public static void main(String[] pArgs) {
final JDialog dialog = new JDialog();
dialog.setSize(300, 300);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setLocation(10, 10);
}
});
dialog.setVisible(true);
}
}
The move method documentation says:
This method changes layout-related information, and therefore,
invalidates the component hierarchy.
The method changes the geometry-related data. Therefore, the native
windowing system may ignore such requests, or it may modify the
requested data, so that the Window object is placed and sized in a way
that corresponds closely to the desktop settings.
I assume you can do a call to revalidaite() before setting the dialog visible again.
I did it my way -
package com.whodesire.element;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
public class MessageEdge {
private JDialog messageEdge = null;
private JDialog tempMessage = null;
private Point elmLoc = null;
private String[] option;
private JButton btnOK;
private JLayeredPane lp = null;
private int top = 70;
MessageEdge(JFrame owner){
owner.setAlwaysOnTop(false);
}
public void ShowMessage(final String msg){
ShowMessage(msg, "OK");
}
public void ShowMessage(final String msg, final String... option){
this.option = option;
init();
}
protected void setRootPaneStroking(JRootPane rootPane){
rootPane.setWindowDecorationStyle(JRootPane.NONE);
KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE");
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
disposeMessage();
}
};
InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(stroke, "ESCAPE");
rootPane.getActionMap().put("ESCAPE", action);
};
private void init(){
top = 70;
tempMessage = new JDialog(){
private static final long serialVersionUID = 1L;
{
setUndecorated(true);
setType(Type.UTILITY);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBackground(new Color(0, 0, 0, 0));
elmLoc = Elementos.getElementosLocationPoint();
setSize(460, 57);
setLayout(new GridLayout(1, 1));
if(lp == null)
lp = getModelJLayeredPane();
add(lp);
setLocation(elmLoc.x-10, elmLoc.y+top);
setAlwaysOnTop(true);
validate();
setVisible(true);
}
};
new Thread(new Runnable(){
public void run(){
try{
OneMethod.playSound("catchyMessage");
whileLoop:
while(true){
//System.out.println("top value is : " + top + ", is top value bigger than -47 : " + (top > -47));
if(top > -47){
top -= 7;
tempMessage.setLocation(elmLoc.x-10, elmLoc.y+top);
}else{
top = -47;
initMessageEdge();
break whileLoop;
}
Thread.sleep(4);
}
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}).start();
}
private void initMessageEdge(){
tempMessage.setVisible(false);
tempMessage.remove(lp);
tempMessage.dispose();
//Elementos is my JFrame
messageEdge = new JDialog(Elementos.getFrame(), true){
private static final long serialVersionUID = 1L;
{
setUndecorated(true);
setType(Type.UTILITY);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setRootPaneStroking(getRootPane());
setBackground(new Color(0, 0, 0, 0));
requestFocusInWindow();
elmLoc = Elementos.getElementosLocationPoint();
setSize(460, 57);
setLayout(new GridLayout(1, 1));
if(lp == null)
lp = getModelJLayeredPane();
add(lp);
setLocation(elmLoc.x-10, elmLoc.y+top);
setAlwaysOnTop(true);
validate();
}
};
messageEdge.setVisible(true);
messageEdge.requestFocus();
}
private JLayeredPane getModelJLayeredPane(){
JLayeredPane layer = new JLayeredPane();
layer.setBounds(0, 0, 460, 57);
layer.setLayout(null);
JPanel panel = new JPanel(){
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics gr){
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.01f));
g.setColor(new Color(255, 196, 51));
g.fillRect(0, 0, 460, 57);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.75f));
g.setColor(new Color(255, 196, 51));
g.fillRect(0, 0, 460, 47);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
g.setColor(new Color(244, 171, 50));
int[] xxPoly = {0, 10, 10};
int[] yyPoly = {47, 47, 57};
Polygon pplg = new Polygon(xxPoly, yyPoly, xxPoly.length);
g.fillPolygon(pplg);
}
};
panel.setSize(450, 57);
panel.setOpaque(true);
panel.setLayout(null);
layer.add(panel);
btnOK = new JButton(){
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics gr) {
final Graphics2D g = (Graphics2D) gr.create();
g.setPaint(new GradientPaint(new Point(0, 0), Color.WHITE,
new Point(0, getHeight()), new Color(255, 196, 51)));
g.fillRect(0, 0, getWidth(), getHeight());
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setColor(Color.BLACK);
g.setFont(new Font(OneMethod.getSegoeUIBoldFont().getFamily(), Font.BOLD, 11));
g.drawString(option[0], 8, 17);
g.dispose();
super.paintComponent(g);
}
};
btnOK.setFocusPainted(false);
btnOK.setBorder(BorderFactory.createLineBorder(new Color(244, 171, 50)));
btnOK.setBounds(460-30, (int)((47/2)-(25/2)), 30, 25);
layer.add(btnOK);
btnOK.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent evt){
btnOK.setBorder(BorderFactory.createEmptyBorder());
btnOK.setBorder(BorderFactory.createLoweredBevelBorder());
}
#Override
public void mouseReleased(MouseEvent evt){
btnOK.setBorder(BorderFactory.createLineBorder(new Color(244, 171, 50)));
disposeMessage();
Elementos.getFrame().setAlwaysOnTop(true);
}
});
layer.moveToFront(btnOK);
return layer;
}
private void disposeMessage(){
messageEdge.setModal(false);
messageEdge.setVisible(false);
messageEdge.dispose();
}
}
Hope it may help you and others, Cheers...

Categories

Resources