Hello guys I've been trying to do a small program which is just a window with a JButton that opens a JOptionPane on click and lets me input an entry for a vacation list. I want to add that entry as an JCheckBox to the JLabel every time the action of the JButton is performed. My problem currently is that even though my code seems so work the JCheckBox won't show up after inputting the String into the JOptionPane. It probably has to do something with actionPerformed being a void method? I'd be glad for some help and I'm sorry if that question has already occurred but I didn't find it anywhere.
Thanks in advance!
My Code:
public class Urlaub extends JFrame {
public Urlaub() {
super("Urlaub");
JFrame window = this;
window.setSize(800, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
JLabel grouped = new JLabel();
window.add(grouped);
grouped.setLayout(new FlowLayout());
JButton addThing = new JButton("Add things");
addThing.setVisible(true);
grouped.add(addThing);
addThing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String entry = JOptionPane.showInputDialog(this, "Enter item");
JCheckBox checkItem = new JCheckBox(entry);
grouped.add(checkItem); // this is the line which should add the JCheckBox to the JLabel/Window
}
});
}
}
You need to revalidate the container after changing it's children. This forces a repaint.
You're also adding the elements to a JLabel, which is unusual. You're better off with a JPanel:
super("Urlaub");
JFrame window = this;
window.setSize(800, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
JPanel grouped = new JPanel();
window.getContentPane().add(grouped);
grouped.setLayout(new FlowLayout());
JButton addThing = new JButton("Add things");
grouped.add(addThing);
grouped.add(new JCheckBox("je"));
addThing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String entry = JOptionPane.showInputDialog(this, "Enter item");
JCheckBox checkItem = new JCheckBox(entry);
grouped.add(checkItem); // this is the line which should add the JCheckBox to the JLabel/Window#
window.getContentPane().revalidate();
}
});
Related
I am trying to build a JFrame with four manual input JTextFields: description, hours, minutes, ID
and two JButtons: Submit and Reset
I need to disable the "Submit" button until all text fields have some data. To achieve this, I have used the DocumentListener and that is working fine, that is, initially the "Submit" button is disabled and gets enabled only when all text fields have some input.
PROBLEM: After "Submit" button is enabled, I need to hit the submit button twice to get the actual action trigger (probably first time is to restore focus after getting enabled, second time to do actual work). This issue does not happen with the "Reset" button.
TRIED AND DIDN'T WORK: I tried restoring focus using submit.requestFocusInWindow() and it brought focus to the "Submit" button but the last modified text field lost focus and I had to click it again to restore focus on that field.
Please assist. I am quite new to StackOverflow, so kindly don't close the thread.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel titlePanel = new JPanel();
JPanel descPanel = new JPanel();
JPanel timeWorkedPanel = new JPanel();
JPanel iDPanel = new JPanel();
titlePanel.add(title);
mainPanel.add(titlePanel);
descPanel.add(desc);
mainPanel.add(descPanel);
timeWorkedPanel.add(hour);
timeWorkedPanel.add(minute);
mainPanel.add(timeWorkedPanel);
iDPanel.add(iD);
mainPanel.add(iDPanel);
JTextArea reqList = new JTextArea();
reqList.setLineWrap(false);
reqList.setEditable(false);
JScrollPane reqListScroll = new JScrollPane (reqList);
reqListScroll.setPreferredSize(new Dimension(400,400));
reqListScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
reqListScroll.setColumnHeaderView(new JLabel(" REQUEST CREATED TIME WORKED"));
mainPanel.add(reqListScroll);
List<JTextField> textFieldList = new ArrayList<>();
textFieldList.add(desc);
textFieldList.add(hour);
textFieldList.add(minute);
textFieldList.add(csiID);
JButton submit = new JButton("SUBMIT");
JButton reset = new JButton("RESET");
buttonPanel.add(submit);
buttonPanel.add(reset);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createVerticalStrut(20)); // a spacer
JFrame mainFrame = new JFrame("Test Frame");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setSize(new Dimension(500,600));
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
submit.setEnabled(false);
DocumentListener docListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
boolean isEnabled = true;
for(JTextField tf : textFieldList) {
if(tf.getText().isEmpty())
isEnabled = false;
}
submit.setEnabled(isEnabled);
}
};
for(JTextField tf : textFieldList) {
tf.getDocument().addDocumentListener(docListener);
}
final WebDriver newDriver = driver;
final ChromeOptions newOptions = options;
//Click on "SUBMIT" button
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("submitting");
mainFrame.setVisible(false);
createTicket(newDriver, newOptions, subportfolio, title, desc , hour, minute, csiID);
mainFrame.setVisible(true);
} catch (InterruptedException e1) {
}
}
});
//Click on "RESET" button
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
desc.setText(null);
hour.setText(null);
minute.setText(null);
csiID.setText(null);
}
});
I'm working on a Java assignment. I have many classes linked together and one of the constructors is the following:
public class RemovePatientForm extends JFrame implements ActionListener {
JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel midPanel = new JPanel();
JLabel removeLabel = new JLabel("Please type in the ID of the patient to be removed");
JLabel idLabel= new JLabel("ID");
JTextField idText=new JTextField();
JButton submit = new JButton("Submit");
JButton reset = new JButton("Clear");
boolean externalForm = false;
public RemovePatientForm(){
setTitle("Removing a patient");
setLayout(new BorderLayout());
setSize(400,200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
add("North", northPanel);
add("South", southPanel);
northPanel.add(removeLabel);
southPanel.add(submit);
southPanel.add(reset);
add(idLabel);
add(idText);
submit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==submit){
if(!(idText.getText().equals(""))){
int selectedvalue = JOptionPane.showConfirmDialog(null, "Do you want to proceed with the deletion?", "do you want to proceed with the deletion?", JOptionPane.YES_NO_OPTION);
if(selectedvalue==JOptionPane.YES_OPTION){
int id=Integer.parseInt(idText.getText());
if(searchForId(id)){
removeToDatabase();
dispose();
}
else{
JOptionPane.showMessageDialog(null,"This ID is not available!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Nothing is affected!");
}
}
else{
JOptionPane.showMessageDialog(null,"You have to fill the ID number!","Warning",JOptionPane.ERROR_MESSAGE);
}
}
if(arg0.getSource()==reset && externalForm==false){
idText.setText("");
}
}
The problem in here is that when I press the submit button, everything is okay and working as written within the code.
But, if I press the reset button, nothing is happening.
What do you think the solution is? is this code enough to determine the problem?
You didn't add an action listener for the reset button.. i think you forgot it. Try to add it and it should work.
Add this code within your constructor:
reset.addActionListener(this);
Please help me out to separate these ActionListeners in a periodic table that I am attempting to complete. When I execute the program and click on 'H', it opens all the other elements and when the others are clicked, it does not work. So I need a way to separate these using any method...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeriodicTable
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Elements");
frame.setVisible(true);
frame.setSize(1000,1500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("H");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("He");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Li");
panel.add(button3);
button3.addActionListener (new Action2());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("H");
frame2.setVisible(true);
frame2.setSize(1000,1500);
JLabel label = new JLabel("Hydrogen");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("He");
frame3.setVisible(true);
frame3.setSize(1000,1500);
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Li");
frame4.setVisible(true);
frame4.setSize(1000,1500);
JLabel label = new JLabel("Lithium");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
}
Thanks in advance.
(note: only the first 3 elements are coded for...)
When I execute the program and click on 'H', it opens all other elements
Only one frame opens for me.
and when the others are clicked, it does not work.
Each button opens a single frame for me.
However, button 3 opens the wrong frame because you add the wrong listener to the button:
//button3.addActionListener (new Action2());
button3.addActionListener (new Action3());
Other issues:
You should add the components to the frame BEFORE making the frame visible.
Don't hardcode screen sizes, you never know what size screen other users will be using
So the order of your code might be something like:
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame("He");
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
And of course you really don't want to create dozens of separate ActionListeners. You want to make the listener more generic so it can be shared.
Something like:
static class Action implements ActionListener
{
public Action(String element, String description)
{
this.element = element;
this.description = description;
}
public void actionPerformed (ActionEvent e)
{
JLabel label = new JLabel(description);
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame(element);
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
Then when you create the listener you use:
button3.addActionListener (new Action("HE", "Helium"));
I am writing a very simple GUI, that contains 3 buttons, 2 labels, 2 text fields and one text area. Strangely, the result is unstable: when running the class the GUI appears with random number of the controls. I tried various layout managers, changing the order among the control - nothing.
Can someone help?
package finaltestrunner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FinalTestGUI extends JFrame implements ActionListener
{
public Boolean startState = false;
JButton sofButton;
JButton startStopButton;
JButton exitButton;
JTextField loopCounts;
JTextField trSnField;
JTextArea resultField = null;
public FinalTestGUI()
{
// The constructor creates the panel and places the controls
super(); // Jframe constructor
JFrame trFrame = new JFrame();
trFrame.setSize(1000, 100);
trFrame.setVisible(true);
trFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trFrame.setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
// trFrame.setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
trFrame.add(trControlPanel);
// cpl.add(trResultField);
startStopButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trStartStopButton)
{
startState = !startState;
if (startState)
{
startStopButton.setText("Run ");
startStopButton.setForeground(Color.red);
}
else
{
startStopButton.setText("Stop");
startStopButton.setForeground(Color.green);
}
}
});
sofButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trSofButton)
{
loopCounts.setText("SOF\n");
}
});
exitButton.addActionListener (new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trExitButton)
{
System.exit(0);
}
});
} // End of the constructor
#Override
public void actionPerformed (ActionEvent ae) { }
public void atpManager ()
{
String selectedAtp = "";
}
}
There are a couple of issues with this code:
You are already inheriting from JFrame, so you do not need to create yet another JFrame
You are showing your frame with setVisible(true) and afterwards adding components to it. This invalidates your layout, you need to revalidate afterwards (or move setVisible() to a position where you already added your components)
You are adding your components to the JFrame directly, but you need to use its contentpane. Starting with Java 1.5, the JFrame.add() methods automatically forward to the content pane. In earlier versions, it was necessary to retrieve the content pane with JFrame.getContentPane() to add the child components to the content pane.
Try this:
public FinalTestGUI() {
// The constructor creates the panel and places the controls
super(); // Jframe constructor
setSize(1000, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
// getContentPane().add(trControlPanel); // pre 1.5
add(trControlPanel); // 1.5 and greater
setVisible(true);
}
I got a little problem with a JOptionPane which I use to warn user if wrong input is found. It works correct first time. But when I close down the JFrame which calls for that JOptionPane, and open it again it will this time call for it twice. And it will stack for every close down I do.
I have tried to look for the problem without any luck. I can provide the code, but it is quite large though.
Third EDIT: I have found and solved the problem now.
Ok, I provided the code I use. I have cut it down so it only show the necessary one. I dont think it will compile, but this is how I use the addActionListener();
public class BorderLayoutDemo extends JFrame implements ActionListener {
private JButton button1 = new JButton("L?gg till kund");
private JButton button2 = new JButton("Ta bort kund");
private JButton button3 = new JButton("Visa kund");
private JButton button4 = new JButton("Lista alla kunder");
private JButton button5 = new JButton("Avsluta");
private JButton button6 = new JButton("Change");
private JTextArea TextWindow = new JTextArea("Hej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\n");
private JScrollPane scrollPane = new JScrollPane(TextWindow); //l?gger in TextWindow s? att det f?r en scroll-bar
private JPanel aPanel = new JPanel();
private JFrame aFrame = new JFrame();
private JTextField aTextfield1 = new JTextField();
private JTextField aTextfield2 = new JTextField();
private JButton aButton1 = new JButton("L?gg till kund");
private JButton aButton2 = new JButton("St?ng");
public BorderLayoutDemo() {
setTitle("Bankregister");
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
panel.setLayout(new GridLayout(6,1,55,5)); //row, cols, hgap, vgap
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
JPanel panel2 = new JPanel();
panel2.add(panel);
add(panel2,BorderLayout.WEST);
add(scrollPane,BorderLayout.CENTER);
setJMenuBar(menu());
setSize(600,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void addCustomer(boolean status) {
if(status) {
aFrame.setTitle("L?gg till kund");
aFrame.setSize(200,300);
aFrame.setLayout(new GridLayout(3,1));
aPanel.setLayout(new GridLayout(2,1)); //rad, kolumn
aPanel.add(aTextfield1);
aPanel.add(aTextfield2);
aButton1.addActionListener(this);
aButton2.addActionListener(this);
System.out.println("Foo!!!!!!!!!!!!!");
aFrame.add(aPanel);
aFrame.add(aButton1);
aFrame.add(aButton2);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setLocationRelativeTo(null);
aFrame.setVisible(true);
}
else {
aFrame.setVisible(false);
}
}
public static void main(String[] args) {
new BorderLayoutDemo();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
setEnabled(false);
addCustomer(true);
}
//IFs f?r addCustomer();
else if(e.getSource() == aButton1) {
if((aTextfield1.getText().isEmpty() || aTextfield2.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "You miss to fill out the fields");
}
else {
JOptionPane.showMessageDialog(null, "Added");
Kund kund = new Kund(aTextfield1.getText(),aTextfield2.getText());
setEnabled(true);
register.add(kund);
}
}
else if(e.getSource() == aButton2) {
setEnabled(true);
addCustomer(false);
}
Sounds like you are adding the "validation listener" every time you open the JFrame. So check your "addListenerXXX" code to make sure it is only added/created once.
Which also leads to the question why are you using a JFrame for this? Typically an application has a single JFrame. Then, if you need a window to enter data you create a JDialog.
By passing null as the first parameter of that method you are creating a default JFrame that the JOptionPane uses as its parent component and not the JFrame you have created in your code. If you provide more detail in your question I'm sure someone here will provide you with a much more detailed answer.