I am writing an application in Java and am using Netbeans IDE. I have set two JCheckBox (chk1 and chk2) and two JTextField (jtextfield1 and jtextfield2). I want that if I check chk1, jtextfield2 will be set to uneditable and if I chk2, jtextfield2 will be set to editable and vice versa.
How to use JCheckBox to make JTextField editable and vice versa?
With the code below, it works alright but if i check the chk2 all the text fields are set to uneditable.
private void ckDepoActionPerformed(java.awt.event.ActionEvent evt) {
if(ckDepo.isSelected()){
txtDeposit.setEditable(false);
}
else{
txtWithdraw.setEditable(true);
}
}
private void ckWithdrawActionPerformed(java.awt.event.ActionEvent evt) {
transact="withdraw";
if(ckWithdraw.isSelected()){
txtWithdraw.setEditable(false);
}
else{
txtDeposit.setEditable(true);
}
}
Suggestions:
I would use JRadioButtons all added to the same ButtonGroup. This way selecting one JRadioButton will unselect all the others.
I would give each JRadioButton an ItemListener that inside it enabled or disabled its adjacent JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class RadioBtnMayhem {
private static final int COLUMNS = 10;
public static void main(String[] args) {
JPanel mainPanel = new JPanel(new GridLayout(0, 1));
ButtonGroup btnGroup = new ButtonGroup();
int fieldCount = 5;
for (int i = 0; i < fieldCount; i++) {
JRadioButton radioBtn = new JRadioButton();
btnGroup.add(radioBtn);
final JTextField textField = new JTextField(COLUMNS);
textField.setEnabled(false);
radioBtn.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
textField.setEnabled(e.getStateChange() == ItemEvent.SELECTED);
}
});
JPanel radioFieldPanel = new JPanel();
radioFieldPanel.add(radioBtn);
radioFieldPanel.add(textField);
mainPanel.add(radioFieldPanel);
}
JOptionPane.showMessageDialog(null, mainPanel);
}
}
Related
I'm having some trouble with a java project. I've made an empty GUI interface, and now I need to add some functionality to it. I'm stuck, however, on how to go about that. The basic layout has 4 radio buttons, Rectangle, Box, Circle, and Cylinder. I have a group panel that has 4 separate panels that each have text boxes with labels for entering height, length, width, and radius. Here's how it looks: GUI layout. Depending on the radio button that is selected, certain boxes that aren't needed should be hidden. For example, if Rectangle is selected, only the boxes for length and width should be visible.
The main frame that will display everything is here:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import java.awt.Font;
public class GUIFrame extends JFrame
{
//private final BorderLayout layout;
private final FlowLayout layout;
private final JLabel lblTitle;
private final JButton btnProc;
public GUIFrame()
{
super("GUI Layout");
Font titleFont = new Font("Verdana", Font.BOLD, 26);
btnProc = new JButton("Click to Process");
lblTitle = new JLabel("Figure Center");
lblTitle.setFont(titleFont);
widthPanel myWidth = new widthPanel();
myWidth.setLocation(0, 400);
lengthPanel myLength = new lengthPanel();
heightPanel myHeight = new heightPanel();
radiusPanel myRadius = new radiusPanel();
radioButtonPanel myButtons = new radioButtonPanel();
//layout = new BorderLayout(3, 2);
layout = new FlowLayout();
JPanel txtGroup = new JPanel();
txtGroup.setLayout(new GridLayout(2, 2));
txtGroup.add(myWidth);
txtGroup.add(myLength);
txtGroup.add(myRadius);
txtGroup.add(myHeight);
setLayout(layout);
add(lblTitle);
add(myButtons);
add(txtGroup);
add(btnProc);
if(myButtons.btnRectangle.isSelected())
{
myHeight.setVisible(false);
myRadius.setVisible(false);
}
}
private class RadioButtonHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent event)
{
}
}
}
I can get this working using if statements, but I'm supposed to be using event handlers and I'm lost on how to code that to get it to work properly.
if it helps, here's the code for the button panel:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class radioButtonPanel extends JPanel
{
private final JRadioButton btnRectangle;
private final JRadioButton btnBox;
private final JRadioButton btnCircle;
private final JRadioButton btnCylinder;
private final ButtonGroup radioButtonGroup;
private final JLabel label;
private final JPanel radioPanel;
public radioButtonPanel()
{
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(5,1));
btnRectangle = new JRadioButton("Rectangle", true);
btnBox = new JRadioButton("Box", false);
btnCircle = new JRadioButton("Circle", false);
btnCylinder = new JRadioButton("Cylinder", false);
label = new JLabel("Select A Figure:");
radioPanel.add(label);
radioPanel.add(btnRectangle);
radioPanel.add(btnBox);
radioPanel.add(btnCircle);
radioPanel.add(btnCylinder);
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(btnRectangle);
radioButtonGroup.add(btnBox);
radioButtonGroup.add(btnCircle);
radioButtonGroup.add(btnCylinder);
add(radioPanel);
}
}
And a sample of one of the panels. They all follow the same setup, just different variable names.
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.GridLayout;
public class heightPanel extends JPanel
{
private final JLabel lblHeight;
private final JTextField txtHeight;
private final JPanel myHeight;
public heightPanel()
{
myHeight = new JPanel();
myHeight.setLayout(new GridLayout(2,1));
lblHeight = new JLabel("Enter Height:");
txtHeight = new JTextField(10);
myHeight.add(lblHeight);
myHeight.add(txtHeight);
add(myHeight);
}
}
The below code should give you a quick introduction of how to use event listener/handler for your button group (JRadioButtons).
but I'm supposed to be using event handlers and I'm lost on how to
code that to get it to work properly.
//add listener to the rectangle button and should be the same for the other `JRadioButtons` but with different `identifiers`.
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
//TODO
}
}
});
Depending on the radio button that is selected, certain boxes that
aren't needed should be hidden. For example, if Rectangle is selected,
only the boxes for length and width should be visible.
//To hide JTextFields use
void setVisible(boolean visible) method. You should pass false as the argument to the method if you want to hide the JTextField.
Example:
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnRectangle){
TextFieldName.setVisible(false); // set the textfields that you want to be hidden once the Rectangle button is chosen.
}
}
});
We have a legacy piece of software that runs on Java 1.6. When we finally got the green light to upgrade it to Java 1.8, the following problem manifested itself.
We have a set of radio buttons with accelerator keys. If a JTextComponent of any sort has the focus, and you hit one of the radio button accelerators (say, ALT-s), and you release the "s" before you release the ALT, the UIManager will activate the menu bar. (This only happens with the Windows look and feel)
Looks like a bug, and I've been thinking of writing a workaround by "consuming" the ALT release in those cases, but maybe someone has a better idea? Using a different look and feel is not an option, nor is switching off the standard Alt behavior in the UI Manager.
Here's a short code sample. Note there are no accelerator/mnemonic conflicts of any sort.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class MnemonicTest extends JFrame {
public MnemonicTest() {
super("MnemonicTest");
init();
}
public static void main(String[] args) throws Exception {
MnemonicTest test = new MnemonicTest();
test.setVisible(true);
}
private void init() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
setSize(new Dimension(500,400));
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(stopButton, BorderLayout.SOUTH);
JMenuBar jMenuBar = new JMenuBar();
JMenu menu = new JMenu("XXX");
JMenuItem a1 = new JMenuItem("a1", 'A');
JMenuItem b1 = new JMenuItem("b1", 'B');
JMenuItem c1 = new JMenuItem("c1", 'C');
menu.add(a1);
menu.add(b1);
menu.add(c1);
jMenuBar.add(menu);
this.setJMenuBar(jMenuBar);
JPanel p = new JPanel();
ButtonGroup group = new ButtonGroup();
p.add(new JTextField("XXXXXXXXXX"), BorderLayout.CENTER);
JRadioButton but1 = new JRadioButton("test");
but1.setMnemonic('s');
JRadioButton but2 = new JRadioButton("2222");
p.add(but1);
p.add(but2);
group.add(but1);
group.add(but2);
getContentPane().add(p, BorderLayout.CENTER);
}
}
I did manage to find a solution that works, even if it's not exactly a beauty contest winner. If you have a better one, please post it!!
The problem seems to be that the KeyEvent is sent to the radio button and not to the pane or the text field. And when the system sees that the ALT key has been released, it invokes the default action.
Of course, a plain vanilla Alt when a radio button has the focus should still do what it is supposed to do: activate the menu bar.
If you press, say, Alt-S (our accelerator), the radio button will receive: keyPressed(Alt) -> keyPressed("S") -> keyReleased("S") -> keyReleased(Alt).
Thus, if we save the value of the last key pressed, we'll consume the last event (keyReleased(Alt)) unless the last key pressed was also an Alt.
This is a workaround, and not a pretty one, but it works. The code is as follows (I've left my debug statements in the code):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class MnemonicTest extends JFrame {
int codeLast = 0;
private final class RadioButtonKeyAdapter extends KeyAdapter {
private static final int NO_CODE = 0;
private int lastCode = 0;
#Override
public void keyPressed(KeyEvent e) {
System.out.println("pressed source: " + e.getSource() + "\n" + e.getKeyCode());
this.setLastCode(e.getKeyCode());
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("released source: " + e.getSource() + "\n" + e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_ALT && this.getLastCode() != e.getKeyCode()) {
e.consume();
}
this.setLastCode(NO_CODE);
}
private int getLastCode() {
return lastCode;
}
private void setLastCode(int lastCode) {
this.lastCode = lastCode;
}
}
private static final long serialVersionUID = 1L;
public MnemonicTest() {
super("MnemonicTest");
init();
}
public static void main(String[] args) throws Exception {
MnemonicTest test = new MnemonicTest();
test.setVisible(true);
}
private void init() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
setSize(new Dimension(500,400));
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(stopButton, BorderLayout.SOUTH);
JMenuBar jMenuBar = new JMenuBar();
JMenu menu = new JMenu("XXX");
JMenuItem a1 = new JMenuItem("a1", 'A');
JMenuItem b1 = new JMenuItem("b1", 'B');
JMenuItem c1 = new JMenuItem("c1", 'C');
menu.add(a1);
menu.add(b1);
menu.add(c1);
jMenuBar.add(menu);
this.setJMenuBar(jMenuBar);
JPanel p = new JPanel();
ButtonGroup group = new ButtonGroup();
JTextField textField = new JTextField("XXXXXXXXXX");
p.add(textField, BorderLayout.CENTER);
JRadioButton but1 = new JRadioButton("test");
but1.setMnemonic('s');
JRadioButton but2 = new JRadioButton("2222");
p.add(but1);
p.add(but2);
group.add(but1);
group.add(but2);
getContentPane().add(p, BorderLayout.CENTER);
but1.addKeyListener(new RadioButtonKeyAdapter());
but2.addKeyListener(new RadioButtonKeyAdapter());
}
}
I'm writting a program to encript data. It has a JTextArea to edit text, but I want to choose if I save it encripted or in plain text. For this I created a JDialog that appears when the save button is clicked. It contains two radio buttons: one to save the data encripted and the other to save in plain text. In the middle of them there is a JPasswordField requesting the key of the encription.
My question is if there is a simple way of making the TextField not useable and half transparent, when the option to save encripted is not selected. Or, if there isn't a simple way of doing it, a way to hide the TextArea. I tryed using a ChangeListener on the radio button but it isn't working. Here is my code:
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class StackOverflowVersion extends JFrame {
public static JFrame frame;
public StackOverflowVersion() {
dialogoCriptografar();
System.exit(EXIT_ON_CLOSE);
}
public void dialogoCriptografar(){
final ButtonGroup bGroup = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[2];
final JPasswordField passwordField = new JPasswordField(20);
// create the raio bunttons
buttons[0] = new JRadioButton("Encript document before saving");
buttons[1] = new JRadioButton("Just save it");
//ad them to the ButtonGroup
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
// select the option to encript
buttons[0].setSelected(true);
//creates a panel with the radio buttons and a JPasswordField
final JPanel box = new JPanel();
JLabel descricao = new JLabel("Choose an option to save:");
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(descricao);
box.add(buttons[0]);
box.add(passwordField);
box.add(buttons[1]);
// creates the dialog
final JDialog dialogo = new JDialog(frame, "Storage options", true);
dialogo.setSize(275,125);
dialogo.setLocationRelativeTo(frame);
dialogo.setResizable(false);
dialogo.add(box);
dialogo.setVisible(true);
/* Doesn't work:
buttons[0].addChangeListener(new ChangeListener(){
boolean visivel = true;//ele começa visivel
public void stateChanged(ChangeEvent event){
if(visivel){
box.remove(password);
SwingUtilities.updateComponentTreeUI(dialogo);
dialogo.revalidate();
dialogo.repaint();
visivel = false;
}
else{
box.add(password);
SwingUtilities.updateComponentTreeUI(dialogo);
dialogo.revalidate();
dialogo.repaint();
SwingUtilities.updateComponentTreeUI(dialogo);
visivel = true;
}
}
});
*/
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new StackOverflowVersion();
frame.setVisible(true);
}
});
}
}
My question is if there is a simple way of making the TextField not useable and half transparent,
Have you tried a simple
textField.setEditable(false);
Or
textField.setEnabled(false);
Observation in your code.
1) Add setVisible at the end after all the UI components' properties, events etc are set.
2) In your case you need a listener for each of the RadioButton.
3) Also I prefer using an ItemListener to a ChangeListener(fires even when mouse is moved over it).
Please check the code below.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main extends JFrame {
public static JFrame frame;
public Main() {
dialogoCriptografar();
System.exit(EXIT_ON_CLOSE);
}
public void dialogoCriptografar(){
final ButtonGroup bGroup = new ButtonGroup();
final JRadioButton[] buttons = new JRadioButton[2];
final JPasswordField passwordField = new JPasswordField(20);
// create the raio bunttons
buttons[0] = new JRadioButton("Encript document before saving");
buttons[1] = new JRadioButton("Just save it");
//ad them to the ButtonGroup
bGroup.add(buttons[0]);
bGroup.add(buttons[1]);
// select the option to encript
buttons[0].setSelected(true);
//creates a panel with the radio buttons and a JPasswordField
final JPanel box = new JPanel();
JLabel descricao = new JLabel("Choose an option to save:");
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(descricao);
box.add(buttons[0]);
box.add(passwordField);
box.add(buttons[1]);
// creates the dialog
final JDialog dialogo = new JDialog(frame, "Storage options", true);
dialogo.setSize(275,125);
dialogo.setLocationRelativeTo(frame);
dialogo.setResizable(false);
dialogo.add(box);
// Doesn't work:
buttons[0].addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
if(buttons[0].isSelected()) {
passwordField.setVisible(true);;
//SwingUtilities.updateComponentTreeUI(dialogo);
// System.out.println("asdasd");
box.revalidate();
box.repaint();
}
}
});
buttons[1].addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("a");
if(buttons[1].isSelected()) {
passwordField.setVisible(false);;
//System.out.println("asdasd");
//SwingUtilities.updateComponentTreeUI(dialogo);
box.revalidate();
box.repaint();
}
}
}); //
dialogo.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new Main();
frame.setVisible(true);
}
});
}
I have a JFrame that has custom swing component and JTextfield and JButton. JButton has set to default button. When I hit enter in the moment that textfield in focus, button will trigger. but when I hit enter in the moment that custom component in focus button will not trigger.
package org.laki.test;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class TestFrame extends JFrame {
private JTextField textField;
public TestFrame() {
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
getContentPane().add(textField);
textField.setColumns(10);
ComboBox comboBox = new ComboBox();
comboBox.addItem("lakshman");
comboBox.addItem("tharindu");
comboBox.addItem("Ishara");
getContentPane().add(comboBox);
JButton btnNewButton = new JButton("Test");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("enter is hitting...!!!");
}
});
getContentPane().add(btnNewButton);
this.rootPane.setDefaultButton(btnNewButton);
}
private class ComboBox extends JComboBox<String>
{
private static final long serialVersionUID = 10000012219553L;
#Override
public void processKeyEvent(final KeyEvent event)
{
if ((event.getKeyCode() == KeyEvent.VK_DOWN) ||
(event.getKeyCode() == KeyEvent.VK_SPACE))
{
doSomthing();
}
else if(event.getKeyCode() == KeyEvent.VK_ENTER)
{
//I added this to capture the enter event
}
}
}
public static void main(String[] args) {
TestFrame testframe = new TestFrame();
testframe.setSize(300, 400);
testframe.setVisible(true);
}
}
I can't remove processKeyEvent method, because it does special event in custom component.
what should I do to fire the button when I hit enter in the moment of focus in custom component?
Your custom component might have overridden JComponent.processKeyEvent() and not let to call it's parents implementation. Check and if not then pass key event to parent using
super.processKeyEvent(event);
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.