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();
}
}
}
Related
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();
}
});
}
}
I'm using Java with Window builder
I've created a 4x4 grid out of jlabels (each grid point is a different jlabel) on my jframe.
I also have a button called btnPlace.
What I want to do is have an image appear at a random grid point on button click. The image file is called red.png which is a red circle. The image can appear at any grid point except the grid point number 1.
Sort of like this: http://i.stack.imgur.com/bBn6D.png
Here's my code:
public class grid {
public static void main (String[] args)
{
JFrame grid =new JFrame();
grid.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
JPanel set = new JPanel();
set.setBounds(10, 11, 307, 287);
grid.getContentPane().add(set);
set.setLayout(new GridLayout(4, 4, 0, 0));
JLabel a = new JLabel("");
set.add(a);
JLabel b = new JLabel("");
set.add(b);
JLabel c = new JLabel("");
set.add(c);
^^ this repeats up to JLabel p. just to save time.
JButton btnPlace = new JButton("Place");
grid.getContentPane().add(btnPlace);
grid.setVisible(true);
} }
Here is fully working example:
On pressing button it'll draw Image on randomly selected JLabel
package stackoverflow;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DummyColor {
private JFrame frame;
private JLabel[] labels = new JLabel[4];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DummyColor window = new DummyColor();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DummyColor() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 657, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lbl1 = new JLabel("First BOX");
lbl1.setBounds(10, 11, 273, 194);
frame.getContentPane().add(lbl1);
JLabel label = new JLabel("Second BOX");
label.setBounds(336, 11, 273, 194);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("Third BOX");
label_1.setBounds(10, 251, 273, 194);
frame.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Fourth BOX");
label_2.setBounds(347, 251, 273, 194);
frame.getContentPane().add(label_2);
labels[0] = lbl1;
labels[1] = label;
labels[2] = label_1;
labels[3] = label_2;
JButton btnPick = new JButton("Place");
btnPick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon imageIcon = new ImageIcon(DummyColor.class.getResource("/red.jpg"));
int randInt = randInt(1, 4);
System.out.println(randInt);
for (int i = 0; i < labels.length; i++) {
JLabel jLabel = labels[i];
if (i == randInt - 1) {
jLabel.setIcon(imageIcon);
} else {
jLabel.setIcon(null);
}
}
}
});
btnPick.setBounds(10, 439, 57, 23);
frame.getContentPane().add(btnPick);
}
private static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
I would create a custom JPanel and add a MouseListener. Whenever the Panel is clicked, an image will be draw at that point clicked on the panel
public class grid{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.add(new MyPanel());
}
}
class MyPanel extends JPanel{
Point p;
BufferedImage img;
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
p = e.getLocationOnScreen();
repaint();
}
});
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
try{
img = ImageIO.read("someImage.png");
}catch(Exception e){e.printStackTrace();}
g.drawImage(img, p.getX(), p.getY(), width, height, this);
}
}
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;
}
}
}
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();
}
});
}
}
I am trying to position a JButton with a null layout but it will not show up, if i switch to gridlayout they are only lined up in the middle no matter what i change. How can i set the position and size of my button?
In Frame
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
//setLayout(new GridLayout(1, 1, 0, 0));
setLayout(null);
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
In Launcher
package ThreeD;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
public Launcher() {
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
rplay = new Rectangle(20, 50, 80, 40);
roptions = new Rectangle(20, 50, 80, 40);
rhelp = new Rectangle(20, 50, 80, 40);
rmainMenu = new Rectangle(20, 50, 80, 40);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
}
}
Child containers do not inherit their parent's LayoutManager, so in the constructor of Launcher I would recommend:
public Launcher() {
this.setLayout(null);
//this.setLayout(new GroupLayout(2, 2)); // I strongly recommend you try this though and get rid of the setBounds and rects
drawButtons();
}
Edit: LayoutManagers layout their components, but not what is inside a component. That's why it isn't enough to just set the frame's layout.
My guess is you are not setting the size or layout before adding the JPanel Launcher. So the buttons are displaying fine, but the JPanel is not. Try putting in:
launcher.setBounds( new Rectangle( 0, 0, 200, 200 ) );
or what ever size you need.
See if that works