How do I add actions to buttons? - java

I want my buttons to print to the console when I click them. Here's my code. Im looking to make a basic app using this code, and I was wondering how to make the buttons have actions. For the first time, I just want to start with the console for the first time, but later possibly display images?
public static void main(String[] args) {
JFrame frame = new JFrame("GUI");
frame.setSize(320, 300);
frame.setBackground(Color.WHITE);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setSize(50,50);
JLabel label = new JLabel();
frame.add(panel);
panel.add(label);
label.setText("Welcome to Team 1389!");
Container contentPane = getContentPane();
contentPane.setBackground(Color.blue);
contentPane.setLayout(new FlowLayout());
JButton button = new JButton("MATCHES");
button.setSize(100, 30);
button.setLocation(95, 45);
button.addActionListener(null);
button.setVisible(true);
frame.add(button);
JButton button2 = new JButton("PIT TEAM");
button2.setSize(100, 30);
button2.setLocation(95, 100);
button2.setVisible(true);
frame.add(button2);
JButton button3 = new JButton("SCOUTING");
button3.setSize(100, 30);
button3.setLocation(95, 150);
button3.setVisible(true);
frame.add(button3);
}
private static Container getContentPane() {
// TODO Auto-generated method stub
return null;
}
}

You can look at this tutorial on Oracle's website, it explains things well:
Use an ActionListener. They are interfaces so you will need to add unimplemented methods where the event is handled:
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
//do stuff..
}
});
You can also create the listener separately before adding it if you desire to do so:
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
//do stuff..
}
};
button.addActionListener(listener);

Related

How to create multiple frames or windows in GUI?

I am new to creating GUI. I want to know how to create multiple windows. I want to show another frame if a button is to be clicked. I have searched how and i saw that some people are making another GUI form and just calling the other form i a button was clicked, but i dont understand how.
There are numerous ways to do this. One of the main ways is to create a new Java Class with its own properties. Here is a nexample:
JButton button = new JButton("Button_Leads_To_This_Window");
button.addActionListener( new ActionActionListener()
{
public void actionPerformed(ActionEvent e)
{
NewFrame();
}
});
This will allow the button to call a new window, similar as the way you called the "My Empire" window. For example NewFrame() class will look like this:
public static void newFrame()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
Here is more information to the matter:
https://www.thoughtco.com/create-a-simple-window-using-jframe-2034069
https://www.youtube.com/watch?v=RMz9LYY2g4A
Good luck.

How to make button open the frame in a relevant language?

I have two classes, each one with JFrame.
The first frame contains two buttons, they are supposed to open the next frame in a proper language. My task is: I open the first frame (start program), I want to choose english language, I click on the button with "English" label, it opens the next frame with program. All labels, all buttons are in English.
When I want it to be in e.g. French, I click French button in the first frame, and the second one opens with all labels and button in French
So, my question is this: how to combine action with clicking on the button with opening the frame in a proper language?
Currently all buttons opens the same frame with labels in one language.
Here is a sample of my code of the first frame and "View" is the next JFrame in next class View:
public class StartFrame extends JFrame {
JButton button1 = new JButton(new ImageIcon(((new ImageIcon("flag.png")).getImage()).getScaledInstance(100, 75, java.awt.Image.SCALE_SMOOTH)));
JButton button2 = new JButton(new ImageIcon(((new ImageIcon("flag2.jpg")).getImage()).getScaledInstance(100, 75, java.awt.Image.SCALE_SMOOTH)));
public StartFrame() {
setSize(480,360);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(2,1));
JPanel panel2 = new JPanel();
add(panel2);
panel2.setLayout(null);
panel2.setBackground(Color.white);
panel2.setLayout(new FlowLayout());
button1.setPreferredSize(new Dimension(100, 75));
button2.setPreferredSize(new Dimension(100, 75));
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
button1.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View f = new View();
f.setVisible(true);
f.setLocationRelativeTo(null);
dispose();
}
});
button2.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View en = new View();
en.setVisible(true);
en.setLocationRelativeTo(null);
dispose();
}
});
}
public static void main(String[] args) {
StartFrame frame = new StartFrame();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
You could add a language field to the class View. Then, on your action listener you change the value of that field:
button1.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View f = new View();
f.setLanguage("French");
f.setVisible(true);
f.setLocationRelativeTo(null);
dispose();
}
});
button2.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e) {
View en = new View();
en.setLanguage("English");
en.setVisible(true);
en.setLocationRelativeTo(null);
dispose();
}
});

How to retrieve a swing form values

I have two swing Frames. Frame one will contain a button.when we click the button we will get another frame which will have the five lables(which are the varibles of a class.) with the textfields beside, and a submit button. user will enter the values and clicks submit butoon.
My question is how can retrieve the values from that Frame two when user clicks submit button .i have the code like blelow.
public class Form extends JFrame implements ActionListener {
JPanel panel = new JPanel();
JFrame frame = new JFrame("New frame");
JPanel panel2 = new JPanel();
JButton button = new JButton("add");
JButton button2 = new JButton("Submit");
JLabel label;
JTextField textfield;
public Form() {
setLayout(new BorderLayout());
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setPreferredSize(new Dimension(300, 200));
button.addActionListener(this);
add(panel, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
}
public static void main(String[] a) {
Form s = new Form();
s.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
s.pack();
s.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
dispose();
panel2.setLayout(new FlowLayout());
panel2.setPreferredSize(new Dimension(1000, 1000));
final Field[] fields = Employee.class.getFields();
for (Field temp : fields) {
label = new JLabel(temp.getName());
label.setBounds(20, 50, 100, 20);
textfield = new JTextField(20);
textfield.setBounds(140, 50, 100, 20);
panel2.add(label);
panel2.add(textfield);
}
frame.add(panel2);
frame.setSize(290, 300);
frame.setVisible(true);
button2.setSize(20, 30);
frame.add(button2, BorderLayout.SOUTH);
repaint();
revalidate();
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
}
}
Start by taking a look at The Use of Multiple JFrames, Good/Bad Practice?
Instead of using a second frame, you should use a modal dialog, which, when made visible, will halt your programs execution at that point until it's disposed, at which time it will return and you can extract the values you want from it.
See How to Make Dialogs for more details

Add JPanel to contentPane within actionListener

I'm trying to add a JPanel to my JFrame within an actionListener method, but it appears only after the second click on the button. This is a portion of my code where panCours is a JPanel and ConstituerData the targeted JFrame :
addCours.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
panCours.setBounds(215, 2, 480, 400);
panCours.setBorder(BorderFactory.createTitledBorder("Saisir les données concernant le cours"));
ConstituerData.this.getContentPane().add(panCours);
}
});
I don't understand why it doesn't appear as soon as I click on the button. Any explanation and help about how to fix this ?
You'll need to add a call to repaint(); (as well as probably revalidate();) to get the JPanel to show immediately. A basic example demonstrating your problem (and the solution) below;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JButton button = new JButton("Test");
button.setBounds(20, 30, 100, 40);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setBounds(215, 2, 480, 480);
frame.add(panel);
frame.revalidate(); // Repaint here!! Removing these calls
frame.repaint(); // demonstrates the problem you are having.
}
});
frame.add(button);
frame.setSize(695, 482);
frame.setVisible(true);
}
}
The above said, (as suggested by others) it's only right that I recommend against the use of a null layout in future. The swing layouts are a little awkward to begin with, but they will help you a great deal in the long run.
the answer can be found in the following snippet:
you need to revalidate() the contentPane, not repaint the frame. you can add any panel you want to the contentpane like this. if you declare contentPane as a private field you dont need your getContentPane() call. contentPane is global so it can be reffered to directly from anywhere within the class.
be careful about NullPointerExeptions which can be thrown if you refer to it before initialising.
public class testframe extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testframe frame = new testframe();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public testframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
setContentPane(contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel a = new JPanel();
contentPane.add(a);
contentPane.revalidate();
}
});
contentPane.add(btnNewButton);
}
}

How to open a new window by clicking a button

As a part of my program, I need to have a button that when the user click on it, it opens a new window.
Well I guess I should have a class that make the frame and call it by the button. but I don't have any idea to start. I just got my button in the program, but it does not work. So can some tell me how to do it? or code it.
Here is a simplified version of what you want to do:
JButton button = new JButton("New Frame");
button.addActionListener( new ActionActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Create a method named "createFrame()", and set up an new frame there
// Call createFrame()
}
});
You would probably want to call some method in the ActionListener rather than make the frame on actionPerformed. Maybe something like this:
public static void createFrame()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
What that frame should look like:
new CLASS_NAME().setVisible(true);
eg. new NewJFrame().setVisible(true);

Categories

Resources