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);
}
}
}
Related
I am working on my first college project. I just start coding. I am making a washing machine for this project.
How can I make my graphics rotate when pressed the start button and stop when I pressed the stop button? Also, I have a countdown timer, once it times out, my graphics will stop rotating as well. (They are in different packages).
Here is my code(Main, first package)
package Main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import Timer.*;
public class WashingMachine extends JPanel implements ActionListener{
JFrame frame = new JFrame("Washing Machine");
JLabel label_numCloth = new JLabel("Number of Clothes");
JTextField num_tf = new JTextField("",10);
JButton com_bt = new JButton("Compute");
JButton start_bt = new JButton("Start");
JButton stop_bt = new JButton("Stop");
JLabel label_cost = new JLabel("Cost: ");
JLabel label_price = new JLabel("1 Kg = 4 Baht");
JPanel panel_num = new JPanel();
JPanel panel_cost = new JPanel();
JPanel panel_r = new JPanel();
JPanel panel_l = new JPanel();
JPanel panel_start_stop = new JPanel();
static double cost;
WashingMachine(){
panel_num.setLayout(new GridLayout(3,1));
panel_num.add(label_numCloth);
panel_num.add(num_tf);
panel_num.add(com_bt);
panel_cost.setLayout(new GridLayout(2,1));
panel_cost.add(label_cost);
panel_cost.add(label_price);
panel_start_stop.setLayout(new GridLayout(1,2));
panel_start_stop.add(start_bt);
panel_start_stop.add(stop_bt);
panel_l.add(panel_start_stop);
panel_r.setLayout(new BorderLayout());
panel_r.add(panel_num,BorderLayout.NORTH);
panel_r.add(panel_cost,BorderLayout.CENTER);
frame.add(this);
setLayout(new BorderLayout());
frame.add(panel_r,BorderLayout.EAST);
frame.add(panel_l,BorderLayout.WEST);
frame.setBackground(Color.BLACK);
frame.setSize(250,250);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label_price.setForeground(Color.red);
com_bt.addActionListener(this);
start_bt.addActionListener(this);
stop_bt.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
//Calculate price
double cloth = Double.parseDouble(num_tf.getText());
cost = cloth*4;
label_cost.setText("Cost: " + cost + " " + "Baht");
if(e.getSource() == start_bt) {
repaint();
Simulation sim = new Simulation();
Countdown cout_d = new Countdown();
if(e.getSource() == start_bt) {
repaint();
}
}
}
}
Here is my code (Simulation for washing machine,second package)
package Timer;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Simulation extends JPanel implements ActionListener{
JFrame frame = new JFrame("Simulation and Timer");
Timer timer = new Timer(500, this);
int startAngle = 0;
int shift =5;
public Simulation(){
timer.start();
frame.add(this);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillOval(87,90,275,275);
g.setColor(new Color(0,255,255));
g.fillOval( 100,100 ,250,250 );
g.setColor(Color.white);
g.fillOval(275,120,20,20);
}
public void actionPerformed(ActionEvent e){
}
}
package Timer;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.awt.*;
public class Countdown {
JFrame frame = new JFrame("Countdown Clock");
JLabel counter_label = new JLabel("");
Timer timer;
private int second = 0;
private int minute = 40;
String ddSecond;
String ddMinute;
DecimalFormat dFormat = new DecimalFormat("00");
Font font = new Font("Arial",Font.BOLD,20);
public static void main(String[] args) {
new Countdown();
}
public Countdown() {
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
counter_label.setBounds(120, 100,50 ,50 );
counter_label.setHorizontalAlignment(JLabel.CENTER);
counter_label.setFont(font);
frame.setBackground(Color.black);
frame.add(counter_label);
frame.setVisible(true);
counter_label.setText("40:00");
countdownTimer();
timer.start();
}
public void countdownTimer() {
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
second--;
ddSecond = dFormat.format(second);
ddMinute = dFormat.format(minute);
counter_label.setText(ddMinute + ":" + ddSecond);
if(second==-1) {
second = 59;
minute--;
ddSecond = dFormat.format(second);
ddMinute = dFormat.format(minute);
counter_label.setText(ddMinute + ":" + ddSecond);
}
if(minute==0 && second==0 ) {
timer.stop();
}
}
});
}
}
Hello I am new to JAVA and recently studied graphics but got stuck on how to draw a circle (I learn on my own through Google) I would be happy if you help me with the following lines of code
(Do not refer to the background sub button)
public class Panel_ {
static JPanel panel1 = new JPanel();
public static Color randomColor() {
int r = (int) Math.round(Math.random() * 255 - 1);
int g = (int) Math.round(Math.random() * 255 - 1);
int b = (int) Math.round(Math.random() * 255 - 1);
Color R_col = new Color(r, g, b);
System.out.println(R_col);
return R_col;
}
public static void Panel() {
var color_changer = new JButton("To change color");
color_changer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel1.setBackground(randomColor());
}
});
var Panel = new JPanel();
Panel.add(color_changer);
Panel.setBackground(Color.blue);
panel1.setBackground(Color.black);
panel1.setPreferredSize(new Dimension(400, 430));
var frame = new JFrame("Color changer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel1, BorderLayout.NORTH);
frame.getContentPane().add(Panel, BorderLayout.SOUTH);
frame.pack();
frame.setSize(500, 500);
frame.setBackground(Color.blue);
frame.setVisible(true);
}
public void paintCircle(Graphics g) {
g.setColor(Color.blue);
g.fillOval(60, 80, 100, 100);
}
public static void main(String args[]) {
Panel();
}
}
Use paintComponent for panel1 which I changed the name to topPanel in the runnable code below:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Panel extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel topPanel;
private JPanel panel;
private JButton color_changer;
public Panel() {
initializeForm();
}
private void initializeForm() {
setAlwaysOnTop(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.blue);
color_changer = new JButton("To change color");
color_changer.addActionListener((ActionEvent e) -> {
topPanel.setBackground(randomColor());
});
topPanel = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillOval(60, 80, 100, 100);
};
};
panel = new JPanel();
panel.add(color_changer);
panel.setBackground(Color.blue);
topPanel.setBackground(Color.black);
topPanel.setOpaque(true);
topPanel.setPreferredSize(new Dimension(400, 430));
getContentPane().add(topPanel, BorderLayout.NORTH);
getContentPane().add(panel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new Panel().setVisible(true);
});
}
public static Color randomColor() {
int r = (int) Math.round(Math.random() * 255 - 1);
int g = (int) Math.round(Math.random() * 255 - 1);
int b = (int) Math.round(Math.random() * 255 - 1);
Color R_col = new Color(r, g, b);
System.out.println(R_col);
return R_col;
}
}
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'm doing the double actionlistener exercise detailed in Head First Java, and learn about inner classes, but for some reason my code is not compiling. I'm getting argument invalid errors when I try to call the addActionListener method for JButton.
TwoButtons.java:
import javax.swing.*;
import java.awt.*;
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main(String[] args){
TwoButtons gui = new TwoButtons();
gui.go();
}
public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("Change Label");
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton("Change circle");
colorButton.addActionListener(new ColorListener());
label = new JLabel("I'm a label");
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(300,300);
frame.setVisible(true);
}
class LabelListener implements ActionListener{
public void actionPerformed(ActionEvent event){
label.setText("OUch!");
}
}//close inner class
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent event){
frame.repaint();
}
} //close inner class
}
MyDrawPanel.java: (no errors)
import java.awt.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g;
int red = (int)(Math.random()*255);
int green = (int)(Math.random()*255);
int blue = (int)(Math.random() * 255);
Color startColor = new Color(red,green,blue);
red = (int)(Math.random()*255);
green = (int)(Math.random()*255);
blue = (int)(Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70,70, startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
}
}
You need to import ActionEvent and ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
They reside under java.awt.event.* and not java.awt.*.
If you use an IDE like Eclipse, you can easily import all needed classes with a simple action.
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);
}
}