I am new in java swing unfortunately when i want to set action listener to one of the button that it has to get the textArea content and send that to another class it doesn't work in a way that i expect and instead it works when i change the text area's content, i don't know What's happened?
first button i named Button and the same problem happened when i use another action listener inside the Button's action listener named Clac
here is my code:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class FFT_Main_Frame extends JFrame {
JLabel label;
JButton button;
TextPanel txtPanel;
JButton Button;
JLabel label1;
// JTextArea[] BoxArray;
makePolynomial mp;
JButton Calc;
Complex[] Nums;
Complex[] Result;
int input;
FFT_Main fft_main;
ShowResult shr;
public FFT_Main_Frame() {
Button.addActionListener(new ActionListener() {
// Test t;
// Integer content;
#Override
public void actionPerformed(ActionEvent arg0) {
try {
Integer content = new Integer(Integer.parseInt(txtPanel.getTextArea()));
input = content;
System.out.println(input);
// inputt=input;
mp = new makePolynomial(content);
setLayout(new FlowLayout());
add(mp);
// setLayout(new BorderLayout());
add(Calc);
Nums = new Complex[input + 1];
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for (int i = input; i >= 0; i--) {
Nums[i] = new Complex(Double.parseDouble(mp.BoxArray[2 * (i + 1) - 1].getText()),
Double.parseDouble(mp.BoxArray[2 * i].getText()));
}
for (int i = 0; i <= input; i++) {
System.out.println(Nums[i]);
}
fft_main = new FFT_Main();
Result = new Complex[input];
Result = fft_main.Recursive_FFT(Nums);
shr = new ShowResult(Result);
setLayout(new BorderLayout());
add(shr, BorderLayout.CENTER);
System.out.println("Result\n\n");
for (int i = 0; i <= input; i++) {
System.out.println(Result[i]);
}
}
});
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Please Enter Just Numbers! ", "Wrong Value",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
thanks for your help
You are using action listener wrong way here is an example how to use it
public FFT_Main_Frame() {
JButton Button = new JButton("Button");
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
// Code Here
}catch(Exception e) {
// Code Here
}
});
JButton Calc = new JButton("Calc");
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Code Here
}
});
}
}
Some tutorials on how to use action listener
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
http://www.tutorialspoint.com/swing/swing_action_listener.htm
Related
I have created dynamic JChekboxes that is linked to a file. I want to see which ones are checked via an action listener. I have tried getSource(), I have tried getState() none of them are working...
for (int f = 0; f < numberCheckBox[0]; f++) {
String line1 = tableLines[f].toString().trim();
String[] dataRow1 = line1.split("/");
checkBoxList[f] = new JCheckBox(Arrays.toString(dataRow1).replace("[", "").replace("]", ""));
Checkp.add(checkBoxList[f]);
System.out.print(checkBoxList[f]);
}
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(files));
Object[] tableLines = br.lines().toArray();
numberCheckBox[0] = tableLines.length;
for (int j = 0; j < numberCheckBox[0]; j++) {
if(e.getSource() == finalCheckBoxList[j]){
if(e.getStateChange() == 1){
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
The first thing you'll want to do is check out How to Use Buttons, Check Boxes, and Radio Buttons
So from the JCheckBox JavaDocs
isSelected
public boolean isSelected()
Returns the state of the
button. True if the toggle button is selected, false if it's not.
Returns:true if the toggle button is selected, otherwise false
In addition, if you need some way to pass information to the ActionListener. You could continue to rely on the index of the values, but I always prefer to encapsulate this information if possible.
So, in this example, I've used both the actionCommand and clientProperty methods to seed the information I might want to use in the ActionListener
I did use isSelected and it did not work as well.
Then you're doing something wrong, because the below example works just fine
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
int[] numberCheckBox = new int[] { 5 };
JCheckBox[] checkBoxList = new JCheckBox[5];
String[] tableLines = new String[] {
"this/is/a/test",
"hello/world",
"something/wicked/this/way/comes",
"a/long/long/time/ago",
"i/have/something/to/say",
};
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
gbc.anchor = GridBagConstraints.LINE_START;
for (int f = 0; f < numberCheckBox[0]; f++) {
String line1 = tableLines[f].toString().trim();
String[] dataRow1 = line1.split("/");
checkBoxList[f] = new JCheckBox(String.join(", ", dataRow1));
checkBoxList[f].setActionCommand(line1);
checkBoxList[f].putClientProperty("value", line1);
add(checkBoxList[f], gbc);
System.out.print(checkBoxList[f]);
}
JButton save = new JButton("Save");
gbc.anchor = GridBagConstraints.CENTER;
add(save, gbc);
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox cb : checkBoxList) {
if (cb.isSelected()) {
System.out.println("Action Command = " + cb.getActionCommand());
System.out.println("Client Property = " + (String)cb.getClientProperty("value"));
}
}
}
});
}
}
}
I am creating a simple calculator for a school assignment but I can't get it to work for multiple digits
package calculator;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
public class Calculator implements ActionListener{
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Calculator();
}
});
}
public Calculator()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Simple Calculator");
guiFrame.setSize(300,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
numberCalc = new JTextField();
numberCalc.setHorizontalAlignment(JTextField.RIGHT);
numberCalc.setEditable(false);
guiFrame.add(numberCalc, BorderLayout.NORTH);
buttonPanel = new JPanel();
//Make a Grid that has three rows and four columns
buttonPanel.setLayout(new GridLayout(4,4));
guiFrame.add(buttonPanel, BorderLayout.CENTER);
//Add the number buttons
for (int i=1;i<10;i++)
{
addButton(buttonPanel, String.valueOf(i));
}
JButton addButton = new JButton("+");
addButton.setActionCommand("+");
OperatorAction subAction = new OperatorAction(1);
addButton.addActionListener(subAction);
JButton subButton = new JButton("-");
subButton.setActionCommand("-");
OperatorAction addAction = new OperatorAction(2);
subButton.addActionListener(addAction);
JButton multiplyButton = new JButton("*");
multiplyButton.setActionCommand("*");
OperatorAction multiAction = new OperatorAction(3);
multiplyButton.addActionListener(multiAction);
JButton divideButton = new JButton("/");
divideButton.setActionCommand("/");
OperatorAction diviAction = new OperatorAction(4);
divideButton.addActionListener(diviAction);
JButton clearButton = new JButton("ce");
clearButton.setActionCommand("ce");
OperatorAction clearAction = new OperatorAction(5);
clearButton.addActionListener(clearAction);
JButton blankButton = new JButton(" ");
JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
if (!numberCalc.getText().isEmpty())
{
int number = Integer.parseInt(numberCalc.getText());
if (calcOperation == 1)
{
int calculate = currentCalc + number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 2)
{
int calculate = currentCalc - number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 3)
{
int calculate = currentCalc * number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 4)
{
int calculate = currentCalc / number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 5)
{
int calculate = 0;
numberCalc.setText(Integer.toString(calculate));
}
}
}
});
buttonPanel.add(addButton);
buttonPanel.add(subButton);
buttonPanel.add(equalsButton);
buttonPanel.add(divideButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(clearButton);
buttonPanel.add(blankButton);
guiFrame.setVisible(true);
}
//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
but.addActionListener(this);
parent.add(but);
}
//As all the buttons are doing the same thing it's
//easier to make the class implement the ActionListener
//interface and control the button clicks from one place
#Override
public void actionPerformed(ActionEvent event)
{
//get the Action Command text from the button
String action = event.getActionCommand();
//set the text using the Action Command text
numberCalc.setText(action);
}
private class OperatorAction implements ActionListener
{
private int operator;
public OperatorAction(int operation)
{
operator = operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
}
}
However when I run the code It will not allow me to enter in numbers with more than one digit. Also the ce button I created will not reset to zero.
I have included an image of the output.
Thanks in advance.
Output of calculator
The ActionListener is not correct
#Override
public void actionPerformed(ActionEvent event)
{
//get the Action Command text from the button
String action = event.getActionCommand();
//set the text using the Action Command text
numberCalc.setText(action);
}
This will set the numberCalc text to the value of the button, not append the value.
Use numberCalc.setText(NumberCalc.getText() + action); to append the text
Also, for OperatorAction, you don't update any GUI component
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
You should clear numberCalc to wait for the next value or you will end up with 1 + 12 instead of 1 + 2.
If the button is clearButton, you need to change the logic and reset everything currentCalc, numberCalc, calcOperation, ...
package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public interface Listeners
{
static PatternGame game = new PatternGame();
InputGame game2 = new InputGame();
static class inst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("inst".equals(e.getActionCommand()))
{
}
}
}
static class play implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("play".equals(e.getActionCommand()))
{
menu.mf.dispose();
PatternGame.gameStart();
}
}
}
static class exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("exit".equals(e.getActionCommand()))
{
System.exit(0);
}
}
}
static class input implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (InputGame.numOfClicks != 0)
{
InputGame.button = (JButton) e.getSource();
InputGame.button.setText("X");
InputGame.numOfClicks--;
}
else
{
if (InputGame.checkCorrect())
{
JOptionPane.showConfirmDialog(null, "Would you like another pattern?");
PatternGame.order++;
PatternGame.gameStart();
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect!");
menu.start();
}
}
}
}
}
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InputGame implements Properties,Listeners{
public static JFrame gf = new JFrame();
public static JButton button = new JButton();
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static int numOfClicks =0;
public static int numCorrect=0;
public static int[][] input = new int[][]{
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
};
//public static Thread d;
public static void setup() {
gf.dispose();
gf = new JFrame();
gf.setLocation(300,100);
gf.setSize(size);
gf.setResizable(false);
gf.setLayout(Ggrid);
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PatternGame.clear();
blank();
gf.setVisible(true);
System.out.print(numOfClicks);
}
public static void blank()
{
for (int a =0;a<4;a++)
{
for (int b =0;b<4;b++)
{
button = new JButton("");
button.setActionCommand("");
button.addActionListener(new input());
gf.add(button);
}
}
}
public static void input()
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
String x = button.getText();
if (x.equals("X"))
{
input[a][b] = 1;
}
else if (x.equals(""))
{
input[a][b] = 0;
}
System.out.println(input[a][b]);
}
}
}
public static boolean checkCorrect()
{
input();
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (order == 1)
{
if (handlebars[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 2)
{
if (ys[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 3)
{
if (spaceShip[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 4)
{
if (flock[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 5)
{
if (percent[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 6)
{
if (square[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
}
}
return false;
}
}
Ok, this is my code. Now what I want the program to accomplish is for the program to display the blank screen(which I have done) then when the user clicks one of the buttons and it places a X on that button. Then after 6 clicks for the program to translate the pattern they put in to the input array, so I can compare the input array to the pattern array, and be able to tell the user if its correct or not and move on. What this program does now is it displays the blank screen then when a button is pressed it displays the X. I got it to check for one button but I don't know how to check for all of them. So how could I check each button for the text it holds.
You can call getComponents() on the parent container- whether panel, frame or window and then check if it is an instance of button, then check the text set on it like this:
Component[] comps = parent.getComponents();
for(Component c:comps){
if(c instanceof JButton){
JButton btn = (JButton) c;
String text = btn.getText();
//Use text for whatever, add it to an array or something
}
}
Hope you get the idea
I'm trying to learn SwingWorker and I have this simple code running and working, but I can't figure out how to prompt a JOptionPane.showMessageDialog when the task is complete. I've to tried to put
if (isDone())
JOptionPane.showMessageDialog(null, "Task Complete");
in different locations, but can't get anything to work. I've read that I may have to put it in the invokeLater() for it to run in the EDT, I'm not really sure how to accomplish that.
I tried to have my SwingWorker as a class member of my panel, but I can't instantiate it because it gets intantiaated in a listener. So I get a null pointer trying to put if (task.isDone()) in my invokeLater().
What is the proper way to accomplish this task?
I have an SSCCE here (all you do is enter a number and it prints my name that many times to a text area).
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.*;
public class RepeatNameSwingWorker extends JPanel {
private JProgressBar jpb = new JProgressBar(0, 100);
private JTextArea jtaNames = new JTextArea(20, 50);
private final JTextField jtfTimes = new JTextField(8);
private final JButton jbtExecute = new JButton("Execute");
private final JLabel jlblNumTimes = new JLabel("Enter number of times: ");
public RepeatNameSwingWorker(){
jpb.setStringPainted(true);
jtaNames.setLineWrap(true);
jtaNames.setWrapStyleWord(true);
JPanel panel = new JPanel();
panel.add(jlblNumTimes);
panel.add(jtfTimes);
panel.add(jbtExecute);
setLayout(new BorderLayout());
add(jpb, BorderLayout.NORTH);
add(new JScrollPane(jtaNames), BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
jbtExecute.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
RepeatNames task = new RepeatNames(
Integer.parseInt(jtfTimes.getText()), jtaNames);
task.addPropertyChangeListener(new PropertyChangeListener(){
#Override
public void propertyChange(PropertyChangeEvent e) {
if ("progress".equals(e.getPropertyName())) {
jpb.setValue((Integer)e.getNewValue());
}
}
});
task.execute();
if (task.isDone())
JOptionPane.showMessageDialog(null, "Task Complete");
}
});
}
static class RepeatNames extends SwingWorker<String, String>{
int times;
JTextArea result;
public RepeatNames(int times, JTextArea result) {
this.times = times;
this.result = result;
}
#Override
protected String doInBackground(){
publishNames(times);
return null;
}
#Override
protected void done() {
try {
result.append(get().toString()); // Display in text field
} catch (Exception ex) {
result.append(ex.getMessage());
}
}
#Override
protected void process(List<String> list) {
for (int i = 0; i < list.size(); i++) {
result.append(list.get(i) + " ");
}
}
private void publishNames(int n) {
int count = 0;
int number = 2;
while (count <= n) {
if (isPrime(number)) {
count++;
setProgress(100 * count / n);
publish("Paul");
}
number++;
}
}
private static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new RepeatNameSwingWorker());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
});
}
}
, but I can't figure out how to prompt a JOptionPane.showMessageDialog when the task is complete
Show the JOptionPane in the done() method.
I'm not sure how much of sense my title does but since you are suppose to have somewhat of a good title this was the best I came up with, so what I actually mean is...
Let's say in theory I've got 10 tabs, and instead of having them all compressed together in 1 line I'd like to split them in 2, so I'd have 5 tabs on the upper side and 5 on the lower.
Example pic:
not clear your question, but there are basic methods for Tabs in the JTabbedPane
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class TabComponentsDemo extends JFrame {
private static final long serialVersionUID = 1L;
private final int tabNumber = 15;
private final JTabbedPane pane = new JTabbedPane();
private JMenuItem tabComponentsItem;
private JMenuItem scrollLayoutItem;
public TabComponentsDemo(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initMenu();
add(pane);
}
public void runTest() {
pane.removeAll();
for (int i = 0; i < tabNumber; i++) {
String title = "Tab " + i;
pane.add(title, new JLabel(title));
//initTabComponent(i);
}
tabComponentsItem.setSelected(true);
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
scrollLayoutItem.setSelected(false);
setSize(new Dimension(400, 200));
setLocationRelativeTo(null);
setVisible(true);
}
/*private void initTabComponent(int i) {
pane.setTabComponentAt(i, new ButtonTabComponent(pane));
}*/
private void initMenu() {//Setting menu
JMenuBar menuBar = new JMenuBar();//create Options menu
tabComponentsItem = new JCheckBoxMenuItem("Use TabComponents", true);
tabComponentsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
tabComponentsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < pane.getTabCount(); i++) {
if (tabComponentsItem.isSelected()) {
//initTabComponent(i);
} else {
pane.setTabComponentAt(i, null);
}
}
}
});
scrollLayoutItem = new JCheckBoxMenuItem("Set ScrollLayout");
scrollLayoutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK));
scrollLayoutItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT) {
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
} else {
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
}
}
});
JMenuItem resetItem = new JMenuItem("Reset JTabbedPane");
resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.ALT_MASK));
resetItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runTest();
}
});
JMenu optionsMenu = new JMenu("Options");
optionsMenu.add(tabComponentsItem);
optionsMenu.add(scrollLayoutItem);
optionsMenu.add(resetItem);
menuBar.add(optionsMenu);
setJMenuBar(menuBar);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
new TabComponentsDemo("TabComponentsDemo").runTest();
}
});
}
}
If you want them all displayed in a single row (which I think is what the latter part of your description indicates...), you'll want to set the tab layout policy to JTabbedPane.SCROLL_TAB_LAYOUT.
Here's an example with an image.