I am making my first game, and the last time I asked this question, I kinda didn't explain it very well. Basically, below is the opening screen of the game. I know, not very good, but it is just a rough draft. Then I also built the game.
There are two buttons in the opening screen, for it is a 2 player game. Both players must click ready, and then I want to program to end, and to start the second program. However I'm not sure how to do that.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class OpeningScreen {
JFrame frame;
JPanel main;
JButton ready1;
JButton ready2;
JPanel bottom;
JLabel label;
public OpeningScreen(){
UIManager.put("Button.background", Color.cyan);
UIManager.put("Button.foreground", Color.magenta);
UIManager.put("ToolTip.background", Color.magenta);
frame=new JFrame("Super Tuesday");
main=new JPanel();
ready1=new JButton("CLICK IF READY");
ready2=new JButton("CLICK IF READY");
label=new JLabel("SUPER TUESDAY");
bottom=new JPanel();
label.setFont(label.getFont().deriveFont(50.0f));
frame.setSize(480, 800);
frame.setLayout(new BorderLayout());
frame.add(main, BorderLayout.CENTER);
bottom.setLayout(new BorderLayout());
ready1.setToolTipText("CLICK ME TO START THE GAME");
ready2.setToolTipText("CLICK ME TO START THE GAME");
main.setBackground(Color.gray);
label.setForeground(Color.white);
ready1.setFont(ready1.getFont().deriveFont(20.0f));
ready2.setFont(ready2.getFont().deriveFont(20.0f));
ready1.setForeground(Color.pink);
ready2.setForeground(Color.pink);
ready1.setPreferredSize(new Dimension(240,150 ));
ready2.setPreferredSize(new Dimension(240, 150));
bottom.setPreferredSize(new Dimension(600, 150));
main.setLayout(new FlowLayout());
main.add(label, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
bottom.add(ready1, BorderLayout.WEST);
bottom.add(ready2, BorderLayout.EAST);
MyMouseManager1 mmm1=new MyMouseManager1();
MyMouseManager2 mmm2=new MyMouseManager2();
ready1.addMouseListener(mmm1);
ready2.addMouseListener(mmm2);
frame.setVisible(true);
}
class MyMouseManager1 implements MouseListener{
public void mouseClicked(MouseEvent e) {
ready1.setBackground(Color.green);
ready1.setForeground(Color.white);
ready1.setText("READY!");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
class MyMouseManager2 implements MouseListener{
public void mouseClicked(MouseEvent e) {
ready2.setBackground(Color.green);
ready2.setForeground(Color.white);
ready2.setText("READY!");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
public static void main(String[] args){
OpeningScreen smartie=new OpeningScreen();
}
}
Here is the second program. Please don't copy. heh.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.applet.Applet;
public class Clickasfastasyoucan extends java.applet.Applet{
private JFrame w;
private JPanel b;
private Button p;
private JPanel d;
private int times;
private JLabel number;
JPanel n;
JFrame x;
public Clickasfastasyoucan() {
x=new JFrame(" ");
n=new JPanel();
times=0;
number=new JLabel("How fast can you click?");
w = new JFrame("My Smart Button");
w.setSize(1500, 1000);
b = new JPanel();
p = new Button("Swipe as fast as you can");
w.setSize(500, 500);
b.setPreferredSize(new Dimension(1000,1500));
d=new JPanel();
w.add(b);
b.add(p);
b.setLayout(new GridLayout(1, 1));
b.add(number, BorderLayout.CENTER);
d.setSize(500, 500);
MyMouseManager mmm = new MyMouseManager();
p.addMouseListener(mmm);
p.addMouseMotionListener(mmm);
p.setForeground(Color.white);
p.setBackground(Color.black);
p.setFont(p.getFont().deriveFont(20.0f));
p.setFont(p.getFont().deriveFont(20.0f));
b.setSize(600, 600);
w.setVisible(true);
}
class MyMouseManager implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
n.setBackground(Color.blue);
x.add(n);
x.setSize(500, 500);
n.setSize(500, 500);
x.setVisible(true);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
n.setBackground(Color.blue);
}
public void mouseExited(MouseEvent e) {
n.setBackground(Color.white);
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {times++;
number.setFont(number.getFont().deriveFont(100.0f));
number.setText(" "+times+" ");
if (times>=100&×<999){
b.setBackground(Color.red);
number.setFont(number.getFont().deriveFont(80.0f));
times=times+1;
}
if(times>=1000&×<10000){
b.setBackground(Color.green);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+4;
}
if(times>=10000&×<50000){
b.setBackground(Color.yellow);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+100;
}if(times>=50000&×<500000){
b.setBackground(Color.blue);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+500;
}
if(times>=500000&×<4999999){
b.setBackground(Color.pink);
number.setFont(number.getFont().deriveFont(40.0f));
times=times+1000;
}
if(times>=5000000){
b.setBackground(Color.orange);
number.setFont(number.getFont().deriveFont(20.0f));
number.setText("WOW! YOU WON. CHECK THE OUTPUT TO SEE HOW YOU SCORED!");
System.out.println("1 day: Are you still there?");
System.out.println("24 hour: Snail speed");
System.out.println("15 hours: Fail");
System.out.println("5 hours: Slow Fingers");
System.out.println("1 hour: Fast Fingers");
System.out.println("30 minutes: Champion");
System.out.println("15 minutes: You beat me!");
System.out.println("2 minutes: Cheater");
System.out.println("1 minute: Speed of Light");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("___________________________-");
}
}
}
public static void main(String[] args) {
Clickasfastasyoucan clickgame= new Clickasfastasyoucan();
}
}
I want this one to replace the first program. I'm not sure how to even start with this though, since this is my first attempt at any game, or anything beyond a one class program.
No, you really don't want a java.awt.Applet to replace a JFrame, trust me. They're both used in two vastly different situations, and while the Swing library that underlies JFrames is about 4 years out of date, the AWT library that underlies java.awt.Applet is about 20 years out of date. Just stay clear of Applet.
Instead your GUI classes should be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding, and in fact this is what I recommend -- that you swap views via a CardLayout.
Also -- don't use MouseListeners for your JButton listeners but instead use ActionListeners. MouseListeners won't respond to space bar presses, won't be disabled if the button becomes disabled, and can be capricious if you base behavior on the mouseClicked method. Use the proper tool for the job: ActionListeners, or even better, Actions.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class MainGui extends JPanel {
private CardLayout cardLayout = new CardLayout();
private StartUpPanel startUpPanel = new StartUpPanel(this);
private GamePanel gamePanel = new GamePanel(this);
public MainGui() {
setLayout(cardLayout);
add(startUpPanel, startUpPanel.getName());
add(gamePanel, gamePanel.getName());
}
public void nextCard() {
cardLayout.next(this);
}
private static void createAndShowGui() {
MainGui mainPanel = new MainGui();
JFrame frame = new JFrame("MainGui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class StartUpPanel extends JPanel {
public static final String CLICK_IF_READY = "Click If Ready";
public static String SUPER_TUESDAY = "SUPER TUESDAY";
public static final String READY = "READY";
public static final int MAX_READY = 2;
private static final float TITLE_FONT_POINTS = 40f;
public static final String START_UP_PANEL = "Startup Panel";
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private int readyCount = 0;
private MainGui mainGui;
public StartUpPanel(MainGui mainGui) {
this.mainGui = mainGui;
setName(START_UP_PANEL);
JLabel titleLabel = new JLabel(SUPER_TUESDAY, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
JButton button1 = new JButton(new StartupAction());
JButton button2 = new JButton(new StartupAction());
button1.setFont(button1.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
button2.setFont(button1.getFont());
JPanel southPanel = new JPanel(new GridLayout(1, 0));
southPanel.add(button1);
southPanel.add(button2);
setLayout(new BorderLayout());
add(titleLabel, BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class StartupAction extends AbstractAction {
public StartupAction() {
super(CLICK_IF_READY);
}
#Override
public void actionPerformed(ActionEvent e) {
if (getValue(NAME).equals(CLICK_IF_READY)) { // check if button active
putValue(NAME, READY); // swap button's name
((AbstractButton) e.getSource()).setFocusable(false); // lose focus
readyCount++; // increment ready count.
if (readyCount >= MAX_READY) { // if all buttons pushed
mainGui.nextCard(); // tell main GUI to swap cards
}
}
}
}
}
// simple mock class to represent the game
class GamePanel extends JPanel {
public static final String GAME = "Game";
private static final float FONT_POINTS = 30F;
private MainGui mainGui;
public GamePanel(MainGui mainGui) {
this.mainGui = mainGui;
setName(GAME);
JLabel label = new JLabel(GAME, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, FONT_POINTS));
setLayout(new GridBagLayout());
add(label);
}
}
Related
I cannot get my Jframe to close when a user hits the (X) button. I tried many ways to do them but none of them work.
I tried:
JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Nothing happens. My main class extends jframe and implements action listener. What am I doing wrong?
My code:
package com.xflare.Bot;
import static java.lang.System.out;
import java.awt.*;
import java.lang.String;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame implements ActionListener{
private static Frame frame;
private static boolean debug = true;
private static boolean enabled = true;
private static JButton exitbutton; // reference to the button object
private static JButton webbutton; // reference to the button object
private static JButton aboutbutton; // reference to the button object
public static void main(String[] args) {
new Main().start();
}
private void start(){
//start up
printSystem("starting");
//create frame
printSystem("Creating a frame...");
createFrame();
//create button(s)
createQuitButton();
createWebButton();
createAboutButton();
//Spawn init.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getFrame().setResizable(false);
getFrame().setVisible(true);
printSystem("Started up successfully!");
}
private void createFrame(){
Main.frame = new Frame("app");
frame.setSize(600, 300);
}
private void createQuitButton(){
exitbutton = new JButton("Exit!");
getFrame().setLayout(null);
exitbutton.setBounds(225,45,150,75);//setBounds(x,y,width,height)
exitbutton.setActionCommand("exit");
exitbutton.addActionListener(this);
getFrame().add(exitbutton);
}
private void createWebButton(){
webbutton = new JButton("Open hacked browser");
getFrame().setLayout(null);
webbutton.setBounds(225,130,150,75);//setBounds(x,y,width,height)
webbutton.setActionCommand("web");
webbutton.addActionListener(this);
getFrame().add(webbutton);
}
private void createAboutButton(){
aboutbutton = new JButton("About");
getFrame().setLayout(null);
aboutbutton.setBounds(225,215,150,75);//setBounds(x,y,width,height)
aboutbutton.setActionCommand("about");
aboutbutton.addActionListener(this);
getFrame().add(aboutbutton);
}
private Frame getFrame(){
return Main.frame;
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
printDebug("Button " + actionCommand + " was pressed.");
if(actionCommand.equals("exit")){
exitbutton.setVisible(false);
shutdown();
}
else if(actionCommand.equals("about")){
aboutbutton.setVisible(false);
webbutton.setVisible(false);
exitbutton.setVisible(false);
showAbout();
}
else{
printCritical("Unknown button pressed!");
}
}
private void showAbout(){
}
private void shutdown(){
printSystem("Attempting to shut down...");
enabled = false;
printSystem("Shut down successful!");
System.exit(0);
}
private boolean debugEnabled(){
return debug;
}
private String getVersion(){
return "1.0.0";
}
private String getCodename(){
return "[BeastReleased]";
}
private static void printSystem(String var){
out.println("System> " + var);
}
private static void printError(String var){
out.println("Error> " + var);
}
private static void printCritical(String var){
out.println("Critical> " + var);
}
private void printDebug(String var){
if(debugEnabled()) {
out.println("Debug> " + var);
}
}
}
Link to same code: http://pastebin.com/1fDbjm74
This: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
needs to be called on the JFrame that you're actually displaying, Main.frame. You're not doing this.
getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getFrame().setVisible(true);
You've got too many Frame / JFrames. Your class extends JFrame but you're not displaying it. You've also got a Frame variable called frame, (NOT a JFrame variable) that you are displaying, and of course since this is not a JFrame, you can't make JFrame method calls, like the one above on it.
Simplify: create ONE JFrame not a Frame, and call this method on it and set it visible. So either get rid of the frame variable and use the class itself, the this, as your JFrame, and display it, or don't have your class extend JFrame and use your frame variable, but make it a JFrame object not a Frame object, since Frame does not have the setDefaultCloseOperation(...) method.
Also you're over-using static modifiers where they shouldn't be used. All your fields should be instance (non-static) fields.
Also, use of null layouts and setBounds will bite you in the end. For instance when I run your program, portions of the middle button's text are missing because its size has been artificially constrained in a bad way. Much better is to us layout managers to your advantage. For example:....
Please have a look at this program structure:
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MyMain extends JPanel {
public static final String MENU_PANEL = "MENU";
public static final String ABOUT_PANEL = "About";
private CardLayout cardLayout = new CardLayout();
public MyMain() {
JPanel aboutPanel = new JPanel(new GridBagLayout());
JLabel aboutLabel = new JLabel("About");
aboutLabel.setFont(aboutLabel.getFont().deriveFont(Font.BOLD, 32));
aboutPanel.add(aboutLabel);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 10, 10));
buttonPanel.add(createButton(new ExitAction("Exit!", KeyEvent.VK_X)));
buttonPanel.add(createButton(new OpenBrowserAction("Open Hacked Browser", KeyEvent.VK_O)));
buttonPanel.add(createButton(new AboutAction("About", KeyEvent.VK_A, this)));
JPanel menuPanel = new JPanel(new GridBagLayout());
int ebGap = 40;
menuPanel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
menuPanel.add(buttonPanel);
setLayout(cardLayout);
add(menuPanel, MENU_PANEL);
add(aboutPanel, ABOUT_PANEL);
}
private JButton createButton(Action action) {
JButton button = new JButton(action);
Font btnFont = button.getFont().deriveFont(Font.BOLD, 20);
button.setFont(btnFont);
return button;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("My Main Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
public void showPanel(String cardLayoutKey) {
cardLayout.show(this, cardLayoutKey);
}
}
class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
if (comp != null) {
Window win = SwingUtilities.getWindowAncestor(comp);
if (win != null) {
win.dispose();
}
}
}
}
class OpenBrowserAction extends AbstractAction {
public OpenBrowserAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Open Browswer");
}
}
class AboutAction extends AbstractAction {
private MyMain myMain;
public AboutAction(String name, int mnemonic, MyMain myMain) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
if (myMain != null) {
myMain.showPanel(MyMain.ABOUT_PANEL);
}
}
}
You are calling the setDefaultCloseOperation method on the wrong place. Here's what you should do:
private void start(){
//start up
printSystem("starting");
//create frame
printSystem("Creating a frame...");
createFrame();
//Spawn init.
getFrame().setResizable(false);
getFrame().setVisible(true);
printSystem("Started up successfully!");
}
private void createFrame(){
Main.frame = new Frame("app");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
}
I am building a Java Swing app, which I want it will work this way:
When you resize the window, the JScrollPane object (which is within a JSplitPane) should redimension its minimum, maximum and preferred size taking as reference the current window width.
I fixed this settings on the method componentResized() of ComponentAdapter class, however, it doesn't work as suppose must do.
This is the code. I wish you test it on your pc and can help me.
Thanks a lot for your time payed.
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
public class ComVisor extends JFrame
{
private JList imagesList;
private JPanel imagePanel;
private JSplitPane mainPanel;
private JScrollPane scrollPanelRight;
private int width;
public ComVisor(String nameApplication)
{
setFrame(nameApplication);
setComponents();
}
private void setFrame(String nameApplication)
{
setLayout(new BorderLayout(1, 3));
setTitle(nameApplication);
setMinimumSize(new Dimension(400, 200));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));
setLocationRelativeTo(null);
this.addWindowListener(
new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
JOptionPane.showMessageDialog(ComVisor.this, nameApplication + "-Salida");
return;
}
}
);
this.addComponentListener(
new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent E)
{
width = getWidth();
scrollPanelRight.setPreferredSize(new Dimension(width / 3, 0));
scrollPanelRight.setMinimumSize(new Dimension(width / 7, 0));
scrollPanelRight.setMaximumSize(new Dimension(width / 5 * 4, 0));
return;
}
}
);
}
private void setComponents()
{
String[] a = {"dsdsdsd", "dsdsdkkhskj", "dskhkjdhskjdhksdh", "sdskdhskjhds"};
JButton b = new JButton("Soy un boton xD");
JPanel p = new JPanel();
imagesList = new JList(a);
p.add(b);
imagesList.setVisibleRowCount(100);
scrollPanelRight = new JScrollPane(imagesList);
mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPanelRight, p);
add(mainPanel, BorderLayout.CENTER);
return;
}
private class Manejador implements ActionListener
{
#Override
public void actionPerformed(ActionEvent listener)
{
return;
}
}
}
and this is the main class, which calls a Comvisor object
import static javax.swing.SwingUtilities.invokeLater;
public class Principal
{
public static void main(String[] args)
{
invokeLater(
new Runnable()
{
#Override
public void run()
{
new ComVisor("ComVisor").setVisible(true);
return;
}
}
);
return;
}
}
I have two frames with contents . The first one has a jlabel and jbutton which when it is clicked it will open a new frame. I need to repaint the first frame or the panel that has the label by adding another jlabel to it when the second frame is closed.
//Edited
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FirstFrame extends JPanel implements KeyListener{
private static String command[];
private static JButton ok;
private static int count = 1;
private static JTextField text;
private static JLabel labels[];
private static JPanel p ;
private static JFrame frame;
public int getCount(){
return count;
}
public static void createWindow(){
JFrame createFrame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2,1));
text = new JTextField (30);
ok = new JButton ("Add");
ok.requestFocusInWindow();
ok.setFocusable(true);
panel.add(text);
panel.add(ok);
text.setFocusable(true);
text.addKeyListener(new FirstFrame());
createFrame.add(panel);
createFrame.setVisible(true);
createFrame.setSize(600,300);
createFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
createFrame.setLocationRelativeTo(null);
createFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.out.println(command[count]);
if(command[count] != null){
p.add(new JLabel("NEW LABEL"));
p.revalidate();
p.repaint();
count++;
System.out.println(count);
}
}
});
if(count >= command.length)
count = 1;
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(command[count] == null)
command[count] = text.getText();
else
command[count] = command[count]+", "+text.getText();
text.setText("");
}
});
}
public FirstFrame(){
p = new JPanel();
JButton create = new JButton ("CREATE");
command = new String[2];
labels = new JLabel[2];
addKeyListener(this);
create.setPreferredSize(new Dimension(200,100));
//setLayout(new BorderLayout());
p.add(new JLabel("dsafsaf"));
p.add(create);
add(p);
//JPanel mainPanel = new JPanel();
/*mainPanel.setFocusable(false);
mainPanel.add(create);
*/
create.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
createWindow();
}
});
//add(mainPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
frame = new JFrame();
frame.add(new FirstFrame());
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
if(ok.isDisplayable()){
ok.doClick();
return;}
}
}
}
});
}
}
As per my first comment, you're better off using a dialog of some type, and likely something as simple as a JOptionPane. For instance in the code below, I create a new JLabel with the text in a JTextField that's held by a JOptionPane, and then add it to the original GUI:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class FirstPanel2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private JTextField textField = new JTextField("Hovercraft rules!", 30);
private int count = 0;
public FirstPanel2() {
AddAction addAction = new AddAction();
textField.setAction(addAction);
add(textField);
add(new JButton(addAction));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class AddAction extends AbstractAction {
public AddAction() {
super("Add");
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
final JTextField someField = new JTextField(text, 10);
JPanel panel = new JPanel();
panel.add(someField);
int result = JOptionPane.showConfirmDialog(FirstPanel2.this, panel, "Add Label",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
JLabel label = new JLabel(someField.getText());
FirstPanel2.this.add(label);
FirstPanel2.this.revalidate();
FirstPanel2.this.repaint();
}
}
}
private static void createAndShowGui() {
FirstPanel2 mainPanel = new FirstPanel2();
JFrame frame = new JFrame("My Gui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Also, don't add KeyListeners to text components as that is a dangerous and unnecessary thing to do. Here you're much better off adding an ActionListener, or as in my code above, an Action, so that it will perform an action when the enter key is pressed.
Edit
You ask:
Just realized it is because of the KeyListener. Can you explain please the addAction ?
This is functionally similar to adding an ActionListener to a JTextField, so that when you press enter the actionPerformed(...) method will be called, exactly the same as if you pressed a JButton and activated its ActionListener or Action. An Action is like an "ActionListener" on steroids. It not only behaves as an ActionListener, but it can also give the button its text, its icon and other properties.
I have a JFrame which contains 2 JPanel subclass and 2 JLabel in BorderLayout. One of the JPanel contains JButtons and the other is used for displaying graphics. The JLabels are in north and south, the button JPanel in the west and the display JPanel in center.
The display JPanel requires constant refresh, so i invoke its repaint() method via the action event generated by swing timer. I also override its paintComponent() method to do my drawings.
Instead of displaying what i have drawn, the "content of the JFrame" is being drawn onto the display JPanel. I am aware that i can simply "clear" the display JPanel by using g.fillRect() or super.paintComponent() before doing my drawings.
I am just curious why this happens.
i'm using jdk 1.6u27. below is my code:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Main {
public static void main(String[] args) {
Simulation sim = new Simulation();
}
}
class Simulation extends JFrame {
public JLabel state;
private JLabel id;
private ButtonPanel control;
private Display display;
public Simulation() {
id = new JLabel("Test");
state = new JLabel("Test");
control = new ButtonPanel();
display = new Display(this);
this.setLayout(new BorderLayout());
this.add(id, BorderLayout.NORTH);
this.add(control, BorderLayout.WEST);
this.add(display, BorderLayout.CENTER);
this.add(state, BorderLayout.SOUTH);
this.setSize(500, 600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public ButtonPanel getControl() {
return this.control;
}
}
class ButtonPanel extends JPanel implements ActionListener {
public JButton b[] = new JButton[8];
public boolean bp[] = new boolean[8];
public ButtonPanel() {
this.setLayout(new GridLayout(8, 1));
for (int i = 0; i < b.length; i++) {
b[i] = new JButton(""+i);
b[i].addActionListener(this);
bp[i] = false;
this.add(b[i]);
}
}
public void actionPerformed(ActionEvent e) {
//do something
}
}
class Display extends JPanel implements ActionListener {
private Timer tm;
private int yco;
private Simulation sim;
public Display(Simulation sim) {
tm = new Timer(100, this);
tm.start();
yco = 0;
this.sim = sim;
}
#Override
public void paintComponent(Graphics g) {
//draw something
g.drawLine(0, yco, 100, 100);
}
public void actionPerformed(ActionEvent e) {
yco ++;
this.repaint();
}
}
Without super.paintComponent(g), the result depends on your platform's default for the opacity property of the JPanel UI delegate, PanelUI. Mine happens to be true, but you can experiment on your platform, as suggested below.
Addendum: "If you do not honor the opaque property you will likely see visual artifacts."—paintComponent(). The artifact you observe will vary by platform, but it is not atypical. In effect, you are breaking the promise to draw every pixel, and you see whatever is left over in some buffer.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Simulation sim = new Simulation();
}
});
}
}
class Simulation extends JFrame {
public JCheckBox state;
private JLabel id;
private ButtonPanel control;
private Display display;
public Simulation() {
id = new JLabel("Test");
state = new JCheckBox("Opaque");
control = new ButtonPanel();
display = new Display(this);
this.setLayout(new BorderLayout());
this.add(id, BorderLayout.NORTH);
this.add(control, BorderLayout.WEST);
this.add(display, BorderLayout.CENTER);
this.add(state, BorderLayout.SOUTH);
state.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
display.setOpaque(e.getStateChange() == ItemEvent.SELECTED);
}
});
state.setSelected(true);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public ButtonPanel getControl() {
return this.control;
}
}
class ButtonPanel extends JPanel {
private static final int N = 8;
private List<JToggleButton> list = new ArrayList<JToggleButton>(N);
public ButtonPanel() {
this.setLayout(new GridLayout(0, 1));
for (int i = 0; i < N; i++) {
final JToggleButton b = new JToggleButton(String.valueOf(i));
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println(b.isSelected());
}
});
list.add(b);
this.add(b);
}
}
}
class Display extends JPanel {
private Simulation sim;
private Timer tm;
private int yco;
public Display(Simulation sim) {
this.setPreferredSize(new Dimension(320, 320));
this.setOpaque(true);
this.sim = sim;
tm = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yco++;
repaint();
}
});
tm.start();
}
#Override
public void paintComponent(Graphics g) {
//super.paintComponent(g);
g.drawLine(0, yco, getWidth() / 2, getHeight() / 2);
}
}
I am writing a program for a black jack game. It is an assignment we are not to use gui's but I am doing it for extra credit I have created two frames ant they are working. On the second frame I want to be able to switch back to the first when a button is pressed. How do I do this?
first window.............
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow1 extends JFrame implements ActionListener
{
private JButton play = new JButton("Play");
private JButton exit = new JButton("Exit");
private JPanel pane=new JPanel();
private JLabel lbl ;
public BlackJackWindow1()
{
super();
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
play = new JButton("Start");
exit = new JButton("exit");
lbl = new JLabel ("Welcome to Theodores Black Jack!!!!!");
add (lbl) ;
add(play, BorderLayout.CENTER);
play.addActionListener (this);
add(exit,BorderLayout.CENTER);
exit.addActionListener (this);
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow2 bl = new BlackJackWindow2();
if (event.getSource() == play)
{
bl.BlackJackWindow2();
}
else if(event.getSource() == exit){
System.exit(0);
}
}
second window....
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow2 extends JFrame implements ActionListener
{
private JButton hit ;
private JButton stay ;
private JButton back;
//private JLabel lbl;
public void BlackJackWindow2()
{
// TODO Auto-generated method stub
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
hit = new JButton("Hit");
stay = new JButton("stay");
back = new JButton("return to main menu");
// add (lbl) ;
add(hit, BorderLayout.CENTER);
hit.addActionListener (this) ;
add(stay,BorderLayout.CENTER);
stay.addActionListener (this) ;
add(back,BorderLayout.CENTER);
back.addActionListener (this) ;
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow1 bl = new BlackJackWindow1();
if (event.getSource() == hit)
{
//code for the game goes here i will complete later
}
else if(event.getSource() == stay){
//code for game goes here i will comeplete later.
}
else
{
//this is where i want the frame to close and go back to the original.
}
}
}
The second frame needs a reference to the first frame so that it can set the focus back to the first frame.
Also your classes extend JFrame but they are also creating other frames in their constructors.
A couple of suggestions:
You're adding components to a JPanel that uses FlowLayout but are using BorderLayout constants when doing this which you shouldn't do as it doesn't make sense:
add(play, BorderLayout.CENTER);
Rather, if using FlowLayout, just add the components without those constants.
Also, rather than swap JFrames, you might want to consider using a CardLayout and swapping veiws in a single JFrame. For instance:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooBarBazDriver {
private static final String INTRO = "intro";
private static final String GAME = "game";
private CardLayout cardlayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardlayout);
private IntroPanel introPanel = new IntroPanel();
private GamePanel gamePanel = new GamePanel();
public FooBarBazDriver() {
mainPanel.add(introPanel.getMainComponent(), INTRO);
mainPanel.add(gamePanel.getMainComponent(), GAME);
introPanel.addBazBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, GAME);
}
});
gamePanel.addBackBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, INTRO);
}
});
}
private JComponent getMainComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Foo Bar Baz");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FooBarBazDriver().getMainComponent());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class IntroPanel {
private JPanel mainPanel = new JPanel();
private JButton baz = new JButton("Baz");
private JButton exit = new JButton("Exit");
public IntroPanel() {
mainPanel.setLayout(new FlowLayout());
baz = new JButton("Start");
exit = new JButton("exit");
mainPanel.add(new JLabel("Hello World"));
mainPanel.add(baz);
mainPanel.add(exit);
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
});
}
public void addBazBtnActionListener(ActionListener listener) {
baz.addActionListener(listener);
}
public JComponent getMainComponent() {
return mainPanel;
}
}
class GamePanel {
private static final Dimension MAIN_SIZE = new Dimension(400, 200);
private JPanel mainPanel = new JPanel();
private JButton foo;
private JButton bar;
private JButton back;
public GamePanel() {
foo = new JButton("Foo");
bar = new JButton("Bar");
back = new JButton("return to main menu");
mainPanel.add(foo);
mainPanel.add(bar);
mainPanel.add(back);
mainPanel.setPreferredSize(MAIN_SIZE);
}
public JComponent getMainComponent() {
return mainPanel;
}
public void addBackBtnActionListener(ActionListener listener) {
back.addActionListener(listener);
}
}
Since I had to test it myself if it is in fact so easy to implement, I built this simple example. It demonstrates a solution to your problem. Slightly inspired by #jzd's answer (+1 for that).
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class FocusChangeTwoFrames
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createGUI();
}
});
}
private static void createGUI() throws HeadlessException
{
final JFrame f2 = new JFrame();
f2.getContentPane().setBackground(Color.GREEN);
final JFrame f1 = new JFrame();
f1.getContentPane().setBackground(Color.RED);
f1.setSize(400, 300);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
if(f1.hasFocus())
f2.requestFocus();
else
f1.requestFocus();
}
};
f1.addMouseListener(ml);
f2.setSize(400, 300);
f2.setLocation(200, 150);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setVisible(true);
f2.addMouseListener(ml);
}
}
Enjoy, Boro.