I have two forms. First one is to decide button numbers by using jslider. Second form is to display jbuttons according to jslider value. When i click jbutton2, the second form shows and display buttons. It is working perfectly. However, I want to create jbutton without clicking jbutton2 in the first form.
Instead, when I change jslider, it should create buttons on the second form at the run time and once i change jslider it should create that amount of button again on the second form and refresh the second form buttons number according to jslider value.
I have tried revalidate();, repaint(); but they do not work, they dont refresh the second form.
So, How can I refresh second form when the jslider ,that is on the first form, changes ?
Actually you should provide a piece of code so we can understand it better.
But generally i think i could understand what you mean (if i'm not wrong).
Basically you need the layout manager on the second form.
here is a code sample, i hope it can generally answer your need.
Code for the first form
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class FirstForm extends JFrame {
JButton fbtn = new JButton("Show F2");
JSlider fslider = new JSlider(1, 10);
SecondForm fsecond = new SecondForm();
public FirstForm(){
setSize(200,200);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(fbtn,BorderLayout.NORTH);
getContentPane().add(fslider,BorderLayout.CENTER);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fsecond.setVisible(true);
}
});
fslider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
fsecond.setBtnCount(fslider.getValue());
}
});
}
public static void main(String[] args) {
// TODO code application logic here
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new FirstForm().setVisible(true);
}
});
}
}
Code for the second form
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SecondForm extends JFrame {
Vector fbtns = new Vector();
int fshowbtncount=1;
GridBagConstraints gbc = new GridBagConstraints();
public SecondForm(){
setSize(200, 200);
setLocation(201, 0);
getContentPane().setLayout(new GridBagLayout());
fbtns.add(new JButton("Button ".concat(String.valueOf(fbtns.size()+1))));
invalidateForm();
}
private void invalidateForm(){
gbc.fill = GridBagConstraints.VERTICAL;
for (int i=0; i<fbtns.size(); i++) {
getContentPane().remove((Component)fbtns.get(i));
}
int y=0;
for (int i=0; i<fshowbtncount; i++) {
gbc.gridx=0;
gbc.gridy=y++;
getContentPane().add((Component)fbtns.get(i),gbc);
}
pack();
invalidate();
}
public void setBtnCount(int cnt){
if (cnt>=0 && cnt!=fshowbtncount) {
fshowbtncount = cnt;
while (fbtns.size()<cnt) {
fbtns.add(new JButton("Button ".concat(String.valueOf(fbtns.size()+1))));
}
invalidateForm();
}
}
}
Hope this can help you out.
Related
I have got a set of nodes in my program, each have a specific x,y location.
and each have a set of image icons.
I want to draw image animation for each nodes at its specific location.
Here is my code: (this only shows the last image which i know why!.)
public void showPicture() {
//nodes :
for(int i=0;i<thisGraph.getNode().size();i++){
if(thisGraph.getNode().get(i).getImageIcon()!=(null)){
for(int j=0;j<thisGraph.getNode().get(i).getImageIcon().size();j++){
if(j>0)
lables.get(lables.size()-1).setVisible(false);
JLabel jLabel1 = new JLabel();
lables.add(jLabel1);
jLabel1.setLayout(new GridBagLayout());
jLabel1.setIcon(thisGraph.getNode().get(i).getImageIcon().get(j));
jLabel1.setVisible(true);
jLabel1.setBounds((int)thisGraph.getNode().get(i).getX(),(int)thisGraph.getNode().get(i).getY(),195,163);
jPanel1.add(jLabel1);
}
}
}
}
This method showPicture() is called in a buttonActionListener.
And I also have another button which I want it to stop the image animations for all labels.
What I have tried:
Thread.sleep() -> it freezes the button and it only shows the last image
I figured I had to use timer, but through all the topics I went they only used it on one label, not multiple labels.
Edit
->
i read those examples given in the comments . and here is what i have resolved but it still is freezes the button and doesn't works :
int j = 0;
public void showPicture(){
//nodes :
for(int i=0;i<thisGraph.getNode().size();i++){
if(thisGraph.getNode().get(i).getImageIcon()!=(null)){
j=0;
while( j<thisGraph.getNode().get(i).getImageIcon().size()){
if(j>0)
lables.get(lables.size()-1).setVisible(false);
JLabel jLabel1 = new JLabel();
lables.add(jLabel1);
jLabel1.setLayout(new GridBagLayout());
jLabel1.setIcon(thisGraph.getNode().get(i).getImageIcon().get(j));
jLabel1.setVisible(true);
jLabel1.setBounds((int)thisGraph.getNode().get(i).getX(),(int)thisGraph.getNode().get(i).getY(),195,163);
jPanel1.add(jLabel1);
//
ActionListener act;
act = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLabel1.setVisible(true);
j++;
}
};
Timer timer = new Timer(1000, act );
timer.start();
timer.stop();
//
}
}
}}
Swing is single threaded and not thread safe. This means that you shouldn't block the Event Dispatching Thread with long running or blocking operations, like Thread.sleep. You should also, only ever update the UI (or anything it relies on) from within the context of the Event Dispatching Thread.
See Concurrency in Swing for more details.
Probably the simplest solution to your problem is to use a Swing Timer.
The idea is a you use a single Timer to act as the "main animation loop", changing the properties of ALL the objects you need updated within it.
The following is pretty basic example, it animates 100 JLabels, simply changing their background color with a randomly picked color
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private List<JLabel> nodes = new ArrayList<>(100);
private Random random = new Random();
private Color[] colors = new Color[] { Color.RED, Color.GREEN, Color.BLUE, Color.BLACK, Color.MAGENTA};
public TestPane() {
setLayout(new GridLayout(0, 10));
for (int index = 0; index < 100; index++) {
JLabel label = new JLabel();
label.setBorder(new EmptyBorder(5, 5, 5, 5));
label.setOpaque(true);
label.setBackground(pickColor());
nodes.add(label);
add(label);
}
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (JLabel label : nodes) {
label.setBackground(pickColor());
}
}
});
timer.start();
}
protected Color pickColor() {
return colors[random.nextInt(colors.length)];
}
}
}
See How to Use Swing Timers for more details
I'm trying to make a grid of 20px x 20px buttons that I define as "cells", blank by default, no special decorations such as shading, and change color when clicked. (They are meant to show "1" just for testing purposes). I make a Cell class to define these buttons, give each an ActionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Cell implements ActionListener
{
private JButton button;
private EditorPanel editorPanel;
public Cell(EditorPanel editorPanel){
button = new JButton("1'");
button.addActionListener(listener -> colorCell());
button.setPreferredSize(new Dimension(20,20));
button.setMargin(new Insets(0,0,0,0));
button.setOpaque(true);
button.setContentAreaFilled(false);
this.editorPanel = editorPanel;
}
public JButton getButton() {
return button;
}
public void colorCell()
{
button.setBackground(Color.BLACK);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
and then use an array of Cell objects (cells) in my EditorPanel class to create a grid of these buttons with dimensions defined by "col" and "row".
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EditorPanel{
public JFrame jframe;
public JPanel jpanel;
public static EditorPanel editorPanel;
public Render render;
public static final int col = 45, row = 45, tile_size=20;
public static final int panelWidth=900, panelHeight=900;
public Dimension dim;
public int coloredPixels;
public Cell[][] cells;
public void getFrame() {
editorPanel = new EditorPanel();
dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe = new JFrame("Pixel Art Creator");
jframe.setVisible(true);
jframe.setSize(panelWidth+17, panelHeight+40);
jframe.setLocation(dim.width/2 - jframe.getWidth()/2, dim.height/2 - jframe.getHeight()/2);
jframe.add(render = new Render());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel addCells()
{
cells=new Cell[row][col];
JPanel panel = new JPanel(new GridLayout(row, col));
for(int i = 0; i< row; i++){
for(int j = 0; j<col; j++){
cells[i][j] = new Cell(this);
panel.add(cells[i][j].getButton());
}
}
return panel;
}
public static void main (String[] args)
{
editorPanel = new EditorPanel();
editorPanel.getFrame();
editorPanel.addCells();
}
}
I then try to add each created Cell object that I attempted to put into the cells array in the addCells() method and add it to my JPanel. When I run this code I don't get any buttons, meaning that these buttons aren't being added to JPanel. How should I go about this?
So, two "significant" issues:
editorPanel.addCells(); never adds the JPanel that it creates to anything, so it will never be displayed
Calling JFrame#setVisible BEFORE you've finished establishing the UI can cause the UI elements not to show up on the UI. You can fix this by calling revalidate and repaint on the container which is changed, but if possible, simply get the UI established first, then make it visible
I would, however, suggest a slight change in approach. Rather then making Cell a class which contains a JButton, and then exposing that button to other aspects of your UI, I would make Cell a component and simply add it to the what ever container you want, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int y = 0; y < 20; y++) {
gbc.gridy = y;
for (int x = 0; x < 20; x++) {
gbc.gridx = x;
add(new Cell(), gbc);
}
}
}
}
public class Cell extends JPanel {
public Cell() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
colorCell();
}
});
setBorder(new LineBorder(Color.GRAY));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
protected void colorCell() {
if (getBackground() != Color.DARK_GRAY) {
setBackground(Color.DARK_GRAY);
} else {
setBackground(null);
}
}
}
}
Now, I've just used a plain old JPanel in the this case, but you could just as easily extend from a JButton or JToggledButton ... but I might be tempted to use a factory pattern instead, but that's me.
The purpose of using a GridBagLayout is to allow the frame and outer containers to be resized without changing the size of the Cells themselves, unlike GridLayout, which will try and make the cells fill the available space
I'm failing to understand why my yankee and whiskey JButtons aren't working. Right now I only want them to close the program when romeo is greater than 1 and sierra is greater than 1.
import java.awt.*;
import java.lang.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.util.Scanner;
public class AlphaMenu extends JFrame /*implements actionPerformed*/
{
private GraphicsDevice gamma;
public JButton charlie, zulu, yankee, xray;
public JFrame beta;
public JPanel delta, echo, foxtrot, golf, hotel;
public JTextArea whiskey, victor;
public BorderLayout uniform;
public ImageIcon bg;
public JLabel tango;
public int sierra, romeo;
public Integer quebec, papa;
public ActionEvent oscar;
public ActionEvent november;
public AlphaMenu()
{
//Initialization of Objects
charlie = new JButton("EXIT");
zulu = new JButton("Enter Time");
yankee = new JButton("Enter Amount of Money");
xray = new JButton("Calculate");
sierra = 0;
romeo = 0;
quebec = new Integer(0);
papa = new Integer(0);
whiskey = new JTextArea(2, 15);
victor = new JTextArea(2, 15);
bg = new ImageIcon("background.gif");
beta = new JFrame();
delta = new JPanel();
echo = new JPanel();
foxtrot = new JPanel();
golf = new JPanel();
hotel = new JPanel();
uniform = new BorderLayout();
ImageIcon bg = new ImageIcon("background.gif");
tango = new JLabel("");
tango.setIcon(bg);
//Modification of panels
beta.add(delta, uniform.PAGE_END);
beta.add(golf, uniform.PAGE_START);
beta.add(echo, uniform.LINE_START);
beta.add(foxtrot, uniform.LINE_END);
beta.add(hotel, uniform.CENTER);
golf.add(tango);
//Modification of JButton charlie & adding of JButtons
charlie.setPreferredSize(new Dimension(100, 50));
delta.add(charlie);
charlie.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
echo.add(whiskey);
echo.add(yankee);
foxtrot.add(victor);
foxtrot.add(zulu);
//Modification of JFrame beta
beta.setUndecorated(true);
beta.setExtendedState(JFrame.MAXIMIZED_BOTH);
beta.setResizable(false);
beta.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
beta.setVisible(true);
}
public void buttonSetup() throws NumberFormatException
{
//Modification of JButton yankee & JTextArea whiskey & int sierra
romeo = quebec.parseInt(whiskey.getText());
yankee.setPreferredSize(new Dimension(300, 50));
yankee.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent oscar)
{
System.exit(0);
}
});
//Modification of JButton zulu & JTextArea victor & int romeo
sierra = papa.parseInt(victor.getText());
zulu.setPreferredSize(new Dimension(300, 50));
zulu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent november)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
}
public static void main(String[] args)
{
new AlphaMenu();
}
}
So, you have two JTextArea (JTextField would probably be better) and a button. you want some buttons to execute exit when the text of both textareas is an integer greater than 1.
seems that your buttonSetup() function isn't called anywhere.
Anyway, I'd create an ActionListener that reads the texts, converts to integer, tests your condition and executes exit(). This ActionListener should be added to all the buttons you want to perform the action
final ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
final int intRomeo = Integer.parseInt(romeo.getText());
final int intSierra = Integer.parseInt(sierra .getText());
if (intRomeo > 1 && intSierra > 1) {
// whatever you want to do
System.exit(0);
}
} catch (/*NumberFormat*/ Exception e) {
// ...not integers
}
};
}
whiskey.addActionListener(al);
yankee.addActionListener(al);
I have to add: the variable names you are using are really bad. Consider choosing something more significative.
For starters, readability...it would probably help the "sloppiness" if you used more appropriate names for your variables, indented different sections of code, and used comments to help describe sections in layman's terms. Maybe "btnExit" and "btnCalculate" would help make things a little easier to navigate.
Moving forward, you also don't have two different classes here, you have one class with several methods. Which is fine but wanted to inform you of that. I think maybe you need to add the buttons to their panels after your action listeners and formatting for each button. I'm just getting into some swing stuff myself and I've noticed moving the .add() functions around in the code has helped when I run into issues like this. Try the following bellow. I indented and used new naming conventions for the comments, but the code uses your convention.
//add the pnlEcho to frmBeta
beta.add(echo, uniform.LINE_START);
//format btnYankee
yankee.setPreferredSize(new Dimension(300, 50));
//btnYankee action listener
yankee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { //default action event
System.exit(0); //you could use this
beta.dispose(); //or you could dispose the frame and
//do more work after it is gone
}
});
//add btnYankee to pnlEcho
echo.add(yankee);
I'm failing to understand why my yankee and whiskey JButtons aren't
working
The variable wiskey is not JButton type but JTextArea type.
I am learning the basics of Java and decided to practice working on objects, by making a simple program which I called a 'PlayerAction Counter'. It does nothing more that counting an 'action' which is fired by clicking '+1' button and additionally reset the counter, when the 'Reset' button is clicked. For this case I've made a Application.java which holds the main method and launches the program, Interface.java for GUI, EventHandling.java for events and Person.java which holds interface components and methods to change their state. It looks like this:
My idea was to create the window in Interface class and set it's layout, then create two Person objects called PlayerOne and Player Two. The Person class creates two labels and two buttons and set a label of one by a constructor parameter.
I've managed to add these two objects' elements to the GUI by getters and it looks just fine. I added ActionListener to both buttons in Person class and it also works just fine.
I am stuck on getting back to Person fields and methods from EventHandling class. I've created a setValueLabel() which increases by one a value of 'action' and sets it on the label, but I have to idea how to launch the method from another class. I can not make another object inside (throws StackOverFlow error), but should it not somehow refer to those two made in Interface class?
Here is the code:
Application.java
import java.awt.EventQueue;
public class Application {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Interface().setVisible(true);
}
});
}
}
Interface.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
public class Interface extends JFrame {
private JLabel titleLabel;
private JPanel mainPanel;
private JPanel leftPanel, rightPanel;
private JSeparator separator;
Person PlayerOne = new Person("PlayerOne");
Person PlayerTwo = new Person("PlayerTwo");
public Interface() {
//Basic init
setTitle("PlayerAction Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//Layout
mainPanel = new JPanel();
add(mainPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
leftPanel = new JPanel();
rightPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
mainPanel.add(leftPanel, BorderLayout.WEST);
separator = new JSeparator(SwingConstants.VERTICAL);
mainPanel.add(separator, BorderLayout.CENTER);
titleLabel = new JLabel("PlayerAction Counter");
mainPanel.add(titleLabel, BorderLayout.PAGE_START);
//Components init
PlayerTwo.getPersonLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getPersonLabel());
PlayerTwo.getValueLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueLabel());
PlayerTwo.getValueUpButton().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueUpButton());
PlayerTwo.getValueResetButton().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueResetButton());
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
mainPanel.add(rightPanel, BorderLayout.EAST);
PlayerOne.getPersonLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getPersonLabel());
PlayerOne.getValueLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueLabel());
PlayerOne.getValueUpButton().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueUpButton());
PlayerOne.getValueResetButton().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueResetButton());
pack();
}
}
Person.java
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JLabel;
public class Person {
private JLabel personLabel;
private JLabel valueLabel;
private JButton valueUpButton;
private JButton valueResetButton;
private int actionValue = 0;
public Person(String s) {
personLabel = new JLabel(s);
setComponents();
}
private void setComponents() {
valueUpButton = new JButton("+1");
valueResetButton = new JButton("Reset");
valueLabel = new JLabel(""+actionValue);
EventHandling eventHand = new EventHandling(valueUpButton, valueResetButton);
valueResetButton.addActionListener(eventHand);
valueUpButton.addActionListener(eventHand);
}
public void setValueLabel() {
actionValue++;
valueLabel.setText("" +actionValue);
}
public JLabel getPersonLabel() {
return personLabel;
}
public JLabel getValueLabel() {
return valueLabel;
}
public JButton getValueUpButton() {
return valueUpButton;
}
public JButton getValueResetButton() {
return valueResetButton;
}
}
EventHandling.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
public class EventHandling implements ActionListener {
private JButton valueUpButton;
private JButton valueResetButton;
public EventHandling(JButton valueUpButton, JButton valueResetButton) {
this.valueUpButton = valueUpButton;
this.valueResetButton = valueResetButton;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == valueUpButton) {
//no idea how to launch Person.setValueLabel();
//creating new Person object throws StackOverFlow error and I doubt that's the way
}
else if (event.getSource() == valueResetButton) {
}
}
}
I do hope my issue is understandable. The question is: how should it be done?
Please keep in mind that I am a complete rookie and try to learn OOP, but am very confused by it. Please point my mistakes in thinking and the code.
Any feedback will be greatly appraciated.
Thank you.
How would I go about setting the number of selectable items of JRadioButtons?
I tried adding the radiobuttons to a buttongroup, and overriding the buttongroup class, but cant figure which method to modify.
Basically, I want to allow selection of only two radiobuttons. I am aware this is possible using checkboxes, but I need the "roudness" of the radiobuttons, and figure this should be an easier way to go, instead of modifying the look and feel of the checkbox.
Thanks a bunch! :)
Here is an example:
package com.haraj.test.java;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class JRadioButtonTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridLayout());
final Queue<JRadioButton> selectedButtons = new LinkedList<JRadioButton>();
ItemListener listener = new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
JRadioButton newButton = (JRadioButton) e.getSource();
if(e.getStateChange() == ItemEvent.DESELECTED) selectedButtons.remove(newButton);
else
{
if(selectedButtons.size() == 2)
{
JRadioButton oldButton = selectedButtons.poll();
if(oldButton != newButton) oldButton.setSelected(false);
}
selectedButtons.add(newButton);
}
}
};
JRadioButton[] buttons = new JRadioButton[6];
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JRadioButton();
buttons[i].addItemListener(listener);
contentPane.add(buttons[i]);
}
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
One way would be to add an ActionListener to each individual radiobutton which updates a counter if the button is selected.
You can read about jRadioButton functions HERE.
You can then do a function if the counter hits two which makes the other buttons grey (unclickable) using:
.setActionCommand("disable");
You can find more info about the possible methods in the API.