So I am trying to make a menu in swing of 8 functions. This code i have right now.
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Menu extends JFrame {
public Menu(){
init();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
Menu menu = new Menu();
menu.setVisible(true);
}
});
}
private void init() {
setTitle("Group 2");
setSize(300, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton quitButton = new JButton("E(X)it");
quitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
createLayout(quitButton);
JButton nameAsk = new JButton("What is your name?");
nameAsk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
}
});
createLayout(nameAsk);
}
private void createLayout(JComponent... arg){
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(arg[0]));
gl.setVerticalGroup(gl.createSequentialGroup().addComponent(arg[0]));
}
}
The problem is when i add one more button the other one goes away. I think its on top of other button but i am confused now.
Related
I am trying to get the buttons to at least execute something when they are pressed and BlueJ doesn't show any errors, but when I execute the Program and I try to press the buttons, nothing happens. I am really unsure why that is the case. I would appreciate any help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MainMenu
{
JFrame frame= new JFrame();
JButton button = new JButton("Singleplayer");
JButton button2 = new JButton("Multiplayer");
MainMenu(){
prepareGUI();
}
public void prepareGUI(){
frame.setTitle("Game");
frame.getContentPane().setLayout(null);
frame.add(button);
frame.add(button2);
button.setBounds(100,200,100,40);
button2.setBounds(200,200,100,40);
frame.setVisible(true);
frame.setBounds(200,200,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setUpButtonListeners(){
ActionListener buttonlistener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.green);
System.out.println("Singleplayer Selected");
}
};
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame.getContentPane().setBackground(Color.red);
System.out.println("Multiplayer Selected");
}
};
button.addActionListener(buttonlistener);
button2.addActionListener(buttonlistener2);
}
public class MainClass {
public void main(String args[] )
{
new MainMenu();
}
}
}
setUpButtonListeners() are not executed in the program. So action listeners are not available. you can include setUpButtonListeners() in prepareGUI method.
Here I have test application, where I can't understand why ActionListener from Test class doesn't work. Each help will make me happy. Thanks :)
Here's code;
package com.company;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JFrame {
Main(){
GUI m = new GUI();
this.getContentPane().add(m.panel);
this.setDefaultCloseOperation(3);
this.setBounds(0,0,400,200);
this.setLocationRelativeTo(null);
this.requestFocus();
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
new Test();
}
});
}
}
class GUI{
GUI(){
initComp();
btn();
}
JPanel panel = new JPanel();
JButton button1;
JTextField textField;
private void initComp(){
textField = new JTextField(10);
button1 = new JButton("TEST");
panel.add(textField);
panel.add(button1);
}
public String getEnteredText(){
return textField.getText().trim(); //trim dodatkowy
}
public void btn(){
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.out.println("Test from GUI-class");
}
});
}
}
class Test{
Test(){
buttonGetter();
}
GUI m = new GUI();
String kol;
public void buttonGetter(){
m.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.out.println("Test from Test-class");
}
});
}
}
Test doesn't add anything to any components/windows, so it's never visible on the screen, only the instance of GUI, which is created in Main is visible.
A possibly better solution would be to use class inheritance to extend the GUI and override the btn method in order to provide your custom implementation, which might look something like...
public class Test extends GUI {
#Override
public void btn() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.out.println("Test from Test-class");
}
});
}
}
Then instead of creating an instance of GUI in the Main method, you create an instance of Test instead, for example;
GUI m = new Test();
Runnable example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
Main() {
GUI m = new Test();
this.getContentPane().add(m.panel);
this.setDefaultCloseOperation(3);
this.setBounds(0, 0, 400, 200);
this.setLocationRelativeTo(null);
this.requestFocus();
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
public class GUI {
GUI() {
initComp();
btn();
}
JPanel panel = new JPanel();
JButton button1;
JTextField textField;
private void initComp() {
textField = new JTextField(10);
button1 = new JButton("TEST");
panel.add(textField);
panel.add(button1);
}
public String getEnteredText() {
return textField.getText().trim(); //trim dodatkowy
}
public void btn() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.out.println("Test from GUI-class");
}
});
}
}
public class Test extends GUI {
#Override
public void btn() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
System.out.println("Test from Test-class");
}
});
}
}
}
I want to make a window that when you press the buttons it will show the phrase "I Love You" in different language in the text area. I Just don't know how to connect the text area in the buttons. I have three classes. I tried many ways I could think and I also search the things related to this but I can't find any useful
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainClass {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
private ToolBar Tulbar = new ToolBar();
private JTextArea textArea = new JTextArea();
public MainFrame() {
super("This window loves you");
setLayout(new BorderLayout());
add(Tulbar, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ToolBar extends JPanel{
private JButton Button1 = new JButton("Korean");
private JButton Button2 = new JButton("Japanese");
private JButton Button3 = new JButton("French");
private JButton Button4 = new JButton("Italian");
private JButton Button5 = new JButton("English");
private JButton Button6 = new JButton("Tagalog");
public ToolBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
//added buttons
add(Button1);
add(Button2);
add(Button3);
add(Button4);
add(Button5);
add(Button6);
}
public ToolBar(JTextArea frame) {
Button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Saranghae");
}
});
Button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Aishiteru");
}
});
Button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Je t\'aime");
}
});
Button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Ti\'amo");
}
});
Button5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("I Love You");
}
});
Button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Mahal Kita");
}
});
}
}
Since you are calling Button1.addActionListener in public ToolBar(JTextArea frame) constructor, you should invoke this constructor to invoke the code in it. But instead you are invoking public ToolBar() constructor.
To fix this instead of:
private ToolBar Tulbar = new ToolBar();
private JTextArea textArea = new JTextArea();
you should write:
private JTextArea textArea = new JTextArea();
private ToolBar Tulbar = new ToolBar(textArea);
and in ToolBar fix the constructors, instead of:
public ToolBar() {
// ... STUFF 1 ...
}
public ToolBar(JTextArea frame) {
// ... STUFF 2 ...
}
you should write:
public ToolBar(JTextArea frame) {
// ... STUFF 1 ...
// ... STUFF 2 ...
}
or
public ToolBar() {
// ... STUFF 1 ...
}
public ToolBar(JTextArea frame) {
this();
// ... STUFF 2 ...
}
Please learn Java Naming Conventions and use it all the time. You probably don't think it's important, but I promise it will save you from making stupid mistakes, and will save your time fixing them.
loadingLab=new JLabel("The name is being saved..");
loadPanel.add(loadingLab);
submitBttn=new JButton("Submit");
submitBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Submit Button Clicked!!");
try {
//something is wrong in here as it throws an exception
//what is wrong?
frame.setUndecorated(false);
frame.setOpacity(0.55f);
//when above both lines are commented, the code works fine
//but doesnt have transparency
frame.add(loadPanel,BorderLayout.SOUTH);
frame.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
I am trying to display transparent JFrame when "submit" button is clicked which displays panel with a JLabel...
I have tried using setOpacity(0.55f), but it throws exception.. what am i doing wrong?
Unfortunately I think there's no way to keep the system window decoration, you will probably have to go with the default one. Since I'm not 100% sure if you want to toggle the opacity of the whole frame or just the frame's background, I've included both functions in my example. (mKorbels answer help you more if you don't want to have a decoration)
Code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
Color defaultBackground = getBackground();
float defaultOpacity = getOpacity();
JToggleButton button1 = new JToggleButton("Toggle background transparency");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button1.isSelected()) {
setBackground(new Color(defaultBackground.getRed(), defaultBackground.getGreen(),
defaultBackground.getBlue(), 150));
} else {
setBackground(defaultBackground);
}
}
});
JToggleButton button2 = new JToggleButton("Toggle opacity of whole frame");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
if (button2.isSelected()) {
setOpacity(0.55f);
} else {
setOpacity(defaultOpacity);
}
setVisible(true);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button1);
getContentPane().add(button2);
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
});
}
}
Picture of frame with no togglebutton selected:
Picture of frame with the first togglebutton selected:
Picture of frame with the second togglebutton selected:
#Programmer007 wrote - the exception is "
java.awt.IllegalComponentStateException: The frame is displayable."
please where I can't see any, for more info about the possible exceptions to read,
as mentioned no idea, everything is about your effort, transformed to the SSCCE / MCVE, short, runnable, compilable
.
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GenericForm extends JDialog {
private static final long serialVersionUID = 1L;
private Timer timer;
private JDialog dialog = new JDialog();
private int count = 0;
public GenericForm() {
dialog.setSize(400, 300);
dialog.setUndecorated(true);
dialog.setOpacity(0.5f);
dialog.setName("Toggling with opacity");
dialog.getContentPane().setBackground(Color.RED);
dialog.setLocation(150, 150);
dialog.setVisible(true);
timer = new javax.swing.Timer(1500, updateCol());
timer.setRepeats(true);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Hello World") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
boolean bol = dialog.getOpacity() < 0.55f;
count += 1;
if (count < 10) {
if (bol) {
dialog.setOpacity(1.0f);
dialog.getContentPane().setBackground(Color.WHITE);
} else {
dialog.setOpacity(0.5f);
dialog.getContentPane().setBackground(Color.RED);
}
} else {
System.exit(0);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GenericForm();
}
});
}
}
public class ClickButtonClass implements ActionListener
{
public void actionPerformed(ActionEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
}
I did this code for counting clicks. But it only counts left mouse clicks. How do I add right mouse clicks too?
Use MouseListener. Here is an example:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JLabel label = new JLabel("click me");
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent me) {
if (SwingUtilities.isRightMouseButton(me)) {
System.out.println("right click");
} else {
System.out.println("left click");
}
});
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
Don't use an ActionListener.
Instead you should be using a MouseListener. Read the section from the Swing tutorial on How to Write a MouseListener for more information and examples.
To count rightclicks:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Demo extends Frame {
Integer counter=0;
Button btn;
Label label;
public Demo() {
setLayout(new FlowLayout());
btn = new Button("OK");
label= new Label("Number of rightclicks: "+counter);
btn.addMouseListener(new MouseAdapter(){
public void mouseClicked (MouseEvent e) {
if (e.getModifiers() == MouseEvent.BUTTON3_MASK) {
counter++;
label.setText("Number of rightclicks: " +counter.toString());} }
});
add(btn);
add(label);
setSize(300,300);
setVisible(true);
}
public static void main(String args[]) {
new Demo();
}
}