I want to change the color of the background and a clear window without creating a new JFrame. Any suggestions?
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Dodge EM");
frame.setSize(1000, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
placeComponents(frame);
frame.setVisible(true);
frame.getContentPane().setBackground(Color.black);
}
private static void placeComponents(JFrame frame) {
frame.setLayout(null);
JLabel dodgeEM = new JLabel("Dodge EM");
dodgeEM.setForeground (Color.RED);
dodgeEM.setFont(new Font("Serif", Font.BOLD, 30));
dodgeEM.setBounds(440,10,300,150);
frame.add(dodgeEM);
JButton playButton = new JButton("Play");
playButton.setBounds(460,150,95,30);
frame.add(playButton);
ActionListener play = new Play();
playButton.addActionListener(play);
JButton scoresButton = new JButton("Scores");
scoresButton.setBounds(460,250,95,30);
frame.add(scoresButton);
JButton helpButton = new JButton("Help");
helpButton.setBounds(460,350,95,30);
frame.add(helpButton);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(460,450,95,30);
frame.add(quitButton);
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Play extends JFrame implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null, "Play button has been pressed");
this.getContentPane().setBackground(Color.red);
}
}
Any suggestions are much appreciated.
Rather then creating a new class, you can add the action listener to your button like shown below
playButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
//do stuff onclick
frame.getContentPane().setBackground(Color.yellow);
}
});
Related
I have 4 different classes of Code, but I had a problem with the main game part. Basically, as a cube you move around to get to a specific area, but for some reason using keybound labels it allows the label to leave the frame and basically disappear. Here's the code for the NewWindow class which essentially contains the window and key.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Desktop.Action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
public class NewWindow implements ActionListener{
JFrame frame;
JLabel label;
JButton quit = new JButton();
NewWindow.UpAction upAction;
NewWindow.LeftAction leftAction;
NewWindow.DownAction downAction;
NewWindow.RightAction rightAction;
NewWindow(){
JPanel level1 = new JPanel();
level1.setBackground(Color.CYAN);
level1.setBounds(810,410,75,75);
JPanel start = new JPanel();
start.setBackground(Color.CYAN);
start.setBounds(0,410,75,75);
Border border1 = BorderFactory.createLineBorder(Color.RED);
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(900,900);
frame.setLayout(null);
frame.getContentPane().setBackground(Color.BLACK); //c
frame.add(quit);
frame.setResizable(false);
label = new JLabel();
label.setBackground(Color.RED);
label.setBounds(0, 450, 25, 25);
label.setOpaque(true);
upAction = new UpAction();
downAction = new DownAction();
leftAction = new LeftAction();
rightAction = new RightAction();
label.getInputMap().put(KeyStroke.getKeyStroke('w'), "upAction");
label.getActionMap().put("upAction", upAction);
label.getInputMap().put(KeyStroke.getKeyStroke('s'), "downAction");
label.getActionMap().put("downAction", downAction);
label.getInputMap().put(KeyStroke.getKeyStroke('a'), "leftAction");
label.getActionMap().put("leftAction", leftAction);
label.getInputMap().put(KeyStroke.getKeyStroke('d'), "rightAction");
label.getActionMap().put("rightAction", rightAction);
quit.setBounds(0,0,100,40);
quit.setFocusable(false);
quit.setText("Quit");
quit.setFont(new Font("Comic Sans",Font.BOLD,25));
quit.setForeground(Color.RED);
quit.addActionListener(this);
quit.setBorder(border1);
quit.setBackground(Color.black);
ImageIcon image1 = new ImageIcon("3dCube.png");
frame.setVisible(true);
frame.add(label);
frame.add(start);
frame.setIconImage(image1.getImage());
frame.add(level1);
}
public class UpAction extends AbstractAction{
#Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX(), label.getY()-10);
}
}
public class LeftAction extends AbstractAction{
#Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX()-10, label.getY());
}
}
public class DownAction extends AbstractAction{
#Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX(), label.getY()+10);
}
}
public class RightAction extends AbstractAction{
#Override
public void actionPerformed(ActionEvent e) {
label.setLocation(label.getX()+10, label.getY());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==quit) {
frame.dispose();
Launch myWindow = new Launch();
}
}
}
I made a BoxLayout GUI and i'm wondering how i'd use an actionlistener to make the button close the window. If I try to put in RegisterNew.setVisible(false); in an actionlistener, it gives me an error
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RegisterNew extends JFrame
{
public RegisterNew(int axis){
// creates the JFrame
super("BoxLayout Demo");
Container con = getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(new JTextField());
con.add(new JLabel("Enter your password"));
con.add(new JTextField());
con.add(new JButton("Create Account"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[])
{
RegisterNew newDemo = new RegisterNew(BoxLayout.Y_AXIS);
}
}
I'm also trying to link this to ANOTHER GUI so that when you press a button, this one appears, but it gives me the same error as if i put
RegisterNew.setVisible(true); into the action listener
If that's a subordinate dialog window, then use a JDialog, not a JFrame.
If your ActionListener is an inner class then use RegisterNew.this.close();
Else you can get the window ancestor for the JButton using SwingUtilities.getWindowAncestor(button) and call close() or better dispose() on the Window returned.
Note that BoxLayout and layout managers in general have nothing to do with your current problem.
e.g.,
Test class that shows the new register dialog and that extracts information from it.
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestRegistration extends JPanel {
private JTextArea textArea = new JTextArea(30, 60);
public TestRegistration() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ShowRegisterNewAction()));
textArea.setFocusable(false);
textArea.setEditable(false);
setLayout(new BorderLayout());
add(new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
add(bottomPanel, BorderLayout.PAGE_END);
}
private class ShowRegisterNewAction extends AbstractAction {
private RegisterNew registerNew = null;
public ShowRegisterNewAction() {
super("Show Register New Dialog");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
if (registerNew == null) {
JButton btn = (JButton) e.getSource();
Window window = SwingUtilities.getWindowAncestor(btn);
registerNew = new RegisterNew(window, BoxLayout.PAGE_AXIS);
}
registerNew.setVisible(true);
String userName = registerNew.getUserName();
String password = new String(registerNew.getPassword());
textArea.append("User Name: " + userName + "\n");
textArea.append("Password: " + password + "\n");
textArea.append("\n");
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestRegistration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestRegistration());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
New Register class that holds the dialog and has code for displaying it and for extracting information from it. Uses BoxLayout.
import java.awt.Container;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class RegisterNew {
private JDialog dialog = null;
private JTextField nameField = new JTextField(10);
private JPasswordField passField = new JPasswordField(10);
public RegisterNew(Window window, int axis) {
dialog = new JDialog(window, "Register New", ModalityType.APPLICATION_MODAL);
Container con = dialog.getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(nameField);
con.add(new JLabel("Enter your password"));
con.add(passField);
con.add(new JButton(new AcceptAction()));
dialog.pack();
dialog.setLocationRelativeTo(window);
}
public char[] getPassword() {
return passField.getPassword();
}
public String getUserName() {
return nameField.getText();
}
public void setVisible(boolean b) {
dialog.setVisible(b);
}
private class AcceptAction extends AbstractAction {
public AcceptAction() {
super("Accept");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
}
}
I'm in a bit of a situation here.I'm making a new program, when you click on the menu bar it opens a new window for the Licence, now here is the problem, how would I add text into that new window, here is my code for the new window:
JFrame frame = new JFrame("Licence");
frame.setSize(500,120);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I know this is a easy question, I just can't think of the correct code for it.
You can try something like
JDialog dialog = new JDialog(your_frame_reference, "Licence");
dialog .setModal(true);
dialog .setLocationRelativeTo(null);
dialog. getContentPane().add(new JLabel(your_text);
dialog .setVisible(true);
You can use label
JFrame frame = new JFrame("Licence");
JLabel label = new JLabel("Text-Only Label");
label.setFont(new Font("Serif", Font.PLAIN, 36));
frame.add(label);
You can add text by creating JLabels like so:
JLabel label = new JLabel("Hello World");
This can then be added to your JFrame.
Try this Example
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestDialog {
protected static void initUI() {
JPanel pane = newPane("Label in frame");
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
public static JPanel newPane(String labelText) {
JPanel pane = new JPanel(new BorderLayout());
pane.add(newLabel(labelText));
pane.add(newButton("Open dialog"), BorderLayout.SOUTH);
return pane;
}
private static JButton newButton(String label) {
final JButton button = new JButton(label);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window parentWindow = SwingUtilities.windowForComponent(button);
JDialog dialog = new JDialog(parentWindow);
dialog.setLocationRelativeTo(button);
dialog.setModal(true);
dialog.add(newPane("Label in dialog"));
dialog.pack();
dialog.setVisible(true);
}
});
return button;
}
private static JLabel newLabel(String label) {
JLabel l = new JLabel(label);
l.setFont(l.getFont().deriveFont(24.0f));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
}
My question is similar to this one: JTable Cell Update doesn't work.
However, I am using JDialog instead of a JTable specified in above link. I have a custom class which extends JDialog. I use JEditorPane as a text-component in that dialog and create simple OK, Cancel buttons. Now the problem is, when I enter something in the JEdiorPane and presses OK button, the value is not applied to the text-component until I move the focus out of a JDialog or hit tab/ENTER.
I want the container to be notified that I am done with editing as soon as I press the OK button. In short I want to explicitly have a feature similar to stopCellEditing(). How can I do that?
See this example which seems to work correctly and does the same thing as you described:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class TestEditorPaneDialog {
public void init() {
final JFrame frame = new JFrame();
JButton clickMe = new JButton("Click me");
clickMe.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showDialog(frame);
}
});
frame.add(clickMe);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
showDialog(frame);
}
private void showDialog(final JFrame frame) {
final JDialog dialog = new JDialog(frame, true);
final JEditorPane pane = new JEditorPane();
pane.setText("Type something here");
JPanel south = new JPanel();
JPanel buttons = new JPanel(new GridLayout(1, 0, 10, 10));
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
JOptionPane.showMessageDialog(frame, "You have typed in: " + pane.getText());
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
buttons.add(ok);
buttons.add(cancel);
south.add(buttons);
dialog.add(new JScrollPane(pane));
dialog.add(south, BorderLayout.SOUTH);
dialog.setSize(250, 150);
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestEditorPaneDialog().init();
}
});
}
}
In the last question I was asking the community why my JPopupMenu did not appear on the screen.
I was unable to come up with a simple , runnable, compilable example.
So, here is what I did for you guys:
Is the area too small to draw a popup?
I want my popup to be like this:
The code of what I did is visible in the first photo.
Code:
/* The old code entered here has been removed */
Complete code can be found here
edit 2
I copied the various JRadioButtonMenuItem and the setupJPopup() into a new file and ran. It works. Why doesn't it work in ScreenRecorder class?
Code
package demo;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class PopupTrial {
public PopupTrial(){
setupJPopup();
JFrame frame = new JFrame();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
}
frame.getContentPane().add(label);
label.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
frame.setVisible(true);
frame.setSize(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new PopupTrial();
}
});
}
public void setupJPopup(){
encodingGroup.add(avi);
encodingGroup.add(quicktime);
popup.add(avi);
popup.add(quicktime);
popup.addSeparator();
recordingAreaGroup.add(entireScreen);
recordingAreaGroup.add(custom);
popup.add(entireScreen);
popup.add(custom);
popup.addSeparator();
cursorGroup.add(selectBlackCursor);
cursorGroup.add(selectWhiteCursor);
cursorGroup.add(selectNoCursor);
selectCursor.add(selectBlackCursor);
selectCursor.add(selectWhiteCursor);
selectCursor.add(selectNoCursor);
popup.add(selectCursor);
popup.pack();
}
JLabel label = new JLabel("Click Me");
ButtonGroup recordingAreaGroup = new ButtonGroup();
ButtonGroup cursorGroup = new ButtonGroup();
ButtonGroup encodingGroup = new ButtonGroup();
JPopupMenu popup = new JPopupMenu();
JRadioButtonMenuItem avi = new JRadioButtonMenuItem("AVI",true);
JRadioButtonMenuItem quicktime = new JRadioButtonMenuItem("QuickTime",false);
JRadioButtonMenuItem entireScreen = new JRadioButtonMenuItem("Entire Screen",true);
JRadioButtonMenuItem custom = new JRadioButtonMenuItem("Custom...",false);
JMenuItem selectCursor = new JMenu("Select a cursor");
JRadioButtonMenuItem selectWhiteCursor = new JRadioButtonMenuItem("White Cursor",true);
JRadioButtonMenuItem selectBlackCursor = new JRadioButtonMenuItem("Black Cursor",false);
JRadioButtonMenuItem selectNoCursor = new JRadioButtonMenuItem("No Cursor",false);
}
No, the size of the JFrame isn't related to why the PopupMenu isn't showing. Here's an example showing something similar to what you want (and using similar methods) working:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenu extends Box{
Dimension preferredSize = new Dimension(400,30);
public PopupMenu(){
super(BoxLayout.Y_AXIS);
final JPopupMenu menu = new JPopupMenu("Options");
for(int i = 1; i < 20; i++)
menu.add(new JMenuItem("Option" + i));
JLabel clickMe = new JLabel("ClickMe");
clickMe.setAlignmentX(RIGHT_ALIGNMENT);
clickMe.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
menu.show(e.getComponent(), e.getX(), e.getY());
}});
add(clickMe);
}
public Dimension getPreferredSize(){
return preferredSize;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PopupMenu());
frame.validate();
frame.pack();
frame.setVisible(true);
}
}