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);
}
}
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();
}
});
}
}
import javax.swing.*; // Graphics import java.awt.Color; // Graphics Colors
import java.awt.event.ActionListener; // Events
import java.awt.event.ActionEvent; // Events
public class ButtonDemo_Extended implements ActionListener {
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel, redScore, blueScore;
JButton redButton, blueButton, resetButton;
public JPanel createContentPane() {
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(10, 10);
titlePanel.setSize(250, 30);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(0, 0);
redLabel.setSize(120, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(130, 0);
blueLabel.setSize(120, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(260, 30);
totalGUI.add(scorePanel);
redScore = new JLabel("" + redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(120, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
blueScore = new JLabel("" + blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(120, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(260, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(120, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(130, 0);
blueButton.setSize(120, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 40);
resetButton.setSize(250, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redButton) {
redScoreAmount = redScoreAmount + 1;
redScore.setText("" + redScoreAmount);
JOptionPane.showMessageDialog(buttonPanel, "GOOOOOOOOOOOL");
} else if (e.getSource() == blueButton) {
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText("" + blueScoreAmount);
JOptionPane.showMessageDialog(buttonPanel, "GOOOOOOOOOOOL");
} else if (e.getSource() == resetButton) {
redScoreAmount = 0;
blueScoreAmount = 0;
redScore.setText("" + redScoreAmount);
blueScore.setText("" + blueScoreAmount);
}
}
private static void createAndShowGUI() { // For this Class Onlyyyyyyyyyyyy .
JFrame.setDefaultLookAndFeelDecorated(true); // Style Of Frame
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
} }
this might be one way to do it:
`
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AutoCloseJOption {
private static final int TIME_VISIBLE = 3000;
public static void main(String[] args) {
final JFrame frame1 = new JFrame("My App");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(100, 100);
frame1.setLocation(100, 100);
JButton button = new JButton("My Button");
frame1.getContentPane().add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = new JOptionPane("Message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(null, "Title");
dialog.setModal(false);
dialog.setVisible(true);
new Timer(TIME_VISIBLE, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
}).start();
}
});
frame1.setVisible(true);
}
}`
I hope this helps you
I am using the following code to test the bound values of a JFrame of mine:
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1 = this.getBounds();
this.setExtendedState(JFrame.MAXIMIZED_BOTH); //this == JFrame
r2 = this.getBounds();
At first, I thought that the values of r2 (regarding x, y, width and height) would be different, since the frame is automatically resized. However, the variables r1 and r2 seems to be (almost) equal, according to the Debugger.
Why does this happen? What should I do in order to get the new values of the maximized JFrame?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class NewGUI extends JFrame {
private JPanel contentPane;
private List list;
private JButton btnSelectAgent;
private JTextField textField;
private JButton btnBrowse;
private JButton btnPreviousStep2;
private JButton btnLoad;
private JButton btnPreviousStep3;
private JButton btnStart;
private File file = null;
ImageIcon icon = new ImageIcon("image.gif");
Border blackline = BorderFactory.createLineBorder(Color.black);
private JPanel firstStepPanel;
private JPanel secondStepPanel;
private JPanel thirdStepPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewGUI frame = new NewGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public NewGUI() {
super("GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 681, 422);
contentPane = new JPanel();
contentPane.setForeground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null); //centered location
contentPane.setLayout(null);
//test codes begin
Insets insets = this.getInsets();
Rectangle r = new Rectangle();
Dimension d = new Dimension();
r.x = 0;
r.y = 0;
r.width = 1280;
r.height = 1024;
r = this.getMaximizedBounds();
d = this.getMaximumSize();
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
Dimension d1 = new Dimension();
Dimension d2 = new Dimension();
d1 = this.getSize();
r1 = this.getBounds();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
r = this.getMaximizedBounds();
r2 = r1;
this.setMaximizedBounds(r);
r2.width = this.getWidth();
r2.height = this.getHeight();
d2 = this.getSize();
//test codes end
/* pane.setLayout(null);
JButton b1 = new JButton("one");
JButton b2 = new JButton("two");
JButton b3 = new JButton("three");
pane.add(b1);
pane.add(b2);
pane.add(b3);
JPanel pane = new JPanel();
Insets insets = this.getInsets();
Rectangle r = new Rectangle();
r.x = insets.left;
r.y = insets.top;
JFrame frame = new JFrame();
frame.getInsets();
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top, size.width, size.height);
Rectangle r = new Rectangle();
r.x = 1;
r.y = 2;
b1.setBounds
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top, size.width, size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top, size.width + 50, size.height + 20);
...//In the main method:
Insets insets = frame.getInsets();
frame.setSize(300 + insets.left + insets.right, 125 + insets.top + insets.bottom);
*/
firstStepPanel = new JPanel();
firstStepPanel.setBounds(10, 10, 194, 363);
contentPane.add(firstStepPanel);
//this.add(firstStepPanel, BorderLayout.WEST);
firstStepPanel.setLayout(null);
firstStepPanel.setBorder(
BorderFactory.createTitledBorder(blackline, "Agent selection"));
//makeFrameFullSize(contentPane); //aparentemente nao funcionando
list = new List();
list.setBounds(10, 31, 169, 203);
firstStepPanel.add(list);
list.setMultipleSelections(true);
btnSelectAgent = new JButton("Select Agent");
btnSelectAgent.setBounds(10, 274, 169, 34);
firstStepPanel.add(btnSelectAgent);
secondStepPanel = new JPanel();
secondStepPanel.setBorder(
BorderFactory.createTitledBorder(blackline, "file selection"));
secondStepPanel.setBounds(214, 11, 266, 362);
contentPane.add(secondStepPanel);
//this.add(secondStepPanel, BorderLayout.CENTER);
secondStepPanel.setLayout(null);
btnLoad = new JButton("Load");
btnLoad.setBounds(78, 317, 118, 34);
secondStepPanel.add(btnLoad);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (file == null) {
showMessage("Please, select a file on the upper options");
} else {
disableSecondStep();
enableThirdStep();
}
}
});
btnLoad.setEnabled(false);
textField = new JTextField();
textField.setBounds(10, 29, 157, 34);
secondStepPanel.add(textField);
textField.setEnabled(false);
textField.setColumns(10);
textField.setText("P:\\\\");
btnBrowse = new JButton("Browse");
btnBrowse.setBounds(167, 29, 89, 35);
secondStepPanel.add(btnBrowse);
btnBrowse.setEnabled(false);
btnPreviousStep2 = new JButton("<< Previous");
btnPreviousStep2.setBounds(78, 272, 118, 34);
secondStepPanel.add(btnPreviousStep2);
btnPreviousStep2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enableFirstStep();
disableSecondStep();
}
});
btnPreviousStep2.setEnabled(false);
thirdStepPanel = new JPanel();
thirdStepPanel.setBorder(
BorderFactory.createTitledBorder(blackline, "Process initialization"));
thirdStepPanel.setBounds(490, 10, 165, 362);
contentPane.add(thirdStepPanel);
//this.add(thirdStepPanel, BorderLayout.EAST);
thirdStepPanel.setLayout(null);
//thirdStepPanel.setSize(100, r.height);
//r.x += 100;
//thirdStepPanel.setBounds(r);
//thirdStepPanel.setBounds(r.x,r.y, r.width, r.height);
//thirdStepPanel.setAlignmentX(r.x);
//thirdStepPanel.setAlignmentY(r.y);
btnPreviousStep3 = new JButton("<< Previous");
btnPreviousStep3.setBounds(7, 56, 151, 34);
thirdStepPanel.add(btnPreviousStep3);
btnPreviousStep3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enableSecondStep();
disableThirdStep();
}
});
btnPreviousStep3.setEnabled(false);
btnStart = new JButton(icon);
btnStart.setBounds(7, 101, 151, 159);
thirdStepPanel.add(btnStart);
btnStart.setEnabled(false);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMessage("Process started!");
}
});
//btnStart.setBackground(Color.RED);
btnStart.setForeground(Color.BLACK);
btnStart.setOpaque(false);
btnStart.setBorderPainted(false);
btnStart.setContentAreaFilled(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser("some folder blablabla");
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
//System.out.println(file.getPath());
textField.setText(file.getPath());
} else if (returnVal == JFileChooser.CANCEL_OPTION) {
//System.out.println("File dialog cancelled");
} else if (returnVal == JFileChooser.ERROR_OPTION) {
showMessage("Error in the file dialog!");
}
}
});
btnSelectAgent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (list.getSelectedItems().length == 0) {
showMessage("Please, select an Agent in the Agent's list");
} else {
disableFirstStep();
enableSecondStep();
}
}
});
list.add("Zemax");
list.add("Roundspot");
list.add("CCDCamera");
list.add("HexapodXYTable");
/* this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.add(firstStepPanel, BorderLayout.WEST);
this.add(secondStepPanel, BorderLayout.CENTER);
this.add(thirdStepPanel, BorderLayout.EAST);*/
}
private void showMessage(String msg) {
JOptionPane.showMessageDialog(this, msg);
}
private void enableFirstStep() {
list.setEnabled(true);
btnSelectAgent.setEnabled(true);
}
private void enableSecondStep() {
textField.setEnabled(true);
btnBrowse.setEnabled(true);
btnPreviousStep2.setEnabled(true);
btnLoad.setEnabled(true);
}
private void enableThirdStep() {
btnPreviousStep3.setEnabled(true);
btnStart.setEnabled(true);
}
private void disableFirstStep() {
list.setEnabled(false);
btnSelectAgent.setEnabled(false);
}
private void disableSecondStep() {
textField.setEnabled(false);
btnBrowse.setEnabled(false);
btnPreviousStep2.setEnabled(false);
btnLoad.setEnabled(false);
}
private void disableThirdStep() {
btnPreviousStep3.setEnabled(false);
btnStart.setEnabled(false);
}
private void makeFrameFullSize(JPanel panel) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
panel.setSize(screenSize.width, screenSize.height);
}
BufferedImage image;
public void nextButton() {
try {
image = ImageIO.read(new File("C:\\Users\\BAYGONCALVE\\Desktop\\red_button.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawImage(image, 0, 0, null);
}
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
}
The main problem is, the frame isn't actually visible.
For example, after I cleaned up your code a little I get...
r1 = java.awt.Rectangle[x=1280,y=820,width=0,height=0]
r2 = java.awt.Rectangle[x=1280,y=820,width=0,height=0]
d1 = java.awt.Dimension[width=0,height=0]
d2 = java.awt.Dimension[width=0,height=0]
(took out the call to setBounds and few other things). Based on the fact that the window hasn't been realised yet (not shown), it's not surprising to me that the sizes don't actually change, because until you show the window, it has no context of which GraphicsDevice it will be shown on, therefore no means by which it can determine what the maximum size actually would be...
If you call setVisible(true) in the constructor, before calling setExtendedState(JFrame.MAXIMIZED_BOTH) I get...
r1 = java.awt.Rectangle[x=1214,y=801,width=132,height=38]
r2 = java.awt.Rectangle[x=-8,y=32,width=2576,height=1576]
d1 = java.awt.Dimension[width=132,height=38]
d2 = java.awt.Dimension[width=2576,height=1576]
Side notes...
Don't use null layouts. Pixel perfect layouts are an illusion in modern UI design, you have no control over fonts, DPI, rendering pipelines or other factors that will change the way that you components will be rendered on the screen. Swing was designed to work with layout managers to overcome these issues. If you insist on ignoring these features and work against the API design, be prepared for a lot of headaches and never ending hard work...
Don't mix heavy and light weight components, AWT and Swing components don't play well together, instead of using java.awt.List try using javax.swing.JList instead
Try this
frame.getWidth() and frame.getHeight()
To get size of JFrame without the title and other borders
frame.getContentPane().getSize();
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Issues with ActionListener (Java)
I am trying to implement action listener on two buttons in JFrame, but the issue is one of the two button is performing both the functions; but i've not configured it to do so.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyChangingCirlce implements ActionListener {
JButton colorButton, labelButton;
JLabel myLabel;
MyDrawPanel mdp;
JFrame frame;
public static void main(String[] args) {
MyChangingCirlce mcc = new MyChangingCirlce();
mcc.createFrame();
} // end of main
public void createFrame() {
frame = new JFrame();
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
myLabel = new JLabel("I'm a label");
mdp = new MyDrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, mdp);
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, myLabel);
colorButton.addActionListener(this);
labelButton.addActionListener(this);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == colorButton) {
frame.repaint();
} else {
myLabel.setText("That's it");
}
}
}
My labelButton is performing both the action only 1 time; i.e it changes the color of the circle along with the label text.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
public void paintComponent(Graphics g)
{
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue= (int) (Math.random() * 255);
Color randomColor = new Color(red,green,blue);
g.setColor(randomColor);
g.fillOval(20,70,100,100);
}
}
You override colorButton and labelButton. So the 'else' is always kicking in. Changing the label will cause a redraw.
change
JButton colorButton = new JButton("Changing Colors");
JButton labelButton = new JButton("Change Label");
to
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
After writing myself a class to test it, I came about with this:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Date;
public class Foo implements ActionListener {
JButton colorButton, labelButton;
JLabel myLabel;
JFrame frame;
MyDrawPanel mdp;
public static void main(String[] args) {
Foo mcc = new Foo();
mcc.createFrame();
} //end of main
public void createFrame() {
frame = new JFrame();
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
myLabel = new JLabel("I'm a label");
mdp = new MyDrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
mdp.setPreferredSize(new Dimension(150, 150));
jsp.setLeftComponent(mdp);
frame.setBounds(10, 10, 600, 600);
JPanel right = new JPanel();
right.add(BorderLayout.SOUTH, colorButton);
right.add(BorderLayout.EAST, labelButton);
right.add(BorderLayout.WEST, myLabel);
jsp.setRightComponent(right);
frame.getContentPane().add(jsp);
colorButton.addActionListener(this);
labelButton.addActionListener(this);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == colorButton) {
myLabel.setText("Color button's it");
frame.repaint();
} else {
myLabel.setText("That's it" + new Date().toString());
}
}
public class MyDrawPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillOval(20, 70, 100, 100);
}
}
}
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