So, we can create for example a button dynamically:
panel.add(new JButton("Button"));
validate();
But the question is, how do we make calls to those elements later? For example, how do I add an event listener to this button created above, like, 100 lines of code later?
Create a variable for your JButton:
JButton jButton = new JButton("Button");
panel.add(jButton);
validate();
/*
*
*
100 lines of code
*
*/
// add an event listener
jButton.addActionListener((ActionEvent) -> {
// do something
});
I've always created my buttons before adding to the panel like so
private JPanel buttonPanel() { //button panel method containting
JPanel panel = new JPanel();
JButton addButton = new JButton("Add");
addButton.setToolTipText("Add Customer Data");
JButton editButton = new JButton("Edit");
editButton.setToolTipText("Edit selected Customer");
JButton deleteButton = new JButton ("Delete");
deleteButton.setToolTipText("Delete selected Customer");
addButton.addActionListener((ActionEvent) -> {
doAddButton();
});
editButton.addActionListener((ActionEvent) -> {
doEditButton();
});
deleteButton.addActionListener((ActionEvent) -> {
doDeleteButton();
});
panel.add(addButton);
panel.add(editButton);
panel.add(deleteButton);
return panel;
}
Allows you do something like this later on.
private void doAddButton() { //provides action for add button
CustomerForm customerForm = new CustomerForm(this, "Add Customer", true);
customerForm.setLocationRelativeTo(this);
customerForm.setVisible(true);
}
In order to bind event listeners or other functionality into the button, you'd need to store a reference to it in a variable. So, instead of
panel.add(new JButton("Button"));
You could initialize the button with
JButton myButton = new JButton("Button");
panel.add(myButton);
and then later in your code
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something
}
});
Related
I'd like to create a JTable that displays the values from a created object by clicking a button.
The object is created here:
public class Getraenkeverwaltung extends Firma {
public static Getraenk getraenk1 = new Getraenk(1, "Pepsi Maxx Original", 0.99, 500);
...
}
Now with the following code I'm creating the window with all the panels.
public void buildUi() {
// Create the main window
Frame fr = new Frame();
fr.setLayout(new BorderLayout());
// Define colors
Color headerColor = new Color(38, 70, 83);
Color contentColor = new Color(42, 157, 143);
// create navigation pane at the top
JPanel navigation = new JPanel();
navigation.setBackground(headerColor);
navigation.setLayout(new GridLayout(1,4));
navigation.setPreferredSize(new Dimension(800,50));
// create content pane in the middle
JPanel content = new JPanel();
content.setBackground(contentColor);
content.setPreferredSize(new Dimension(800, 500));
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
// create footer pane at the bottom
JPanel footer = new JPanel();
footer.setBackground(headerColor);
footer.setLayout(new GridLayout(1,1));
footer.setPreferredSize(new Dimension(800, 50));
footer.setLayout(new BorderLayout());
// show impressum in the footer pane
JLabel impressum = new JLabel(Firma.impressum());
impressum.setHorizontalAlignment(SwingConstants.CENTER); // Platziert den Text mittig
impressum.setForeground(Color.white);
// create the buttons
Button btnBestand = new Button("Bestand anzeigen");
Button btnVerkauf = new Button("Verkaufen");
Button btnErhoehen = new Button("Bestand erhoehen");
Button btnExit = new Button("Exit");
// display beverages on button click
btnBestand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String column [] = {"Artikelnummer", "Artikel", "Bestand"};
Object data [][] = {
{getraenk1.getId(), getraenk1.getName(), getraenk1.getBestand()},
{getraenk2.getId(), getraenk2.getName(), getraenk2.getBestand()},
{getraenk3.getId(), getraenk3.getName(), getraenk3.getBestand()}
};
JTable table = new JTable(data, column);
JScrollPane sp = new JScrollPane(table);
content.remove(sp);
content.revalidate();
content.repaint();
content.add(sp);
}
});
// open new sale window
btnVerkauf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Verkaufen();
}
});
// close the program
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// add the buttons to the navigation pane
navigation.add(btnBestand);
navigation.add(btnVerkauf);
navigation.add(btnErhoehen);
navigation.add(btnExit);
// add the impressum to the footer pane
footer.add(impressum, BorderLayout.CENTER);
// add the three main panels to the window
fr.add(navigation, BorderLayout.NORTH);
fr.add(content, BorderLayout.CENTER);
fr.add(footer, BorderLayout.SOUTH);
fr.pack();
}
One of the problems is the button functionality of btnBestand. Whenever I'm changing the value of some of my products, it should refresh the JTable.
Unfortunately, there's a new JTable displayed everytime I click on the button,
so it looks like this after hitting the button four times.
I'd like to just display the table with the new value after clicking on the button again.
Thanks in advance.
// edit:
Removed the content.remove(sp); pointed out by Gjermund Dahl, as it is unnecessary in this context. Thank you.
Problem still persists
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();
}
});
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);
I am trying to create a GUI that gives you hints when the program is opened. I am not sure how I am going to be able to add my text and then create buttons that allow me to go to the next text or return to the previous. I am not sure what type of actionListener I should use for that.
import java.awt.*;
import javax.swing.*;
public class HelpfulHints extends JFrame{
private JTextArea area; //This is my textarea to display hints
private JPanel panel;
private JButton close, previous, next; //Three buttons to operate program
public HelpfulHints(){
super("Tip of the Day");
setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
//Create first button
close= new JButton("Close");
add(close);
//Create second button
previous = new JButton("Previous");
add(previous);
//Create third button
next = new JButton("Next");
add(next);
//Add buttons to panel
panel.add(close);
panel.add(previous);
panel.add(next);
//Keep buttons to south of panel
add(panel, BorderLayout.SOUTH);
//Create ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
close.addActionListener(handler);
previous.addActionListener(handler);
next.addActionListener(handler);
//Create the helpful hint area on the screen
area = new JTextArea();
area.setEditable(true);
area.setLayout(new FlowLayout(FlowLayout.CENTER));
add(area, BorderLayout.CENTER);
setVisible(true);
}
//Inner class for button event handling
private class ButtonHandler implements ActionListener{
//handle Button event
#Override
public void actionPerformed(ActionEvent e){
}
}
}
I have updated the content of listener for your needs.
private JTextArea area; //This is my textarea to display hints
private JPanel panel;
private JButton close, previous, next; //Three buttons to operate program
private List<String> tips = new ArrayList<String>();
private int displayedTipIndex = 0;
public HelpfulHints(){
super("Tip of the Day");
// set up your tips
tips.add("First Tip");
tips.add("Second Tip");
tips.add("Third Tip");
// ... your other code stays the same...
//Create the helpful hint area on the screen
area = new JTextArea();
area.setEditable(true);
area.setLayout(new FlowLayout(FlowLayout.CENTER));
// set first tip
area.setText(tips.get(displayedTipIndex));
add(area, BorderLayout.CENTER);
// disable previous button when we start
previous.setEnabled(false);
//
setVisible(true);
}
//Inner class for button event handling
private class ButtonHandler implements ActionListener{
//handle Button event
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==next){
displayedTipIndex++;
area.setText(tips.get(displayedTipIndex));
// disable the next button if no more tips
if(displayedTipIndex>=tips.size()-1){
next.setEnabled(false);
}
// re-enable previpous button
previous.setEnabled(true);
}
if(e.getSource()==previous){
displayedTipIndex--;
area.setText(tips.get(displayedTipIndex));
/// disable the previous button if no more tips
if(displayedTipIndex<0){
previous.setEnabled(false);
}
// re-enable next button
next.setEnabled(true);
}
if(e.getSource()==close){
System.exit(0);
}
}
}
I'm building a Swing program and I want to be able to use a button to change certain features (Font, ForeGround Color, BackGround Color, etc.) of JComponents (JLabel, JButton).
I can do this without a problem if the components have all been explicitly declared and defined, but I cannot figure out how to do it if they are implicitly built using generic methods.
Below is the gist of what I have so far, minus some unimportant details. When styleButton1 and 2 are clicked, I want to refresh or rebuild the JFrame such that the new values for features/style (in this example, Font) are used for the components (testButton1 and 2), by changing currentFont and then repainting.
I'm not getting any errors with this, but frame and components are not being rebuilt/refreshed, i.e., nothing happens when the style buttons are clicked.
Any ideas on how to make this work? Or any other approaches I can use to get the desired effect?
//imports
public class GuiTesting extends JFrame {
public static void main(String[] args) {
frame = new GuiTesting();
frame.setVisible(true);
}
static JFrame frame;
static Font standardFont = new Font("Arial", Font.BOLD, 10);
static Font secondFont = new Font("Times New Roman", Font.PLAIN, 10);
static Font currentFont = standardFont;
public GuiTesting() {
setTitle("GUI Testing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(basicButton("Button1"));
mainPanel.add(basicButton("Button2"));
mainPanel.add(style1Button("Style 1"));
mainPanel.add(style2Button("Style 2"));
}
public static JButton basicButton(String title) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(currentFont);
return button;
}
public static JButton style1Button(String title) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(standardFont);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentFont = standardFont;
frame.repaint();
}
});
return button;
}
public static JButton style2Button(String title) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(secondFont);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentFont = secondFont;
frame.repaint();
}
});
return button;
}
}
You can store components, which need to refresh style in a list :
private static List<JComponent> components = new ArrayList<JComponent>();
add then in your basicButton() method add new component to refreshing components:components.add(button);
And then in ActionListener you can execute next lines for refreshing style:
for(JComponent c : components){
c.setFont(currentFont);
}
Or you can pass components directly to ActionListener like next :
JButton b1;
JButton b2;
mainPanel.add(b1 = basicButton("Button1"));
mainPanel.add(b2 = basicButton("Button2"));
mainPanel.add(style1Button("Style 1",b1,b2));
and style1Button() code:
public static JButton style1Button(String title,final JComponent... components) {
JButton button = new JButton(title);
button.setPreferredSize(new Dimension(80, 30));
button.setFont(standardFont);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentFont = standardFont;
for(JComponent c : components){
c.setFont(currentFont);
}
frame.repaint();
}
});
return button;
}
Create a styleOne method in your JComponent class that sets all of the values you need. It will have access to all fields of your class. Inside the action listener call this method.
Also, don't create your buttons statically like that. Create them within the constructor directly. If you want to override the look of the buttons do it within an init method or constructor. Or, better yet, subclass JButton.