i have 10 jcheckbox and only 5 should be selected. i already did all the coding for this one, but i don't know how to display the selected 5 into a jlabel. i tried doing it by this code:
JCheckBox check;
JPanel panel=new JPanel();
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
this is the listener
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
name=check.getName();
}
};
and this is the panel where it should be displayed into jlabel
panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel(name);
panel2.add(txtVote);
}
but using this code, it doesn't display anything on the jlabel. if i change the listener into this:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
txtVote.setText(check.getName());
}
};
it will only display into the last label. other jlabels would be blank. please help thank you so much
EDIT
here is the code that is runnable
public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
public JCheckBoxtoLabel() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
JPanel panel2 = panel2();
frame.setLayout(new GridLayout(1,2));
frame.add(panel); frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel=new JPanel(new GridLayout(10,1));
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
return panel;
}
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
}
return panel2;
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
txtVote.setText(check.getName());
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCheckBoxtoLabel();
}
});
}
}
Consider changing what you're doing and displaying the text in a JList and not in JLabels. This can help you consolidate your information. You can also give your JCheckBoxes or JRadioButtons and ItemListener that only allows 5 of the buttons to be selected at a time -- unselecting the oldest one currently selected. For instance:
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FiveNames extends JPanel {
private static final String[] ALL_NAMES = {"Bob", "Bill", "Frank", "Helen",
"Erica", "Mickey", "Donald", "Hillary", "Michael", "Peter", "Roger"};
private static final int ALLOWED_SELECTIONS_COUNT = 5;
private DefaultListModel<String> displayListModel = new DefaultListModel<>();
private JList<String> list = new JList<>(displayListModel);
public FiveNames() {
JPanel namePanel = new JPanel(new GridLayout(0, 1, 0, 5));
RButtonItemListener rButtonListener = new RButtonItemListener();
for (String name : ALL_NAMES) {
JRadioButton rButton = new JRadioButton(name);
rButton.setActionCommand(name);
rButton.addItemListener(rButtonListener);
namePanel.add(rButton);
}
list.setVisibleRowCount(ALLOWED_SELECTIONS_COUNT);
list.setPrototypeCellValue(" ");
list.setBackground(null);
setLayout(new GridLayout(1, 0));
add(namePanel);
add(list);
}
// listener to only allow the last 5 radiobuttons to be selected
private class RButtonItemListener implements ItemListener {
private List<ButtonModel> buttonModelList = new ArrayList<>();
#Override
public void itemStateChanged(ItemEvent e) {
JRadioButton rBtn = (JRadioButton) e.getSource();
ButtonModel model = rBtn.getModel();
if (e.getStateChange() == ItemEvent.SELECTED) {
buttonModelList.add(model);
if (buttonModelList.size() > ALLOWED_SELECTIONS_COUNT) {
for (int i = 0; i < buttonModelList.size() - ALLOWED_SELECTIONS_COUNT; i++) {
ButtonModel removedModel = buttonModelList.remove(0);
removedModel.setSelected(false);
}
}
} else {
buttonModelList.remove(model);
}
displayListModel.clear();
for (ButtonModel buttonModel : buttonModelList) {
displayListModel.addElement(buttonModel.getActionCommand());
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FiveNames");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FiveNames());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
The problem is that txtVote is only a single Jlabel and you are trying to use it for all 5. Since the fifth jlabel was the last to be created it is the one being used. My suggestion is that you create an arraylist field and inside panel12 add each label to the arraylist. Then inside the listener it would iterate through each jlabel in the arraylist check if has text set to it, if so check the next one until it finds one with no text, then sets the text to that. The problem with this at the moment is that in your code you are never defining what happens when they uncheck the box.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
ArrayList<JLabel> boxLabels;
public JCheckBoxtoLabel() {
boxLabels = new ArrayList<JLabel>();
JFrame frame = new JFrame();
JPanel panel = createPanel();
JPanel panel2 = panel2();
frame.setLayout(new GridLayout(1,2));
frame.add(panel); frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel=new JPanel(new GridLayout(10,1));
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
return panel;
}
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
boxLabels.add(txtVote);
}
return panel2;
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
if(!check.isSelected()){
for(JLabel label: boxLabels){
if(label.getText().equals(check.getName())) label.setText("");
}
}else{
for(JLabel label: boxLabels){
if(label.getText().isEmpty()){
label.setText(check.getName());
return;
}
}
}
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCheckBoxtoLabel();
}
});
}
}
Your variable JLabel txtVote is a single JLabel object, not an array.
In your panel2() function you assign 5 new JLabels to txtVote. Since you assign 5 in a row, it gets overriden each time so it only ever contains the final JLabel.
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
}
return panel2;
}
So when you call getText on voteTxt in the action listener, you are only getting the last labels text.
To fix this, you need to make txtVote an array of JLabels, and in your action listener iterate a second time through your JLabels and call get text on each in turn.
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
for (int i = 0; i < txtVotes.length; i++) {
txtVotes[i].getText(check.getName());
}
}
};
I don't know if you realise or want to, but each label is being set to the same value, if you don't want this you will need to store an array of check names somewhere and iterate through these as well.
Related
My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!
Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
return panel;
}
}
}
I am trying to learn how to use CardLayout instead of multiple JFrames and I am messing around with this code I found on youtube. I tried calling setSize() on all the JPanes but it does not change the size and it remains at the minimum window size. Is the reason I can't set the size because of this line of code: "panelCont.setLayout(cl);" ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CLayout {
JFrame frame = new JFrame("CardLayout");
JPanel panelCont = new JPanel();
JPanel panelFirst = new JPanel();
JPanel panelSecond = new JPanel();
JButton buttonOne = new JButton("Switch to second panel");
JButton buttonSecond = new JButton("Switch to first panel");
CardLayout cl = new CardLayout();
public CLayout() {
panelCont.setLayout(cl);
panelFirst.add(buttonOne);
panelSecond.add(buttonSecond);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panelCont.add(panelFirst, "1");
panelCont.add(panelSecond, "2");
cl.show(panelCont, "1");
buttonOne.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "2");
}
});
buttonSecond.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(panelCont, "1");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CLayout();
}
});
}
}
Yes, it's for CardLayout but also it's possible to do resize. You can nest your JPanels for instance. or use something like this :
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class MultiSizedPanels {
private static void createAndShowUI() {
final CardLayout cardLayout = new CardLayout();
final JPanel cardHolder = new JPanel(cardLayout);
JLabel[] labels = {
new JLabel("Small Label", SwingConstants.CENTER),
new JLabel("Medium Label", SwingConstants.CENTER),
new JLabel("Large Label", SwingConstants.CENTER)};
for (int i = 0; i < labels.length; i++) {
int padding = 50;
Dimension size = labels[i].getPreferredSize();
size = new Dimension(size.width + 2 * (i + 1) * padding, size.height + 2 * (i + 1) * padding);
labels[i].setPreferredSize(size);
Border lineBorder = BorderFactory.createLineBorder(Color.blue);
labels[i].setBorder(lineBorder);
JPanel containerPanel = new JPanel(new GridBagLayout());
containerPanel.add(labels[i]);
cardHolder.add(containerPanel, String.valueOf(i));
}
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardHolder);
}
});
JPanel btnHolder = new JPanel();
btnHolder.add(nextButton);
JFrame frame = new JFrame("MultiSizedPanels");
frame.getContentPane().add(cardHolder, BorderLayout.CENTER);
frame.getContentPane().add(btnHolder, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Where component (here a JLabel rather than a JPanel) has it's preferredSize set, then place it in another JPanel.
I hope this helps you.
so i want my buttons to be labeled 1-9 but I dont want to list out all the action listeners and action-commands for each button. How can I do that
and also I cannot use add.ActionListener(this) so what can i use
JButton[] button = new JButton[9];
panel.setLayout(new GridLayout(3,3));
for (int i = 0; i < button.length; i++) {
button[i] = new JButton();
panel.add(button[i]);
String bu = Integer.toString(i);
button[i].setActionCommand(bu);
button[i].addActionListener(new ActionListener());
Sorry im new to java swing so its abit confusing still
I cannot use add.ActionListener(this) so what can i use
You create a class that implements an ActionListener.
Or better yet create a class that implement Action. An Action is the same as an ActionListener. The benefit is that an Action can be used with Key Bindings.
Here is a basic example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(30, 30) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Now you can either click on the button or type the number and the value will be inserted into the text field.
Just add on main action performed method.
Example would be like this :
public void actionPerformed(ActionEvent e){
// your todo code here
}
Make sure to import the appropriate packages.
You have to implement the actionListener
public class Butt implements ActionListener
{
public JPanel method()
{
JPanel panel = new JPanel();
JButton[] button = new JButton[9];
panel.setLayout(new GridLayout(3, 3));
for (int i = 0; i < button.length; i++)
{
button[i] = new JButton(""+i);
panel.add(button[i]);
String bu = Integer.toString(i);
button[i].setActionCommand(bu);
button[i].addActionListener(this);
}
return panel;
}
#Override
public void actionPerformed(ActionEvent e)
{
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.add(new Butt().method());
frame.setVisible(true);
frame.setSize(500, 500);
}
}
see now there is no errors.
results
and also I cannot use add.ActionListener(this) so what can i use
I will interpret what you meant here as "you are not allowed to let the container class implements ActionListener, but still allowed to use ActionListener".
If that is the case, you have at least 2 more choices:
Create an anonymous class for the ActionListener
Create an inner class for the ActionListener
An example using GridLayout with inner-class Actionlistener:
how to put actionlistenerand actioncommand to multiple jbuttons
The following uses inner class to handle buttons' action.
class MainPanel extends JPanel //not implementing ActionListener here
{
private JButton[] btns;
public MainPanel(){
setPreferredSize(new Dimension(150, 150));
setLayout(new GridLayout(3, 3));
initComponents();
addComponents();
}
private void initComponents(){
btns = new JButton[9];
ButtonHandler bh = new ButtonHandler();
for(int x=0; x<btns.length; x++){
btns[x] = new JButton(Integer.toString(x+1));
btns[x].addActionListener(bh); //NOT using addActionListener(this)
}
}
private void addComponents(){
for(int x=0; x<btns.length; x++)
add(btns[x]); //Add in sequential order into grid layout
}
private class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e){
String s = ((JButton)e.getSource()).getText();
JOptionPane.showMessageDialog(null, "Button " + s + " was clicked.");
}
}
}
Finally, run your codes in the EDT:
class TestRunner
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
JFrame frame = new JFrame("Buttons Pad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I have declared an array:
private javax.swing.JPanel[] panelArray = new javax.swing.JPanel[3];
I also have 3 panels: panel0, panel1 and panel2. Can I add these panels to the array? i.e
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
And then manipulate the arrays like this?
boolean[] myBools; .... then set them as true/false
for(int i=0; i<3; i++)
{
if(myBools[i])
panelArray[i].setVisible(true)
}
Because that does not work for me
On my side it's working fine, in this program :
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MyPanel
{
private JPanel[] panelArray = new JPanel[3];
private boolean[] myBools = new boolean[]{false, false, false};
private int counter = 0;
private int prvPanelCounter = 0;
private Timer timer;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
counter++;
if (counter > 2)
counter = 0;
myBools[counter] = true;
for (int i = 0; i < 3; i++)
{
if (myBools[i])
{
panelArray[i].setVisible(myBools[i]);
panelArray[prvPanelCounter].setVisible(myBools[prvPanelCounter]);
myBools[i] = false;
prvPanelCounter = i;
break;
}
}
}
};
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Locate Mouse Position");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel0 = new JPanel();
panel0.setOpaque(true);
panel0.setBackground(Color.BLUE);
JPanel panel1 = new JPanel();
panel1.setOpaque(true);
panel1.setBackground(Color.RED);
JPanel panel2 = new JPanel();
panel2.setOpaque(true);
panel2.setBackground(Color.DARK_GRAY);
panelArray[0] = panel0;
panelArray[1] = panel1;
panelArray[2] = panel2;
JComponent contentPane = (JComponent) frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 1));
frame.add(panel0);
frame.add(panel1);
frame.add(panel2);
panel0.setVisible(myBools[counter]);
panel1.setVisible(myBools[counter]);
panel2.setVisible(myBools[counter]);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(1000, timerAction);
timer.start();
}
public static void main(String\u005B\u005D args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MyPanel().createAndDisplayGUI();
}
});
}
}
What you want to do can be done, but here's a few points to bear in mind:
Make sure you initialise the JPanels before referencing them.
The statement "panelArray[i].setVisible(true)" needs a semicolon after it.
None of these panels will be visible unless you add them to another component, such as a JFrame.
Rather than state javax.swing.JPanel, you could just import the JPanel at the top of the page and refer to it as simply JPanel.
Your "if" statement is unnecessary. Just do .setVisible(myBools[i]);
Hope these were of some help to you.
Yes, you can. Did you really not initialize the myBools array with new ?
I have found how to keep a JButton in its pressed state using this code:
JButton[] buttons;
.
.
.
public void actionPerformed(ActionEvent e)
{
for(int i = 0; i < buttons.length; i++)
{
if(e.getSource() == buttons[i])
{
buttons[i].getModel().setPressed(true);
}
else
{
buttons[i].getModel().setPressed(false);
}
}
}
This code captures the clicked button, keeps it pressed, and makes all other buttons on the panel unpressed. And this code works great... until the window loses focus (or more specifically, its parent JPanel loses focus). After that, all the buttons return to a non-pressed state.
Right now the tutorial on how to write WindowFocusListeners is down. Is there a way to make a JButton's pressed state persist through a loss of focus?
Why not simply use a series of JToggleButtons and add them to the same ButtonGroup object? All the hard work is done for you since the toggle button is built to stay in pressed state if pressed. Think of it as a JRadioButton that looks like a JButton (since in actuality, JRadioButton descends from JToggleButton).
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BunchOfButtons extends JPanel {
private static final String[] TEXTS = {"One", "Two", "Three", "Four", "Five"};
private ButtonGroup btnGroup = new ButtonGroup();
private JTextField textField = new JTextField(20);
public BunchOfButtons() {
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
BtnListener btnListener = new BtnListener();
for (String text : TEXTS) {
JToggleButton toggleBtn = new JToggleButton(text);
toggleBtn.addActionListener(btnListener);
toggleBtn.setActionCommand(text);
btnPanel.add(toggleBtn);
btnGroup.add(toggleBtn);
}
JPanel otherPanel = new JPanel();
otherPanel.add(textField ); // just to take focus elsewhere
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new GridLayout(0, 1, 0, 15));
add(btnPanel);
add(otherPanel);
}
private class BtnListener implements ActionListener {
public void actionPerformed(ActionEvent aEvt) {
textField.setText(aEvt.getActionCommand());
}
}
private static void createAndShowGui() {
BunchOfButtons mainPanel = new BunchOfButtons();
JFrame frame = new JFrame("BunchOfButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}