I'm trying to make a launcher. It works fine, except that when I press the 'Options' button it makes a little window in the corner. How do I prevent this?
The Launcher picture:
(source: gyazo.com)
And now with the option frame running:
(source: gyazo.com)
You can see the little window in the corner. It does not disappear when the Option frame does.
The Main File:
package ca.sidez.Launcher;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import ca.sidez.Main.Game;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class Main {
private Game ga;
public static int game = 0;
public static int isUpdate = 0;
public static int BigVersion = 00;
public static String Version = "04";
public static String Potenic_Version = "1.6a";
public static String DirtLife_Version = "0.1";
public static int lang = 0;
private static void createWindow() {
Font font;
Font font2;
final JFrame frame = new JFrame("Nic Launcher " + Version);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(820, 640);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setResizable(false);
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
font = new Font("Times New Roman", Font.PLAIN, 28);
font2 = new Font("Arial", Font.BOLD, 14);
jep.setContentType("text/html");
jep.setText("<html> Loading... </html>");
jep.setBorder(new EmptyBorder(0, 0, 0, 0));
try {
jep.setPage("http://potenic.tumblr.com/");
} catch(IOException e) {
jep.setContentType("text/html");
jep.setText("<html>Could not load, Check Your Connection</html>");
}
JScrollPane scrollPane = new JScrollPane(jep);
scrollPane.setBackground(Color.BLACK);
scrollPane.setSize(640, 480);
scrollPane.setLocation(0, 0);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
final JRadioButton potenic = new JRadioButton("Potenic: " + Potenic_Version);
final JRadioButton Launcher = new JRadioButton("Launcher");
potenic.setBounds(675, 150, 200, 55);
Launcher.setBounds(675, 100, 200, 55);
ButtonGroup bg = new ButtonGroup();
bg.add(potenic);
bg.add(Launcher);
Launcher.setVisible(false);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(potenic.isSelected()) {
game = 1;
Launcher.setVisible(true);
} else {
game = 0;
Launcher.setVisible(false);
}
}
};
potenic.addActionListener(al);
Launcher.addActionListener(al);
//Enslish
if(lang == 0) {
a JButton launchButton = new JButton("Play");
launchButton.setBounds(50, 530, 150, 55);
launchButton.setFont(font);
launchButton.setVisible(true);
launchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(game == 1) {
Game.main(null);
frame.dispose();
}
}
});
frame.add(launchButton);
if(isUpdate == 0) {
JButton updateButton = new JButton("Check Update");
updateButton.setBounds(250, 530, 250, 55);
updateButton.setFont(font);
updateButton.setVisible(true);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CheckUpdate frame2 = new CheckUpdate();
frame2.setVisible(true);
frame.dispose();
}
});
frame.add(updateButton);
}
else if(isUpdate == 1) {
JButton updateButton = new JButton("Update");
updateButton.setBounds(250, 530, 150, 55);
updateButton.setFont(font);
updateButton.setVisible(true);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Downloader frame2 = new Downloader();
frame2.setVisible(true);
frame.dispose();
}
});
frame.add(updateButton);
}
JButton OptionsButton = new JButton("Options");
OptionsButton.setBounds(550, 530, 150, 55);
OptionsButton.setFont(font);
OptionsButton.setVisible(true);
OptionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(game == 1) {
PotenicOptions frame4 = new PotenicOptions();
frame4.setVisible(true);
frame.dispose();
}
if(game == 0) {
Working frame3 = new Working();
frame3.setVisible(true);
frame.dispose();
}
}
});
frame.add(OptionsButton);
}
//Svenska
if(lang == 1) {
JButton launchButton = new JButton("Spela");
launchButton.setBounds(30, 530, 150, 55);
launchButton.setFont(font);
launchButton.setVisible(true);
launchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(game == 1) {
Game.main(null);
frame.dispose();
}
}
});
frame.add(launchButton);
if(isUpdate == 0) {
JButton updateButton = new JButton("Titta Efter Uppdateringar");
updateButton.setBounds(215, 530, 350, 55);
updateButton.setFont(font);
updateButton.setVisible(true);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CheckUpdate frame2 = new CheckUpdate();
frame2.setVisible(true);
frame.dispose();
}
});
frame.add(updateButton);
}
else if(isUpdate == 1) {
JButton updateButton = new JButton("Uppdatera");
updateButton.setBounds(250, 530, 150, 55);
updateButton.setFont(font);
updateButton.setVisible(true);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Downloader frame2 = new Downloader();
frame2.setVisible(true);
frame.dispose();
}
});
frame.add(updateButton);
}
JButton OptionsButton = new JButton("Inställningar");
OptionsButton.setBounds(600, 530, 200, 55);
OptionsButton.setFont(font);
OptionsButton.setVisible(true);
OptionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(game == 1) {
PotenicOptions frame4 = new PotenicOptions();
frame4.setVisible(true);
frame.dispose();
}
if(game == 0) {
LauncherOptions frame3 = new LauncherOptions();
frame3.setVisible(true);
frame.dispose();
}
}
});
frame.add(OptionsButton);
}
//Suomi
if(lang == 2) {
JButton launchButton = new JButton("Pelaa");
launchButton.setBounds(50, 530, 150, 55);
launchButton.setFont(font);
launchButton.setVisible(true);
launchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(game == 1) {
Game.main(null);
frame.dispose();
}
}
});
frame.add(launchButton);
if(isUpdate == 0) {
JButton updateButton = new JButton("Tarkista päivitys");
updateButton.setBounds(250, 530, 250, 55);
updateButton.setFont(font);
updateButton.setVisible(true);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CheckUpdate frame2 = new CheckUpdate();
frame2.setVisible(true);
frame.dispose();
}
});
frame.add(updateButton);
}
else if(isUpdate == 1) {
JButton updateButton = new JButton("päivittää");
updateButton.setBounds(250, 530, 150, 55);
updateButton.setFont(font);
updateButton.setVisible(true);
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Downloader frame2 = new Downloader();
frame2.setVisible(true);
frame.dispose();
}
});
frame.add(updateButton);
}
JButton OptionsButton = new JButton("Asetukset");
OptionsButton.setBounds(550, 530, 150, 55);
OptionsButton.setFont(font);
OptionsButton.setVisible(true);
OptionsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(game == 1) {
PotenicOptions frame4 = new PotenicOptions();
frame4.setVisible(true);
frame.dispose();
}
if(game == 0) {
LauncherOptions frame3 = new LauncherOptions();
frame3.setVisible(true);
frame.dispose();
}
}
});
frame.add(OptionsButton);
}
frame.add(scrollPane);
frame.add(potenic);
frame.add(Launcher);
frame.setVisible(true);
}
public static void main(String[] args) {
new LoadLang();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createWindow();
}
});
}
}
The Option Code:
package ca.sidez.Launcher;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import ca.sidez.Main.Game;
import ca.sidez.Main.GamePanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class Working extends JFrame {
private Game ga;
public static int game;
Font font;
Font font2;
public Working() {
final JFrame frame = new JFrame("Working In Progress");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setLocationRelativeTo(null);
frame.setLayout(new FlowLayout());
frame.setResizable(false);
font = new Font("Times New Roman", Font.PLAIN, 28);
font2 = new Font("Arial", Font.BOLD, 14);
JLabel working = new JLabel("Working In Progress");
frame.add(working);
//English
if(Main.lang == 0) {
JButton launchButton = new JButton("Back");
launchButton.setBounds(50, 300, 150, 55);
launchButton.setFont(font);
launchButton.setVisible(true);
launchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
frame.add(launchButton);
}
//Svenska
if(Main.lang == 1) {
JButton launchButton = new JButton("Gå Tillbaks");
launchButton.setBounds(50, 300, 150, 55);
launchButton.setFont(font);
launchButton.setVisible(true);
launchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
frame.add(launchButton);
}
//Suomi
if(Main.lang == 2) {
JButton launchButton = new JButton("Takaisin");
launchButton.setBounds(50, 300, 150, 55);
launchButton.setFont(font);
launchButton.setVisible(true);
launchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
frame.add(launchButton);
}
frame.setVisible(true);
}
}
In your OptionsButton.addActionListener (pretty bad name for a variable, should not start with a capital letter), you create a Working object that IS a JFrame, and it's showed up.
But, in your Working class (realy bad name), that extends JFrame you work and show a final JFrame frame attribute.
That's why there is two windows (JFrame) showing up.
Delete that final JFrame frame in Working, and just use this !
Related
I'm actually codding a keypad for an application and I'm encountering a problem. I'm using some empty space in the JDialog I'm creating to place an exist button on the top right corner of the Dialog box. This empty space is creating a border to the dialog box which is unpleasant to see. So I've tried to make panels transparent with setOpaque(false) function, but I achieved nothing. Do I have to use the paint function (which I don't know how to use) ?
Here is my test function without the setOpaque tests I've done :
package test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Test {
public static JFrame frame;
public static void main(String args[]){
frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(400, 400);
panel.setBackground(Color.CYAN);
panel.setLayout(new GridBagLayout());
JTextField text = new JTextField("coucou");
panel.add(text);
text.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
text.setText("");
openKeypad(text);
}
});
frame.setContentPane(panel);
frame.setSize(400, 400);
frame.setUndecorated(true);
frame.setLocation(50,0);
frame.setVisible(true);
}
private static void openKeypad(JTextField text) {
KeyPad pad = new KeyPad(frame, text);
}
}
KeyPad class :
package test;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class KeyPad extends JDialog {
private JTextField field;
public KeyPad(JFrame parent, JTextField field_) {
super(parent, true);
//Initializing field
field = field_;
//Setting layout
JPanel panelButton = new JPanel();
panelButton.setLayout(new GridLayout(4, 3));
//Buttons declaration
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bp = new JButton(".");
JButton del = new JButton();
JButton close = new JButton();
//Setting buttons icons
try {
Image img = ImageIO.read(new File("ressources/closeIcon.png"));
close.setIcon(new ImageIcon(img));
img = ImageIO.read(new File("ressources/deleteIcon.png"));
del.setIcon(new ImageIcon(img));
close.setOpaque(false);
close.setBorder(new EmptyBorder(0, 0, 0, 0));
close.setContentAreaFilled(false);
}catch (Exception e) {
System.out.println(e);
}
//Buttons sizing
b0.setPreferredSize(new Dimension(64, 64));
b1.setPreferredSize(new Dimension(64, 64));
b2.setPreferredSize(new Dimension(64, 64));
b3.setPreferredSize(new Dimension(64, 64));
b4.setPreferredSize(new Dimension(64, 64));
b5.setPreferredSize(new Dimension(64, 64));
b6.setPreferredSize(new Dimension(64, 64));
b7.setPreferredSize(new Dimension(64, 64));
b8.setPreferredSize(new Dimension(64, 64));
b9.setPreferredSize(new Dimension(64, 64));
bp.setPreferredSize(new Dimension(64, 64));
del.setPreferredSize(new Dimension(64, 64));
close.setPreferredSize(new Dimension(32, 32));
//Adding buttons to the panelButton
panelButton.add(b7);
panelButton.add(b8);
panelButton.add(b9);
panelButton.add(b4);
panelButton.add(b5);
panelButton.add(b6);
panelButton.add(b1);
panelButton.add(b2);
panelButton.add(b3);
panelButton.add(bp);
panelButton.add(b0);
panelButton.add(del);
//Adding Listeners
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('0');
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('1');
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('2');
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('3');
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('4');
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('5');
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('6');
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('7');
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('8');
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('9');
}
});
bp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('.');
}
});
del.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delDigit();
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
//Placing close button
JPanel panelClose = new JPanel();
panelClose.setLayout(new BoxLayout(panelClose, BoxLayout.X_AXIS));
panelClose.add(Box.createRigidArea(new Dimension(64*3, 1)));
panelClose.add(close);
JPanel test = new JPanel();
test.setLayout(new BoxLayout(test, BoxLayout.X_AXIS));
test.add(panelButton);
test.add(Box.createRigidArea(new Dimension(32, 1)));
//Setting main panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panelClose);
panel.add(test);
//Setting and displaying the Dialog Box
this.setContentPane(panel);
this.setUndecorated(true);
this.pack();
this.setVisible(true);
}
private void addDigit(char i) {
field.setText(field.getText() + i);
}
private void delDigit() {
if(field.getText().length() > 0) {
field.setText(field.getText().substring(0, field.getText().length() - 1));
}
}
private void disposeDialog() {
this.dispose();
}
}
/////EDIT///////
Here is my keypad code at the moment if someone wants to use it, feel free.
package mainPackage;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class KeyPad extends JDialog {
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private GraphicsDevice[] gs = ge.getScreenDevices();
private JTextField field;
public KeyPad(JDialog parent, JTextField field_, String placement) {
super(parent, true);
//Initializing field
field = field_;
//Setting layout
JPanel panelButton = new JPanel();
panelButton.setLayout(new GridLayout(4, 3));
//Buttons declaration
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bp = new JButton(".");
JButton del = new JButton();
JButton close = new JButton();
//Setting buttons icons
try {
Image img = ImageIO.read(new File("ressources/closeIcon.png"));
close.setIcon(new ImageIcon(img));
img = ImageIO.read(new File("ressources/deleteIcon.png"));
del.setIcon(new ImageIcon(img));
close.setOpaque(false);
close.setBorder(new EmptyBorder(0, 0, 0, 0));
close.setContentAreaFilled(false);
}catch (Exception e) {
System.out.println(e);
}
//Buttons sizing
b0.setPreferredSize(new Dimension(64, 64));
b1.setPreferredSize(new Dimension(64, 64));
b2.setPreferredSize(new Dimension(64, 64));
b3.setPreferredSize(new Dimension(64, 64));
b4.setPreferredSize(new Dimension(64, 64));
b5.setPreferredSize(new Dimension(64, 64));
b6.setPreferredSize(new Dimension(64, 64));
b7.setPreferredSize(new Dimension(64, 64));
b8.setPreferredSize(new Dimension(64, 64));
b9.setPreferredSize(new Dimension(64, 64));
bp.setPreferredSize(new Dimension(64, 64));
del.setPreferredSize(new Dimension(64, 64));
close.setPreferredSize(new Dimension(32, 32));
//Adding buttons to the panelButton
panelButton.add(b7);
panelButton.add(b8);
panelButton.add(b9);
panelButton.add(b4);
panelButton.add(b5);
panelButton.add(b6);
panelButton.add(b1);
panelButton.add(b2);
panelButton.add(b3);
panelButton.add(bp);
panelButton.add(b0);
panelButton.add(del);
panelButton.setOpaque(false);
//Adding Listeners
b0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('0');
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('1');
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('2');
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('3');
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('4');
}
});
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('5');
}
});
b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('6');
}
});
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('7');
}
});
b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('8');
}
});
b9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('9');
}
});
bp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDigit('.');
}
});
del.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
delDigit();
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
//Placing close button
JPanel panelClose = new JPanel();
panelClose.setLayout(new BoxLayout(panelClose, BoxLayout.X_AXIS));
panelClose.add(Box.createRigidArea(new Dimension(64*3, 1)));
panelClose.add(close);
panelClose.setOpaque(false);
JPanel panelButtonWithPadding = new JPanel();
panelButtonWithPadding.setLayout(new BoxLayout(panelButtonWithPadding, BoxLayout.X_AXIS));
panelButtonWithPadding.add(panelButton);
panelButtonWithPadding.add(Box.createRigidArea(new Dimension(32, 1)));
panelButtonWithPadding.setOpaque(false);
//Setting main panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(panelClose);
panel.add(panelButtonWithPadding);
panel.setOpaque(false);
//Setting dialog box transparency
panelButton.setOpaque(false);
panelClose.setOpaque(false);
panelButtonWithPadding.setOpaque(false);
panel.setOpaque(false);
//Setting and displaying the Dialog Box
this.setContentPane(panel);
this.setUndecorated(true);
this.setBackground( new Color(0, 0, 0, 0) ); // set transparency on JDialog only
this.pack();
//To place the KeyPad anywhere on the panel
switch(placement) {
case "BOTTOM_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, 600 - (int) this.getSize().getHeight());
break;
case "BOTTOM_CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2) , 600 - (int) this.getSize().getHeight());
break;
case "BOTTOM_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), 600 - (int) this.getSize().getHeight());
break;
case "CENTER_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, (int) (600 - this.getSize().getHeight())/2);
break;
case "CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2), (int) (600 - this.getSize().getHeight())/2);
break;
case "CENTER_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), (int) (600 - this.getSize().getHeight())/2);
break;
case "TOP_LEFT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x, 0);
break;
case "TOP_CENTER":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) ((800 - this.getSize().getWidth())/2), 0);
break;
case "TOP_RIGHT":
this.setLocation(gs[Main.screen].getDefaultConfiguration().getBounds().x + (int) (800 - this.getSize().getWidth()), 0);
break;
}
this.setVisible(true);
}
private void addDigit(char i) {
field.setText(field.getText() + i);
}
private void delDigit() {
if(field.getText().length() > 0) {
field.setText(field.getText().substring(0, field.getText().length() - 1));
}
}
private void disposeDialog() {
this.dispose();
}
}
Simple example for making a JFrame transparent:
import java.awt.*;
import static java.awt.GraphicsDevice.WindowTranslucency.TRANSLUCENT;
import javax.swing.*;
class TransparentFrame extends JFrame
{
public TransparentFrame()
{
JPanel panel = new JPanel();
panel.setOpaque( false );
panel.add( new JButton("Button") );
add(panel, BorderLayout.SOUTH);
setUndecorated(true);
setSize(300, 300);
//pack();
// setOpacity(0.5f); // set transparency on frame and components
setBackground( new Color(0, 0, 0, 64) ); // set transparency on frame only
setTitle("Transparent Frame Demo");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String args[])
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Exit when translucent windows aren't supported
if (!gd.isWindowTranslucencySupported(TRANSLUCENT))
{
System.err.println( "Translucency is not supported" );
System.exit(0);
}
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(() -> new TransparentFrame().setVisible(true));
}
}
I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.
import java.awt.EventQueue;
public class ExpenseManager {
private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExpenseManager window = new ExpenseManager();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExpenseManager() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
//#SuppressWarnings("unchecked")
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewUser = new JButton("New User");
btnNewUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewUserName.setVisible(true);
txtUserName.setVisible(true);
btnDone.setVisible(true);
}
});
btnNewUser.setBounds(23, 34, 89, 23);
frame.getContentPane().add(btnNewUser);
txtUserName = new JTextField();
txtUserName.setBounds(240, 63, 134, 20);
frame.getContentPane().add(txtUserName);
txtUserName.setVisible(false);
txtUserName.setColumns(10);
lblNewUserName = new JLabel("Enter New UserName");
lblNewUserName.setBounds(240, 38, 134, 14);
lblNewUserName.setVisible(false);
frame.getContentPane().add(lblNewUserName);
btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newUserName = txtUserName.getText();
if(!newUserName.isEmpty())
{
File f = new File("S:/Expense/" + newUserName);
if (f.exists() && f.isDirectory()) {
JOptionPane.showMessageDialog(null, "User already exists");
txtUserName.setText(null);
}
else{
boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
if(!success){
JOptionPane.showMessageDialog(null, "Unable to register");
}else{
JOptionPane.showMessageDialog(null, "User registered Successfully");
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
}
}
});
btnDone.setBounds(240, 103, 89, 23);
btnDone.setVisible(false);
frame.getContentPane().add(btnDone);
btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File[] directories = new File("S:/Expense/").listFiles();
for(int i = 0; i < directories.length; i++)
{
dir[i] = directories[i].getName();
}
comboBox.setVisible(true);
}
});
btnLogin.setBounds(23, 68, 89, 23);
frame.getContentPane().add(btnLogin);
comboBox = new JComboBox<Object>(dir);
comboBox.setBounds(24, 138, 72, 20);
comboBox.setSelectedIndex(1);
comboBox.setVisible(false);
frame.getContentPane().add(comboBox);
}
}
You can use setModel with DefaultComboBoxModel which take an array instead like :
comboBox.setModel(new DefaultComboBoxModel(dir));
Most of the code posted is not relevant to the question asked, so it should be removed (see MCVE).
Review the following, note the comments:
public class ExpenseManager {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ExpenseManager();
} catch (Exception e) { e.printStackTrace(); }
}
});
}
public ExpenseManager() { initialize(); }
private void initialize() {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null); //better use a layout manger
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setBounds(24, 138, 72, 20);
comboBox.setVisible(false);
frame.getContentPane().add(comboBox);
JButton btn = new JButton("Populate combo");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//populate combo
String[] dir = new String[5];
for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}
comboBox.setModel(new DefaultComboBoxModel<>(dir));
comboBox.setVisible(true);
btn.setEnabled(false); //disable button
}
});
btn.setBounds(23, 68, 89, 23);
frame.getContentPane().add(btn);
frame.setVisible(true);
}
}
EDIT implementation using a layout manager :
private void initialize() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setVisible(false);
frame.add(comboBox, BorderLayout.SOUTH); //using BorderLayout which is the default
JButton btn = new JButton("Populate combo");
btn.setPreferredSize(new Dimension(150,35));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//populate combo
String[] dir = new String[5];
for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}
comboBox.setModel(new DefaultComboBoxModel<>(dir));
comboBox.setVisible(true);
btn.setEnabled(false); //disable button
frame.pack(); //resize fram to fit the preferred size and layouts
}
});
frame.getContentPane().add(btn, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
So my goal is to disable buttons on lets say panel B depending one what button they press on panel A. so below I have 2 combo boxes that id like to be able to enable or disable base on the buttons pressed on the first panel. Ive tried googling this problem but I'm new to java so its pretty rough going so far.
heres my sample code of what I'm trying to do.
package pack2;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
JComboBox comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
I needed to declare my comboBox's above my buttons then declare them as final.
here are the changes
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class tessst {
public boolean enableChk1;
public boolean enableChk2;
JComboBox comboBox;
JComboBox comboBox_1;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tessst window = new tessst();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tessst() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panel = new JPanel();
frame.getContentPane().add(panel, "name_15095567731094");
panel.setLayout(null);
final JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_15101078033315");
panel_1.setLayout(null);
JButton select2 = new JButton("2 boxes");
select2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
enableChk2 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
comboBox_1.setEnabled(true);
}
});
select2.setBounds(276, 101, 89, 23);
panel.add(select2);
JButton select1 = new JButton("1 boxes");
select1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = true;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(true);
}
});
select1.setBounds(59, 101, 89, 23);
panel.add(select1);
JButton select0 = new JButton("no boxes");
select0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
enableChk1 = false;
enableChk2 = false;
panel_1.revalidate();
frame.repaint();
panel_1.repaint();
frame.repaint();
panel.setVisible(false);
panel_1.setVisible(true);
comboBox.setEnabled(false);
comboBox_1.setEnabled(false);
}
});
select0.setBounds(166, 169, 89, 23);
panel.add(select0);
comboBox = new JComboBox();
comboBox.setEnabled(enableChk1);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox.setBounds(52, 100, 61, 20);
panel_1.add(comboBox);
comboBox_1 = new JComboBox();
comboBox_1.setEnabled(enableChk2);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
comboBox_1.setBounds(265, 100, 79, 20);
panel_1.add(comboBox_1);
JButton back = new JButton("go back");
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(true);
panel_1.setVisible(false);
}
});
back.setBounds(10, 227, 89, 23);
panel_1.add(back);
}
}
replace your code with this one. Its working Fine. Hope you are expecting this thing.
I have this program that should replace the label "MALE" or "FEMALE" depending on which the chooser selects, but when I tried to run it the "setText" wouldn't work.
`import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Hue implements ItemListener
{
JFrame frame= new JFrame("Demo");
Container content;
JPanel panel= new JPanel();
JLabel label = new JLabel("[LABEL]");
JCheckBox box= new JCheckBox("With Gender");
JRadioButton male= new JRadioButton("Male");
JRadioButton female= new JRadioButton("Female");
ButtonGroup bg = new ButtonGroup();
JTextField field = new JTextField(100);
public void launchFrame()
{
panel.add(label);
panel.add(box);
panel.add(male);
panel.add(female);
bg.add(male);
bg.add(female);
box.addItemListener(this);
male.addItemListener(this);
female.addItemListener(this);
panel.add(field);
panel.setLayout(null);
label.setBounds(5,0, 100, 20);
box.setBounds(10,15, 100, 20);
male.setBounds(20, 35, 100, 20);
female.setBounds(20, 55, 100, 20);
field.setBounds(15, 80, 250, 100);
field.setHorizontalAlignment(JTextField.LEFT);
male.setEnabled(false);
female.setEnabled(false);
field.setEnabled(false);
content= frame.getContentPane();
content.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e)
{
if (e.getItem() == box)
{
if (!box.isSelected())
{
male.setEnabled(false);
female.setEnabled(false);
field.setEnabled(false);
}
else if (box.isSelected())
{
male.setEnabled(true);
female.setEnabled(true);
field.setEnabled(true);
{
if (e.getItem() == male)
{
label.setText("Male");
}
else if (e.getItem() == female)
{
label.setText("Female");
}
}
}
}
}
public static void main(String args[])
{
Hue hw= new Hue();
hw.launchFrame();
}
}`
public void itemStateChanged(ItemEvent e)
{
if (e.getItem() == box)
{
if (!box.isSelected())
{
male.setEnabled(false);
female.setEnabled(false);
field.setEnabled(false);
}
else if (box.isSelected())
{
male.setEnabled(true);
female.setEnabled(true);
field.setEnabled(true);
}
}
else if (e.getItem() == male)
{
label.setText("Male");
}
else if (e.getItem() == female)
{
label.setText("Female");
}
}
according to your code if (e.getItem() == box) then never happen if (e.getItem() == male) or if (e.getItem() == female)
I am trying to create a hangman game with a button for each letter of the alphabet. I have done this the hard way, using absolute positioning and multiple actionlisteners. Is there any way I can do both with a for loop?
Also, how can I implement my hangman using a polymorphic array? The way I have it now, I will use an if statement for each of the limbs. I'd wrather create the man on his own panel, then set the visibility for each limg to true as the use fails at guessing.
Any help is appreciated.
public class HangmanGui extends JFrame{
private JLabel headerLabel;
private JPanel man;
private Graphics gobj;
private JButton aButton ;
private JButton bButton ;
private JButton cButton ;
private JButton dButton ;
private JButton eButton ;
private JButton fButton ;
private JButton gButton ;
private JButton hButton ;
private JButton iButton ;
private JButton jButton ;
private JButton kButton ;
private JButton lButton ;
private JButton mButton ;
private JButton nButton ;
private JButton oButton ;
private JButton pButton ;
private JButton qButton ;
private JButton rButton ;
private JButton sButton ;
private JButton tButton ;
private JButton uButton ;
private JButton vButton ;
private JButton wButton ;
private JButton xButton ;
private JButton yButton ;
private JButton zButton ;
private JButton newWButton ;
private JButton showWButton ;
private JButton quitButton ;
private JButton startButton ;
private JLabel blankWord;
private JLabel titleWord;
private JFrame frame;
private JPanel hangman;
private FlowLayout layout;
private Container container;
/*
public static void main (String[] args){
GUITest gui = new GUITest();
gui.setSize(800,900);
gui.setVisible(true);
}
*/
//
// public GUITest()
// {
// }
public HangmanGui(){
buildGui();
}
public void buildGui(){
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBackground(Color.WHITE);
frame.setBounds(100, 100, 450, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Font lblFont= new Font("Serif", Font.BOLD, 30);
JLabel[] uscore = new JLabel[15];
Man man = new Man();
titleWord = new JLabel("A Game of Hangman.");
titleWord.setBounds(260,10,500,150);
titleWord.setFont(lblFont);
add(titleWord);
// add(blankWord);
//frame.add(man);
this.add(man);
man.setBounds(100,100,400,400);
JPanel panel = new JPanel();
panel.setBounds(6, 232, 400, 400);
frame.getContentPane().add(panel);
layout = new FlowLayout();
container = getContentPane();
setLayout(null);
aButton = new JButton("A");
add(aButton);
aButton.setBounds(30, 520, 50, 29);
aButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
bButton = new JButton("B");
add(bButton);
bButton.setBounds(80, 520, 50, 29);
bButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
cButton = new JButton("C");
add(cButton);
cButton.setBounds(130, 520, 50, 29);
cButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
dButton = new JButton("D");
add(dButton);
dButton.setBounds(180, 520, 50, 29);
dButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
eButton = new JButton("E");
add(eButton);
eButton.setBounds(230, 520, 50, 29);
eButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
fButton = new JButton("F");
add(fButton);
fButton.setBounds(280, 520, 50, 29);
fButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
gButton = new JButton("G");
add(gButton);
gButton.setBounds(330, 520, 50, 29);
gButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
hButton = new JButton("H");
add(hButton);
hButton.setBounds(380, 520, 50, 29);
hButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
iButton = new JButton("I");
add(iButton);
iButton.setBounds(430, 520, 50, 29);
iButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
jButton = new JButton("J");
add(jButton);
jButton.setBounds(480, 520, 50, 29);
jButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
kButton = new JButton("K");
add(kButton);
kButton.setBounds(530, 520, 50, 29);
kButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
lButton = new JButton("L");
add(lButton);
lButton.setBounds(580, 520, 50, 29);
lButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
mButton = new JButton("M");
add(mButton);
mButton.setBounds(630, 520, 50, 29);
mButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
nButton = new JButton("N");
add(nButton);
nButton.setBounds(680, 520, 50, 29);
nButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
oButton = new JButton("O");
add(oButton);
oButton.setBounds(30, 550, 50, 29);
oButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
pButton = new JButton("P");
add(pButton);
pButton.setBounds(80, 550, 50, 29);
pButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
qButton = new JButton("Q");
add(qButton);
qButton.setBounds(130, 550, 50, 29);
qButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
rButton = new JButton("R");
add(rButton);
rButton.setBounds(180, 550, 50, 29);
rButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
sButton = new JButton("S");
add(sButton);
sButton.setBounds(230, 550, 50, 29);
sButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
tButton = new JButton("T");
add(tButton);
tButton.setBounds(280, 550, 50, 29);
tButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
uButton = new JButton("U");
add(uButton);
uButton.setBounds(330, 550, 50, 29);
uButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
vButton = new JButton("V");
add(vButton);
vButton.setBounds(380, 550, 50, 29);
vButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
wButton = new JButton("W");
add(wButton);
wButton.setBounds(430, 550, 50, 29);
wButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
xButton = new JButton("X");
add(xButton);
xButton.setBounds(480, 550, 50, 29);
xButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
yButton = new JButton("Y");
add(yButton);
yButton.setBounds(530, 550, 50, 29);
yButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
zButton = new JButton("Z");
add(zButton);
zButton.setBounds(580, 550, 50, 29);
zButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
startButton = new JButton("Start Game");
add(startButton);
startButton.setBounds(100, 700, 120, 29);
startButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
newWButton = new JButton("New Word");
add(newWButton);
newWButton.setBounds(250, 700, 120, 29);
newWButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
showWButton = new JButton("Show Word");
add(showWButton);
showWButton.setBounds(400, 700, 120, 29);
showWButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
quitButton = new JButton("Quit Game");
add(quitButton);
quitButton.setBounds(550, 700, 120, 29);
quitButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
}
}
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
public class Man extends JPanel {
protected void paintComponent(Graphics g ){
super.paintComponent(g);
//gallows
g.fillRect(10, 250, 150, 20);
g.fillRect(40,70,10,200);
g.fillRect(40,70,60,10);
g.setColor(Color.yellow);
g.fillRect(95,70,5,25);
//head
g.setColor(Color.black);
g.drawOval(82,95,30,30);
//body
g.drawLine(97,125,97,150);
//left leg
g.drawLine(97,150,117,183);
//right leg
g.drawLine(97,150,77,183);
// right arm
g.drawLine(97,125,117,135);
//left arm
g.drawLine(97,125,77,135);
}
}
Use a layout manager to manage the sizing of your buttons, don't use setBounds(). You currently create one but don't set it and so its not used.
layout = new FlowLayout();
setLayout(null); // Why set null and not layout
Set the layout correctly and then you could can use a char in your for loop like
for(char c = 'A'; c <= 'Z'; c++)
{
JButton button = new JButton("" + c);
// add action listener also
add(button); // adding will add it using the layout manager
}
You can learn more about layout managers here.
You could try something like this:
// create a JPanel to hold the buttons that uses a GridLayout with 3 rows
JPanel buttonPanel = new JPanel(new GridLayout(3, ));
for (int i = 0; i < 26; ++i)
{
wButton = new JButton('A' + i);
buttonPanel.add(wButton);
// wButton.setBounds(30 + i * 50, 550, 50, 29); // avoid this
wButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
}
// here add the buttonPanel to the main GUI
To break this down:
1) We use a for loop to go thru the 26 letters of the alphabet.
2) We create a button with the title being the letter. Because characters are actually just integers, adding 1 to 'A' yields 'B'. So, we can use 'A'+i as a little trick. Also, you could use an array of all the letters instead and do something like letter[i] there.
3) Avoid use of setBounds but rather use the layout managers to more easily and simply place and size the buttons.
Disclaimer: I haven't actually tested this, it's just something to get you on the right track.
Suggestions:
Yes, use an array or a collection such as either a simple array of JButton or a List<JButton> or its concrete implementation, an ArrayList<JButton>
Yes, create your letter JButtons in a for loop as many have suggested.
But don't create your special buttons there, buttons such as your reset button or your exit button.
Create one AbstractAction or ActionListener class for all the letter buttons to share and a unique AbstractAction or ActionListener class for each special JButton
Use layout managers, but not just one -- nest them. For instance, the overall GUI can use a BorderLayout with the drawing held BorderLayout.CENTER and the buttons in the SOUTH or PAGE_END position, the JPanels that hold your buttons could be held in a BoxLayout using JPanel, the letter buttons in a GridLayout using JPanel and the same for the specialty buttons.
Use a separate JPanel for drawing the hangman image. Keep its logic separate from everything else. All it cares about is the number of wrong letters guessed, and then it should draw the appropriate images depending on this value. So I'd give it a public method for incrementing this number as well as a public method for resetting the number and its drawing.
For instance
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class LayoutFoo extends JPanel {
// using a List of JButtons to hold my collection
private List<JButton> letterButtons = new ArrayList<>();
private DrawingPanel drawingPanel = new DrawingPanel();
public LayoutFoo() {
JPanel letterButtonPanel = new JPanel(new GridLayout(3, 0, 3, 3));
letterButtonPanel.setBorder(BorderFactory.createTitledBorder("Letters"));
ButtonListener buttonListener = new ButtonListener();
for (char c = 'A'; c <= 'Z'; c++) {
String text = String.valueOf(c);
JButton button = new JButton(text);
button.addActionListener(buttonListener);
letterButtons.add(button); // add JButton to List<JButton>
letterButtonPanel.add(button); // and add to GridLayout-using JPanel
}
// JPanel to hold non-letter JButtons
JPanel specialBtnsPanel = new JPanel(new GridLayout(1, 0, 3, 3));
specialBtnsPanel.add(new JButton(new ResetAction("Reset", KeyEvent.VK_R)));
specialBtnsPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
// JPanel to hold non-drawing JPanels. It uses BoxLayout
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
bottomPanel.add(letterButtonPanel);
bottomPanel.add(specialBtnsPanel);
// set layout and border of main JPanel and add other JPanels to it
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(drawingPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed: " + e.getActionCommand());
((AbstractButton) e.getSource()).setEnabled(false);
}
}
private class ResetAction extends AbstractAction {
public ResetAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
for (JButton button : letterButtons) {
button.setEnabled(true);
}
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
win.dispose();
}
}
private static void createAndShowGui() {
LayoutFoo mainPanel = new LayoutFoo();
JFrame frame = new JFrame("LayoutFoo");
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 DrawingPanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private int wrongLetterCount = 0;
public DrawingPanel() {
setBorder(BorderFactory.createTitledBorder("Hang Man"));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// TODO: draw hangman here based on wrong letter count!
}
public void incrementWrongLetterCount() {
wrongLetterCount++;
repaint();
}
public void reset() {
wrongLetterCount = 0;
repaint();
}
}