Reordering JRadioButtons - java

I'm creating a matching style game in java that displays a group of thumbnails which expand into picture with 3 radio buttons, 1 correct and 2 incorrect. Currently I have the 1st rb displaying the correct answer, it should be able to display on the second or 3rd but I can't figure out how to get it there.
So the possibilities would be (CII, ICI, or IIC)
(the rb text gets pulled from the filenames of the pictures)
final JTextArea textArea = new JTextArea();
add(textArea);
JRadioButton rb1 = new JRadioButton(rb1Text);
add(rb1);
rb1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Correct");
}
});
JRadioButton rb2 = new JRadioButton(rb2Text);
add(rb2);
rb2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Guess Again");
}
});
JRadioButton rb3 = new JRadioButton(rb3Text);
add(rb3);
rb3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Guess Again");
}
});
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);

Figured it out: I changed the setBounds to include a one of the 3 desired y values pulled from a shuffled collection.
ArrayList<String> obj = new ArrayList<String>();
obj.add("250");
obj.add("300");
obj.add("350");
Collections.shuffle(obj);
int rand1 = Integer.parseInt(obj.get(0));
int rand2 = Integer.parseInt(obj.get(1));
int rand3 = Integer.parseInt(obj.get(2));
rb1.setBounds(400, rand1, 200, 15);
rb2.setBounds(400, rand2, 200, 15);
rb3.setBounds(400, rand3, 200, 15);
So every time the next or previous button is pressed it puts the correct answer in a different spot.
Thanks for the ideas Hovercraft Full Of Eels!

Related

How to change selected index in JComboBox when refreshing panel?

I am making a simple sudoku and when I want to start a new game, I reload the panel. I first remove it and then add it to the frame. The problem is that I can choose the difficulty for new game, but it always selects the first "Easy" dificulty, not selected. So if I change it in JComboBox to "medium", when page is reloaded it will load the game with "Easy", not "medium".
What should I do so my refreshed panel will accept changed difficulty?
Here are methods that are used for this in my program:
JComboBox difficulty = new JComboBox();
DefaultComboBoxModel difficultyModel = new DefaultComboBoxModel();
difficultyModel.addElement("Easy");
difficultyModel.addElement("Medium");
difficultyModel.addElement("Hard");
difficulty.setModel(tezavnostModel);
difficulty.setSelectedIndex(0);
difficulty.setPreferredSize(new Dimension(100, 25));
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.reloadSudokuBoard();
sudokuBoard.pickDifficulty(getDifficulty()));
}
});
public String getDifficulty() {
return (String)difficulty.getSelectedItem();
}
public void board(int[][] numbers, int zeros) {
int numberZeros = setDifficulty(sudokuForm.getDifficulty());
int[][] boardNumbers = gameNumbers();
public void reloadSudokuBoard() {
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
}
Hope this helps.
public void reloadSudokuBoard() {
int index = difficulty.getSelectedIndex();
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
difficulty.setSelectedIndex(index);
}
Before removing components, you can use the getSelectedIndex to get the index that was selected. After the element have been added, the setSelectedIndex will fix it

Adding multiple items to an action listener

I was wondering in someone could point me in the right direction for this. I have this simple calculator, where the user enters two numbers and then has to select an action (+, -, *, *) from a drop down menu.
After they select an option, it gives them an answer, but I was trying to add a check box to allow the result to be displayed as a float if the box was checked. I was confused on how to have the actionPreformed handle both the JCheckBox and the JComboBox. I tried just adding newCheckBox, but that causes casting errors, between JCheckBox and JComboBox.
public class Calculator2 implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JPanel xpanel;
String[] mathStrings = { "Multiply", "Subtraction", "Division", "Addition"}; //Options for drop down menu
JComboBox mathList = new JComboBox(mathStrings); //Create drop down menu and fill it
public Calculator2() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
JPanel southPanel = new JPanel(); //New panel for the drop down menu
southPanel.setBorder(BorderFactory.createEtchedBorder());
JCheckBox newCheckBox = new JCheckBox("Show My Answer In Floating Point Format"); //Check box to allow user to view answer in floating point
southPanel.add(newCheckBox);
//newCheckBox.addActionListener(this);
southPanel.add(mathList);
mathList.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
//clear();
return ;
}
JComboBox comboSource = (JComboBox)event.getSource(); //Get the item picked from the drop down menu
String selectedItem = (String)comboSource.getSelectedItem();
if(selectedItem.equalsIgnoreCase("Multiply")) { //multiply selected
result.setText(Integer.toString(xVal*yVal));
}
else if(selectedItem.equalsIgnoreCase("Division")) { //division selected
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
//clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(selectedItem.equalsIgnoreCase("Subtraction")) { //subtraction selected
result.setText(Integer.toString(xVal-yVal));
}
else if(selectedItem.equalsIgnoreCase("Addition")) { //addition selected
result.setText(Integer.toString(xVal+yVal));
}
}
}
What I would recommend is that you keep a reference to the JCheckBox in the Calculator2 class. So something along the lines of
public class Calculator implements ActionListener {
...
JComboBox mathList = ...
JCheckBox useFloatCheckBox = ...
...
}
then in your actionPerformed mehtod, instead of getting the reference to the widget from event.getSource() get it directly from the reference in the class. So actionPerformed would look like this
public void actionPerformed(ActionEvent e) {
String operator = (String)this.mathList.getSelected();
boolean useFloat = this.useFloatCheckBox.isSelected();
...
}
This way you can use the same listener on both objects without having to worry about casting the widget.
The casting errors are because event.getSource() changes depending on which object fired the event. You can check the source of the event and process based on that:
if (event.getSource() instanceof JCheckBox) { ... act accordingly ... } else
Instead you could add a different ActionListener implementation to the JCheckBox so that the event it creates goes to a different place. An anonymous listener that sets a flag or calls a different method would work too.
There are other ways you could approach the problem, do you want the checkbox to affect an existing calculation, or only a new one? If only a new calculation you don't need an action listener on the checkbox, you can find out whether it is checked when you do the calculation:
if (myCheckbox.isSelected()) {
// do float calculation...
} else {
// do int calculation
}

Java how to assign id to button and retrieve them?

I'm getting stuck while building a forum like application which has a vote button.
I have vote up and vote down button for each content which are automatically generated. I want this button to only display the up and down arrow but not any text or label.. how can i find out which button is pressed?
Automated content..
ImageIcon upvote = new ImageIcon(getClass().getResource("vote_up.png"));
ImageIcon downvote = new ImageIcon(getClass().getResource("vote_down.png"));
JButton vote_up = new JButton(upvote);
JButton vote_down = new JButton(downvote);
vote_up.addActionListener(voting);
vote_down.addActionListener(voting);
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
//What to do here to find out which button is pressed?
}
};
any help is appreciated.
public void a(){
int crt_cnt = 0;
for(ClassA temp : listofClassA)
{
b(crt_cnt);
crt_cnt++;
}
}
public void b(crt_cnt){
//draw button
}
As from above, I have multiple vote_up and vote_down button created by the b function, how can i differentiate which crt_cnt is the button from?
There are multiple ways you might achieve this
You could...
Simply use the source of the ActionEvent
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == vote_up) {
//...
} else if (...) {
//...
}
}
};
This might be okay if you have a reference to the original buttons
You could...
Assign a actionCommand to each button
JButton vote_up = new JButton(upvote);
vote_up.setActionCommand("vote.up");
JButton vote_down = new JButton(downvote);
vote_down .setActionCommand("vote.down");
//...
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if ("vote.up".equals(e.getActionCommand())) {
//...
} else if (...) {
//...
}
}
};
You could...
Take full advantage of the Action API and make indiviual, self contained actions for each button...
public class VoteUpAction extends AbstractAction {
public VoteUpAction() {
putValue(SMALL_ICON, new ImageIcon(getClass().getResource("vote_up.png")));
}
#Override
public void actionPerformed(ActionEvent e) {
// Specific action for up vote
}
}
Then you could simply use
JButton vote_up = new JButton(new VoteUpAction());
//...
Which will configure the button according to the properties of the Action and will trigger it's actionPerformed method when the button is triggered. This way, you know 100% what you should/need to do when the actionPerformed method is called, without any doubts.
Have a closer look at How to Use Actions for more details
You can detect by using the method getSource() of your EventAction
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == vote_up ) {
// vote up clicked
} else if (e.getSource() == vote_down){
// vote down clicked
}
}
};
hey thanks for all the help and assistance! I've finally got it! I solved it by
assigning a text on the button, +/- for vote up or down, followed by the content id which i required, then change the font size to 0
vote.setText("+"+thistopic.content.get(crt_cnt).get_id());
vote.setFont(heading.getFont().deriveFont(0.0f));
after that i could easily trace which button is pressed by comparing to the
actionEvent.getActionCommand()
which return the text on the button!
I would wrap the JButton similar to this:
JButton createMyButton(final JPanel panel, final String text,
final boolean upOrDown, final int gridx, final int gridy) {
final JButton button = new JButton();
button.setPreferredSize(new Dimension(80, 50));
final GridBagConstraints gbc = Factories.createGridBagConstraints(gridx,
gridy);
panel.add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
myActionPerformed(text, upOrDown);
}
});
return button;
}
You could use an int instead of the text, if more convenient.

How to add JButton at JTable

I have a JTable with 7 column. I want to add at the seven one column a JButton with Icon.
So I have this:
mappa= modelManager.getContoBancarioManager().getContiBancari(null,WFConst.CONTO_BANCARIO_PUBBLICO);
//fontTable = new Font("Century Gothic", Font.PLAIN, 15);
tableModelContiBancari = new MyTableModelContiBancari();
tableContiBancari= new JTable(tableModelContiBancari);
tableModelContiBancari.stampaTabella(mappa);
tableContiBancari.addMouseListener(new MyMouseAdapterTableConti());
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(tableContiBancari);
jScrollPane.setPreferredSize(dTabella);
Toolkit t = Toolkit.getDefaultToolkit();
Dimension screenSize = t.getScreenSize();
Double larghezza =screenSize.getWidth()*0.95;
// System.out.println(larghezza);
int lar = (int) (larghezza /90);
int lar2 = (int)(larghezza /5);
tableContiBancari.getColumnModel().getColumn(0).setPreferredWidth(10);
tableContiBancari.getColumnModel().getColumn(1).setPreferredWidth(lar2);
tableContiBancari.getColumnModel().getColumn(2).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(3).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(4).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(5).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(6).setPreferredWidth(lar);
Action delete = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//to do
System.out.println("pp");
}
};
ButtonColumn buttonColumn = new ButtonColumn(tableContiBancari, delete, 7);
buttonColumn.setMnemonic(KeyEvent.VK_D);
This is ButtonColumn class:
public void daiProprietaJTableContiBancari(){
mappa= modelManager.getContoBancarioManager().getContiBancari(null,WFConst.CONTO_BANCARIO_PUBBLICO);
//fontTable = new Font("Century Gothic", Font.PLAIN, 15);
tableModelContiBancari = new MyTableModelContiBancari();
tableContiBancari= new JTable(tableModelContiBancari);
tableContiBancari.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F5)
cambiaTipologiaConti();
}
});
tableModelContiBancari.stampaTabella(mappa);
//tableContiBancari.setFont(fontTable);
tableContiBancari.addMouseListener(new MyMouseAdapterTableConti());
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(tableContiBancari);
jScrollPane.setPreferredSize(dTabella);
tableContiBancari.setRowHeight(25);
Toolkit t = Toolkit.getDefaultToolkit();
Dimension screenSize = t.getScreenSize();
Double larghezza =screenSize.getWidth()*0.95;
// System.out.println(larghezza);
int lar = (int) (larghezza /90);
int lar2 = (int)(larghezza /5);
tableContiBancari.getColumnModel().getColumn(0).setPreferredWidth(10);
tableContiBancari.getColumnModel().getColumn(1).setPreferredWidth(lar2);
tableContiBancari.getColumnModel().getColumn(2).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(3).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(4).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(5).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(6).setPreferredWidth(lar);
DefaultTableCellRenderer renderer_archivi = new DefaultTableCellRenderer();
renderer_archivi.setHorizontalAlignment(SwingConstants.RIGHT);
tableContiBancari.getColumnModel().getColumn(4).setCellRenderer(renderer_archivi);
tableContiBancari.getColumnModel().getColumn(5).setCellRenderer(renderer_archivi);
tableContiBancari.getColumnModel().getColumn(6).setCellRenderer(renderer_archivi);
Action delete = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//to do
System.out.println("pp");
}
};
ButtonColumn buttonColumn = new ButtonColumn(tableContiBancari, delete, 7);
buttonColumn.setMnemonic(KeyEvent.VK_D);
//tableContiBancari.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer());
//tableContiBancari.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox()));
//setUpColumnButton(tableContiBancari, tableContiBancari.getColumnModel().getColumn(7));
}
If I try to run the code, I have a JTable with a JButton at the last column but if I try to click on one JButton the action is not execute.
You need to implement your own TableCellRenderer and make its method getTableCellRendererComponent return a JButton for your column. See the Tutorial.
Check out Table Button Column for one approach.
You add text to the column the same way you do for any other column and then the ButtonColumn class is used as a:
renderer - so that the text is displayed on a button
editor - so you can click on the button to invoke an Action.
You must also provide an Action to the ButtonColumn class. The Action will have access to the row the clicked button. You can easily use the row number to delete the row for example, or use the row to get data from the table and do other processing.

Simple ActionListener within a 2D array of JButtons

Okay so I am making a 2d array of JToggleButtons. I got the action listener up and going, but I have no way to tell which button is which.
If I click one, all it returns is something like
javax.swing.JToggleButton[,59,58,19x14,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#53343ed0,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=]
Is there anyway to stick some sort of item or number in the button object to associate each button?
And then when the button is clicked I can retrieve that item or number that was given to it?
Here is my button generator code. (How could I make "int l" associate (and count) to each button made, when it is called, it will return that number, or something along those lines.
JToggleButton buttons[][] = new JToggleButton[row][col];
int l = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
buttons[i][j] = new JToggleButton("");
buttons[i][j].setSize(15,15);
buttons[i][j].addActionListener(new e());
panel.add(buttons[i][j]);
l++;
}
}
ActionListner
public class e implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
System.out.println(source);
}
}
variable "source" is what I use to get my data, so how can int l, be returned through "source" (as its unique value for the unique button clicked) as a button is clicked?
Thanks,
-Austin
very simple way is add ClientProperty to the JComponent, add to your definition into loop e.g.
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
rename e to the MyActionListener and change its contents
public class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
EDIT:
for MinerCraft clone isn't required to implements ony of Listeners, there is only about Icon, find out that in this code (don't implement any of Listeners anf remove used ItemListener)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonsIcon extends JFrame {
private static final long serialVersionUID = 1L;
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
setLayout(new GridLayout(2, 2, 4, 4));
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon((errorIcon));
button.setRolloverIcon((infoIcon));
button.setPressedIcon(warnIcon);
button.setDisabledIcon(warnIcon);
add(button);
JButton button1 = new JButton();
button1.setBorderPainted(false);
button1.setBorder(null);
button1.setFocusable(false);
button1.setMargin(new Insets(0, 0, 0, 0));
button1.setContentAreaFilled(false);
button1.setIcon((errorIcon));
button1.setRolloverIcon((infoIcon));
button1.setPressedIcon(warnIcon);
button1.setDisabledIcon(warnIcon);
add(button1);
button1.setEnabled(false);
final JToggleButton toggleButton = new JToggleButton();
toggleButton.setIcon((errorIcon));
toggleButton.setRolloverIcon((infoIcon));
toggleButton.setPressedIcon(warnIcon);
toggleButton.setDisabledIcon(warnIcon);
toggleButton.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton.isSelected()) {
} else {
}
}
});
add(toggleButton);
final JToggleButton toggleButton1 = new JToggleButton();
toggleButton1.setIcon((errorIcon));
toggleButton1.setRolloverIcon((infoIcon));
toggleButton1.setPressedIcon(warnIcon);
toggleButton1.setDisabledIcon(warnIcon);
toggleButton1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton1.isSelected()) {
} else {
}
}
});
add(toggleButton1);
toggleButton1.setEnabled(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
Just add the row and column data to each listener. You could add an explicit constructor, but I suggest adding a little method (which may have more added to it later).
buttons[i][j].addActionListener(e(i, j));
...
private ActionListener e(final int i, final int j) {
return new ActionListener() {
// i and j available here
...
(In JDK8 you should be able to use a lambda to reduce the syntax clutter.)
And then renaming it with a better name.
I made a minesweeper game and ran into a similar problem. One of the only ways you can do it, is to get the absolute location of the clicked button, then divide that by the x and y between buttons, so for me it was
if ((e.getComponent().getX() != (randx) * 25 && e.getComponent().getY() != (randy) * 25) &&bomb[randx][randy] == false) {
This code was to check if the area had bombs. So I had 25 x and y difference between location of bombs. That will just give you a general idea on how to do this.
I believe: (x - x spacing on left side) / buffer - 1 would work.
Instead of 'e.getSource()' you can always call 'e.getActionCommand()'. For each button you can specify this by:
JButton button = new JButton("Specify your parameters here"); /*you get these from getActionCommand*/
button.setText("title here"); /*as far as I remember*/

Categories

Resources