Resize JOptionPane Dialog and lines in a dialogs - java

My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}

Related

Why is my JSlider not changing the value?

I am trying to make my program so that an integer value entered in a JTextfield can be stored into a variable. Then, when a JButton is clicked, this variable can tell a JSlider to move it's head to that of the integer value stored in the variable. My class name is Camera.Java
Code is showing no errors, however if I click my JButton, nothing happens, instead I see this error in the console:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Camera.main(Camera.java:67)
My code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
public class Camera {
static JButton addtolist;
static Scanner input = new Scanner(System.in);
static JSlider cam = new JSlider();
static JTextField enterval = new JTextField();
static int x ;
public static void main (String args[]){
JFrame myFrame = new JFrame ("Matthew Damon on Mars");
myFrame.setSize(300, 600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel userinp = new JLabel("Enter input: ");
cam = new JSlider(0, 15, 0);
cam.setPaintLabels(true);
enterval.setPreferredSize(new Dimension(100,80));
addtolist = new JButton("Enter");
addtolist.setPreferredSize(new Dimension(50,20));
JTextField enterval1 = new JTextField();
panel.add(addtolist);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(0, new JLabel("0"));
table.put(1, new JLabel("1"));
table.put(2, new JLabel("2"));
table.put(3, new JLabel("3"));
table.put(4, new JLabel("4"));
table.put(5, new JLabel("5"));
table.put(6, new JLabel("6"));
table.put(7, new JLabel("7"));
table.put(8, new JLabel("8"));
table.put(9, new JLabel("9"));
table.put(10, new JLabel("A"));
table.put(11, new JLabel("B"));
table.put(12, new JLabel("C"));
table.put(13, new JLabel("D"));
table.put(14, new JLabel("E"));
table.put(15, new JLabel("F"));
cam.setLabelTable(table);
myFrame.add(cam, BorderLayout.SOUTH);
myFrame.add(userinp, BorderLayout.NORTH);
myFrame.add(enterval1, BorderLayout.NORTH);
myFrame.add(panel, BorderLayout.CENTER);
myFrame.setVisible(true);
buttonAction();
}
public static void buttonAction() {
addtolist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
});
}
}
Your setting x on program creation before the user has had any chance to change its value. Get the text value from within the actionPerformed method which should be after the user has already selected a value, parse it into a number and set the slider with that value.
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
Then get rid of all that static nonsense. The only method that should be static here is main, and it should do nothing but create an instance and set it visible.
Note that better than using a JTextField, use a JSpinner or a JFormattedTextField or if you're really stuck, a DocumentFilter to limit what the user can enter
Again, you should put most everything into the instance realm and out of the static realm. This means getting most of that code outside of the main method and into other methods and constructors, that means not trying to access fields or methods from the class, but rather from the instance. For instance, your main method should only create the main instances, hook them up and set them running and that's it. It should not be used to build the specific GUI components. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class CameraFoo extends JPanel {
// only static field here is a constant.
private static String TEXTS = "0123456789ABCDEF";
private JSpinner spinner = new JSpinner();
private JSlider slider = new JSlider(0, 15, 0);
public CameraFoo() {
List<Character> charList = new ArrayList<>();
Hashtable<Integer, JLabel> table = new Hashtable<>();
for (int i = 0; i < TEXTS.toCharArray().length; i++) {
char c = TEXTS.charAt(i);
String myText = String.valueOf(c);
JLabel label = new JLabel(myText);
table.put(i, label);
charList.add(c);
}
SpinnerListModel spinnerModel = new SpinnerListModel(charList);
spinner.setModel(spinnerModel);
slider.setLabelTable(table);
slider.setPaintLabels(true);
JPanel topPanel = new JPanel();
topPanel.add(spinner);
topPanel.add(new JButton(new ButtonAction("Press Me")));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(slider);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
char ch = (char) spinner.getValue();
int value = TEXTS.indexOf(ch);
slider.setValue(value);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
CameraFoo mainPanel = new CameraFoo();
JFrame frame = new JFrame("CameraFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

Java ActionListener - change variable in actionPerformed

I'm starting my adventure with programming and I've got one problem. I try make a simple calculator using awt. I can't go further because I don't know, how to change one variable - textField initialized in MainFrame. I want to change it in actionPerformed. Here's my code and I'll be grateful if You'll give me some guidance. Thanks!
package starter;
import java.awt.EventQueue;
public class Starter {
public Starter () {
EventQueue.invokeLater(new Runnable (){
#Override
public void run () {
new MainFrame();
System.out.println();
}
});
}
public static void main(String[] args) {
new Starter();
}
}
MainFrame
package starter;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame extends JFrame {
private JTextField textField = new JTextField();
DigitActionListener digitPressed = new DigitActionListener();
public MainFrame() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(true);
setSize(350, 400);
setLayout (new GridLayout (6, 4, 3, 3));
JButton buttonClear = new JButton("Clear"); buttonClear.addActionListener(digitPressed);
JButton button0 = new JButton ("0"); button0.addActionListener(digitPressed);
JButton button1 = new JButton ("1"); button1.addActionListener(digitPressed);
JButton button2 = new JButton ("2"); button2.addActionListener(digitPressed);
JButton button3 = new JButton ("3"); button3.addActionListener(digitPressed);
JButton button4 = new JButton ("4"); button4.addActionListener(digitPressed);
JButton button5 = new JButton ("5"); button5.addActionListener(digitPressed);
JButton button6 = new JButton ("6"); button6.addActionListener(digitPressed);
JButton button7 = new JButton ("7"); button7.addActionListener(digitPressed);
JButton button8 = new JButton ("8"); button8.addActionListener(digitPressed);
JButton button9 = new JButton ("9"); button9.addActionListener(digitPressed);
JButton multiplicationButton = new JButton ("*"); multiplicationButton.addActionListener(digitPressed);
JButton divisionButton = new JButton ("/"); divisionButton.addActionListener(digitPressed);
JButton additionButton = new JButton ("+"); additionButton.addActionListener(digitPressed);
JButton substructionButton = new JButton ("-"); substructionButton.addActionListener(digitPressed);
JButton equalsButton = new JButton ("="); equalsButton.addActionListener(digitPressed);
JButton commaButton = new JButton ("."); commaButton.addActionListener(digitPressed);
add (buttonClear);
add (new JLabel (""));
add (new JLabel (""));
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
textPanel.add(textField, BorderLayout.CENTER);
this.add(textPanel);
add(button7);
add(button8);
add(button9);
add(divisionButton);
add(button4);
add(button5);
add(button6);
add(multiplicationButton);
add(button1);
add(button2);
add(button3);
add(additionButton);
add(commaButton);
add(button0);
add(equalsButton);
add(substructionButton);
}
public JTextField getTextField() {
return textField;
}
public void setTextField(String text) {
textField.setText(text);
}
}
DigitActionListener
package starter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DigitActionListener implements ActionListener {
int size = 0;
char[] tab = new char[size];
public void pain (Graphics g, String s){
g.drawString(s, 20, 10);
}
#Override
public void actionPerformed(ActionEvent e) {
//Object source = e.getSource();
String command = e.getActionCommand();
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
MainFrame mainFrame = new MainFrame();
mainFrame.setTextField(eq);
size++;
}
}
}
Your problem is here:
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
MainFrame mainFrame = new MainFrame();
mainFrame.setTextField(eq);
size++;
}
You're creating a new MainFrame object and changing its state, but understand that this will have no effect on the completely distinct displayed MainFrame object and will not change its state whatsoever (will not change what is displayed within its JTextField). There are a variety of possible solutions, but it all boils down to understanding what Java references are, and calling methods on the appropriate reference, here the appropriate MainFrame object. A simple solution could be for to pass the MainFrame object into your listener via a listener constructor, and then call the methods on this reference.
For example:
class DigitActionListener implements ActionListener {
private MainFrame mainFrame;
int size = 0;
char[] tab = new char[size];
public DigitActionListener(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void pain (Graphics g, String s){
g.drawString(s, 20, 10);
}
#Override
public void actionPerformed(ActionEvent e) {
//Object source = e.getSource();
String command = e.getActionCommand();
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
// MainFrame mainFrame = new MainFrame(); // **** no, don't do this
mainFrame.setTextField(eq);
size++;
}
}
}
and then within MainFrame itself, do something like:
// pass *this* or the current MainFrame instance, into the DigitalActionListener
DigitActionListener digitPressed = new DigitActionListener(this);
Other issues -- learn to use and then use arrays and ArrayLists, as this can help you simplify your code, and thus make program improvement and debugging much easier.

Java: Why doesn't my image show up?

I have created 2 classes that are working together to show pictures by clicking different buttons. In my EventEvent class I tried to make it so that when you press the "Picture 1" button, the variable ImageIcon xpic gets the value of ImageIcon vpic (which holds an image), after xpic has the same value as vpic my frame is supposed to somehow refresh so that xpic's new value applies and gets then shows the picture.
Why doesn't my image show up even though the button press repaints the JPanel the image is in?
Main class:
import java.awt.*;
import javax.swing.*;
public class EventMain extends JFrame{
EventEvent obje = new EventEvent(this);
// Build Buttons
JButton picB1;
JButton picB2;
JButton picB3;
JButton picB4;
JButton picB5;
//Build Panels
JPanel row0;
//Build Pictures
ImageIcon xpic;
ImageIcon vpic;
public EventMain(){
super("Buttons");
setLookAndFeel();
setSize(470, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout1 = new GridLayout(3,4);
setLayout(layout1);
picB1 = new JButton("Picture 1");
picB2 = new JButton("Picture 2");
picB3 = new JButton("Picture 3");
picB4 = new JButton("Picture 4");
picB5 = new JButton("Picture 5");
vpic = new ImageIcon(getClass().getResource("Images/vanessa.png"));
// Set up Row 0
row0 = new JPanel();
JLabel statement = new JLabel("Choose a picture: ", JLabel.LEFT);
JLabel picture = new JLabel(xpic);
// Set up Row 1
JPanel row1 = new JPanel();
// Set up Row 2
JPanel row2 = new JPanel();
//Listeners
picB1.addActionListener(obje);
FlowLayout grid0 = new FlowLayout (FlowLayout.CENTER);
row0.setLayout(grid0);
row0.add(statement);
row0.add(picture);
add(row0);
FlowLayout grid1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(grid1);
row1.add(picB1);
row1.add(picB2);
add(row1);
FlowLayout grid2 = new FlowLayout(FlowLayout.CENTER);
row2.setLayout(grid2);
row2.add(picB3);
row2.add(picB4);
row2.add(picB5);
add(row2);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.NimbusLookAndFeel");
} catch (Exception exc) {
}
}
public static void main(String[] args) {
EventMain con = new EventMain();
}
}
Class containing events:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventEvent implements ActionListener {
EventMain gui;
public EventEvent(EventMain in){
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Picture 1")){
gui.xpic = gui.vpic;
gui.row0.repaint();
}
}
}
You're confusing variables with objects. Just because you change the object associated with the xpic variable, don't assume that this will change the object (the Icon) held by the JLabel. There is no magic in Java, and changing the object that a variable refers to will have no effect on the prior object.
In other words, this:
gui.xpic = gui.vpic;
gui.row0.repaint();
will have no effect on the icon that the picture JLabel is displaying
To swap icons, you must call setIcon(...) on the JLabel. Period. You will need to make the picture JLabel a field, not a local variable, and give your GUI class a public method that allows outside classes to change the state of the JLabel's icon.
Also, you should not manipulate object fields directly. Instead give your gui public methods that your event object can call.
Edit
For example:
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyGui extends JPanel {
public static final String IMAGE_PATH = "https://duke.kenai.com/cards/.Midsize/CardFaces.png.png";
private static final int ROWS = 4;
private static final int COLS = 13;
private BufferedImage largeImg;
private List<ImageIcon> iconList = new ArrayList<>();
private JLabel pictureLabel = new JLabel();
private JButton swapPictureBtn = new JButton(new SwapPictureAction(this, "Swap Picture"));
private int iconIndex = 0;
public MyGui() throws IOException {
add(pictureLabel);
add(swapPictureBtn);
URL imgUrl = new URL(IMAGE_PATH);
largeImg = ImageIO.read(imgUrl);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
int x = (j * largeImg.getWidth()) / COLS;
int y = (i * largeImg.getHeight()) / ROWS;
int w = largeImg.getWidth() / COLS;
int h = largeImg.getHeight() / ROWS;
iconList.add(new ImageIcon(largeImg.getSubimage(x, y, w, h)));
}
}
pictureLabel.setIcon(iconList.get(iconIndex));
}
public void swapPicture() {
iconIndex++;
iconIndex %= iconList.size();
pictureLabel.setIcon(iconList.get(iconIndex));
}
private static void createAndShowGui() {
MyGui mainPanel;
try {
mainPanel = new MyGui();
JFrame frame = new JFrame("MyGui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class SwapPictureAction extends AbstractAction {
private MyGui myGui;
public SwapPictureAction(MyGui myGui, String name) {
super(name);
this.myGui = myGui;
}
#Override
public void actionPerformed(ActionEvent e) {
myGui.swapPicture();
}
}
See the createAction() method below and how it creates an AbstractAction. See also the tutorial related to using actions with buttons. http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.awt.event.ActionEvent;
public class EventMain {
private static final ImageIcon PICTURE_1 = new ImageIcon(EventMain.class.getResource("images/v1.png"));
private static final ImageIcon PICTURE_2 = new ImageIcon(EventMain.class.getResource("images/v2.png"));
private JFrame frame;
EventMain create() {
setLookAndFeel();
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
void show() {
frame.setSize(470, 300);
frame.setVisible(true);
}
private JFrame createFrame() {
JFrame frame = new JFrame("Buttons");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private Component createContent() {
final JLabel picture = new JLabel();
JButton picB1 = new JButton(createAction("Picture 1", picture, PICTURE_1));
JButton picB2 = new JButton(createAction("Picture 2", picture, PICTURE_2));
JButton picB3 = new JButton(createAction("Picture 3", picture, PICTURE_1));
JButton picB4 = new JButton(createAction("Picture 4", picture, PICTURE_2));
JButton picB5 = new JButton(createAction("Picture 5", picture, PICTURE_1));
JLabel statement = new JLabel("Choose a picture: ", JLabel.LEFT);
// Create rows 1, 2, 3
JPanel panel = new JPanel(new GridLayout(3, 4));
panel.add(createRow(statement, picture));
panel.add(createRow(picB1, picB2));
panel.add(createRow(picB3, picB4, picB5));
return panel;
}
/**
* Create an action for the button. http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
*/
private Action createAction(String label, final JLabel picture, final Icon icon) {
AbstractAction action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
picture.setIcon(icon);
}
};
action.putValue(Action.NAME, label);
return action;
}
private Component createRow(Component... componentsToAdd) {
JPanel row = new JPanel(new FlowLayout(FlowLayout.CENTER));
for (Component component : componentsToAdd) {
row.add(component);
}
return row;
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new EventMain().create().show();
}
});
}
}

Turning some of the JTextBox to be JLabels in a Sudoku Game

So here is what i have so far for my sudoku game. Now my grid only displays textboxes where a user can input numbers but nothing will happen yet. I want to know how to make it so that the user can only input one character and only numbers. i would also like to know how to make some textboxes jdialogs displaying uneditable numbers that im taking from http://www.websudoku.com/ for the puzzle. Any help would be appreciated. Thanks.
Main Class
import javax.swing.JOptionPane;
public class Game{
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello. Welcome to a game of Sudoku by #### ####.");
Level select = new Level();
}
}
Difficulty Select Class
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Level extends JFrame {
private JLabel tag1;
private JButton butt1;
private JButton butt2;
private JButton butt3;
private JButton butt4;
public Level(){
super("Difficulty");
setLayout(new FlowLayout());
setSize(250,130);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tag1 = new JLabel("Please Select Your Difficulty.");
add(tag1);
butt1 = new JButton("Easy.");
butt1.setToolTipText("For players new to Sudoku.");
add(butt1);
butt2 = new JButton("Medium.");
butt2.setToolTipText("Your abilites will be tested.");
add(butt2);
butt3 = new JButton("Hard.");
butt3.setToolTipText("Your skills will be strained.");
add(butt3);
butt4 = new JButton("Evil!");
butt4.setToolTipText("You will not survive.");
add(butt4);
thehandler handler = new thehandler();
butt1.addActionListener(handler);
butt2.addActionListener(handler);
butt3.addActionListener(handler);
butt4.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==butt1){
dispose();
string = "Have fun!";
SudokuPanel Squares = new SudokuPanel();
}
else if(event.getSource()==butt2){
dispose();
string = "Good luck!";
SudokuPanel Squares = new SudokuPanel();
}
else if(event.getSource()==butt3){
dispose();
string = "Try to keep your head from exploding...";
SudokuPanel Squares = new SudokuPanel();
}
else if(event.getSource()==butt4){
dispose();
string = "Please refrain from smashing any keyboards.";
SudokuPanel Squares = new SudokuPanel();
}
JOptionPane.showMessageDialog(null, string);
}
}
}
Sudoku Panel Class
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class SudokuPanel extends JFrame {
public final int SQUARE_COUNT = 9;
public Squares [] squares = new Squares[SQUARE_COUNT];
public SudokuPanel(){
super("Sudoku");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3,3));
for(int i=0; i<SQUARE_COUNT; i++){
squares[i] = new Squares();
panel.add(squares[i]);
}
JPanel panel2 = new JPanel();
JButton startTime = new JButton();
JButton stop = new JButton();
JButton resetTimer = new JButton();
MyTimer timer = new MyTimer();
startTime = new JButton("Start Timer");
stop = new JButton("Stop Timer");
final JLabel timerLabel = new JLabel(" ...Waiting... ");
resetTimer = new JButton("Reset");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem newDifficulty = new JMenuItem("Select New Difficulty");
menu.add(newDifficulty);
JMenuItem reset = new JMenuItem("Reset Puzzle");
menu.add(reset);
JMenuItem exit = new JMenuItem("Exit");
menu.add(exit);
exitaction e = new exitaction();
newDifficultyaction d = new newDifficultyaction();
resetaction f = new resetaction();
reset.addActionListener(f);
exit.addActionListener(e);
newDifficulty.addActionListener(d);
panel2.add(timer);
add(panel, BorderLayout.CENTER);
add(panel2, BorderLayout.PAGE_END);
setVisible(true);
setLocationRelativeTo(null);
}
public class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
public class newDifficultyaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
Level select = new Level();
}
}
public class resetaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
SudokuPanel Squares = new SudokuPanel();
}
}
}
Squares/Cells class
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Squares extends JPanel {
public final int CELL_COUNT = 9;
public Cell [] cells = new Cell[CELL_COUNT];
public Squares(){
this.setLayout(new GridLayout(3,3));
this.setBorder(new LineBorder(Color.BLACK,2));
for(int i =0; i<CELL_COUNT; i++){
cells[i] = new Cell();
this.add(cells[i]);
}
}
public class Cell extends JTextField{
private int number;
public Cell(){
}
public void setNumber(int number){
this.number = number;
this.setText("1");
}
public int getNumber(){
return number;
}
}
}
Timer Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyTimer extends Panel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
Timer timer;
public MyTimer(){
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Timer");
timeDisplay = new JLabel("...Waiting...");
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
event e = new event();
startButton.addActionListener(e);
event1 c = new event1();
stopButton.addActionListener(c);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
int count = 0;
timeDisplay.setText("Elapsed Time in Seconds: " + count);
TimeClass tc = new TimeClass(count);
timer = new Timer(1000, tc);
timer.start();
}
}
public class TimeClass implements ActionListener{
int counter;
public TimeClass(int counter){
this.counter = counter;
}
public void actionPerformed(ActionEvent e){
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener{
public void actionPerformed (ActionEvent c){
timer.stop();
}
}
}
I want to know how to make it so that the user can only input one character and only numbers.
There are several ways, all easily discoverable by searching this site, as this problem is a common one. Two I'll mention: use a JFormattedTextField, or use a JTextField whose Document has a DocumentFilter added to it that prevents wrong input from being entered.
i would also like to know how to make some textboxes jdialogs displaying uneditable numbers that im taking from http://www.websudoku.com/ for the puzzle. Any help would be appreciated.
Several possible solutions to this one including
Set the component's enabled property to false.
Set the component's focusable property to false.
Some issues with your post:
You mention use of "textboxes". I recommend you avoid using non-Java non-Swing terms like "textboxes" as they only will serve to confuse. If you are using a specific type of text component and are asking about it, mention the component type by name as solutions may differ depending on the type.
You have posted a wall of code, most of it unrelated to your problem at hand. Please remember that we are volunteers, and please be kind to us. One way is to avoid posting too much unrelated code. Best would be to post a small minimal example program for questions that need this.

Java: Listener subclass won't change superclass buttons

my first post after long time lurking.
I'm trying to write a java program to train my calculation skills as Khan academy removed the never-ending mode on sum, subtraction, etc.
I somehow managed to write the skeleton but I got stuck when I had to implement listeners: if I create a class that implements ActionListener everything works. But when I try to use a sublass that implements ActionListener the code breaks. I'd like to figure out why.
I have 3 classes.
Question: generates 2 random int
public class Question {
public int rand1;
public int rand2;
public Question (){
rand1 = (int) (100 +(Math.random()*900)); // to be sure I have at least 3 digits. See AnswerV2.generate()
rand2 = (int) (100 + (Math.random()*900));
}
}
Answersv2: takes the 2 random int
from Question, sums them, create 3 different answers switching
digits, adds the right answer and shuffles them.
import java.util.ArrayList;
import javax.swing.JButton;
import java.util.Collections;
public class Answersv2 {
public ArrayList Answer_list = new ArrayList();
public int int1;
public int int2;
String uno;
public Answersv2 (int a, int b) {
int1 = a;
int2 = b;
}
public void generate (){
StringBuilder due = new StringBuilder();
StringBuilder tre = new StringBuilder();
StringBuilder quattro = new StringBuilder();
uno = Integer.toString(int1+int2); // create the string version of int1+int2
ArrayList <Character> first_answer = new ArrayList<Character>(); // create an arraylist of char to store the chars
for (char c : uno.toCharArray()) {
first_answer.add(c);
}
Collections.swap(first_answer,first_answer.size()-2,first_answer.size()-1); // switch tens with units
for (char c : first_answer) {
due.append(c);
}
String dueString = due.toString();
Collections.swap(first_answer,first_answer.size()-3,first_answer.size()-2); // switchs hundres with tens
for (char c : first_answer) {
tre.append(c);
}
String treString = tre.toString();
Collections.swap(first_answer,first_answer.size()-2,first_answer.size()-1); // switch tens with units
for (char c : first_answer) {
quattro.append(c);
}
String quattroString = quattro.toString();
add(uno,dueString,treString,quattroString);
}
public void add (String one,String two,String three,String four){
Answer_list.add(one);
Answer_list.add(two);
Answer_list.add(three);
Answer_list.add(four);
shuffle();
}
public void shuffle() {
Collections.shuffle(Answer_list);
}
public void stampa (){ // command code line version to test the program, ignore this
System.out.println("--------------------------------");
System.out.println(int1 + " + " + int2 + " = : ");
System.out.println("A " + Answer_list.get(0));
System.out.println("B " + Answer_list.get(1));
System.out.println("C " + Answer_list.get(2));
System.out.println("D " + Answer_list.get(3));
}
public class CoolButton extends JButton{
public CoolButton(String answer) {
setText(answer);
}
public boolean checkme() { // method to check if the button pressed was the one with the right answer. I still haven't implemented this properly, ignore this too
if (getText() == uno) {
return true;
} else {
return false;
}
}
}
}
3 QuizV2: Creates the GUI and starts the program.
Now... I created a StartListener subclass of QuizV2 in order to make the buttons being able to read the 4 answers from the answer object created in the QuizV2's main and use it to
setText() and to change label text, etc.
Here is the code (Quizv2) with the subclass:
import java.util.ArrayList;
import java.util.Collections;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Quizv2{
public MyLabel label = new MyLabel("Click Start");
JButton button = new JButton("Start");
Answersv2 pinolo;
Question domanda;
Answersv2.CoolButton button1;
Answersv2.CoolButton button2;
Answersv2.CoolButton button3;
Answersv2.CoolButton button4;
public static void main (String [] args) {
Quizv2 quiz = new Quizv2();
quiz.go();
}
public void go () {
Question domanda = new Question();
Answersv2 pinolo = new Answersv2(domanda.rand1,domanda.rand2);
pinolo.generate();
button1 = pinolo.new CoolButton(pinolo.Answer_list.get(0));
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2 = pinolo.new CoolButton(pinolo.Answer_list.get(1));
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
button3 = pinolo.new CoolButton(pinolo.Answer_list.get(2));
button3.setAlignmentX(Component.CENTER_ALIGNMENT);
button4 = pinolo.new CoolButton(pinolo.Answer_list.get(3));
button4.setAlignmentX(Component.CENTER_ALIGNMENT);
JFrame frame = new JFrame("SPI trainer - Sum");
JPanel panel = new JPanel();
label.setAlignmentX(Component.CENTER_ALIGNMENT);
int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
label.setForeground(randomColor);
panel.add(label);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);
ActionListener doGreeting = new StartListener();
button.addActionListener(doGreeting );
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setSize(300,300);
frame.setVisible(true);
frame.setLocationRelativeTo( null );
}
}
class StartListener extends Quizv2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
label.setLabelText("The button text changed.");
}
}
However it seems I'm doing something wrong as it prints 'boo' but it doesn't change the label text. I'd like to avoid to use
class StartListener extends Quizv2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (buttony == e.getSource()) {
label.setLabelText( domanda.rand1 + " + " + domanda.rand2 + " = : ????");
button1.setVisible(true);
button2.setVisible(true);
button3.setVisible(true);
button4.setVisible(true);
button.setVisible(false);
.....
.....
else if (buttonx == e.getSource())
....
}
}
in order to figure out which button was pressed so that the programs knows which block of code execute.
I then tried not to use a subclass and everything worked out. Here is the code (Quizv2)
import java.util.ArrayList;
import java.util.Collections;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Quizv2 implements ActionListener{
public MyLabel label = new MyLabel("Click Start");
JButton button = new JButton("Start");
Answersv2 pinolo;
Question domanda;
Answersv2.CoolButton button1;
Answersv2.CoolButton button2;
Answersv2.CoolButton button3;
Answersv2.CoolButton button4;
public static void main (String [] args) {
Quizv2 quiz = new Quizv2();
quiz.go();
}
public void go () {
domanda = new Question();
pinolo = new Answersv2(domanda.rand1,domanda.rand2);
pinolo.generate();
button1 = pinolo.new CoolButton(pinolo.Answer_list.get(0));
button1.setAlignmentX(Component.CENTER_ALIGNMENT);
button2 = pinolo.new CoolButton(pinolo.Answer_list.get(1));
button2.setAlignmentX(Component.CENTER_ALIGNMENT);
button3 = pinolo.new CoolButton(pinolo.Answer_list.get(2));
button3.setAlignmentX(Component.CENTER_ALIGNMENT);
button4 = pinolo.new CoolButton(pinolo.Answer_list.get(3));
button4.setAlignmentX(Component.CENTER_ALIGNMENT);
JFrame frame = new JFrame("SPI trainer - Sum");
JPanel panel = new JPanel();
label.setAlignmentX(Component.CENTER_ALIGNMENT);
int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
label.setForeground(randomColor); // Little bit of color
panel.add(label);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);
button.addActionListener(this);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(button1);
button1.setVisible(false);
panel.add(button2);
button2.setVisible(false);
panel.add(button3);
button3.setVisible(false);
panel.add(button4);
button4.setVisible(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setSize(300,300);
frame.setVisible(true);
frame.setLocationRelativeTo( null );
}
public void actionPerformed(ActionEvent e) {
label.setLabelText( domanda.rand1 + " + " + domanda.rand2 + " = : ????");
button1.setVisible(true);
button2.setVisible(true);
button3.setVisible(true);
button4.setVisible(true);
button.setVisible(false);
}
}
1) I suggest you put this program aside for quite awhile. You are making a lot of basic errors, so I don't see how you got anything to compile. And your code is a labyrinth which is a sign that the program is way too complex for your abilities at this time.
2) Your post also shows that you need to improve your debugging skills. You really shouldn't post more than about 20 lines of code when asking a question. Reducing a problem to around 20 lines of code is an exercise that improves your debugging skills. 90% of the code you posted is irrelevant to your problem. For instance, your whole Answerv2 class could have been reduced to this:
public class Answersv2 {
public ArrayList<String> Answer_list = new ArrayList<String>();
public Answersv2 () {
Answer_list.add("300", "150", "160", "170");
}
}
Do you really think that the way your code calculated those strings is relevant to why clicking on a button fails to change the text of a label? In fact, your whole Answerv2 class is irrelevant.
The number of lines of code your program can contain is proportional to your debugging skills. You cannot write a 500 line program two days after learning java. And writing Swing programs adds a lot of moving parts, so you need to have a solid grasp of the basics before attempting Swing--like not trying to access a non-static variable inside a static method.
When you are having trouble with some code, like your inheritance problem, start a new program to experiment. Make the new program as simple as possible:
1) Write a basic Swing program that sets up the relevant swing components...
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyGui {
protected JLabel label = new JLabel("Hello");
protected JButton button = new JButton("Click me");
public MyGui() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(300, 100, 500, 300);
JPanel panel = new JPanel();
panel.add(label);
panel.add(button);
Container cpane = frame.getContentPane();
cpane.add(panel);
frame.setVisible(true);
}
}
public class SwingProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} }
2) Get an actionPerformed() method in the same class to work:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyGui implements ActionListener { //********
protected JLabel label = new JLabel("Hello");
protected JButton button = new JButton("Click me");
public MyGui() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(300, 100, 500, 300);
JPanel panel = new JPanel();
panel.add(label);
button.addActionListener(this); //**********
panel.add(button);
Container cpane = frame.getContentPane();
cpane.add(panel);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) { //**************
System.out.println("boo");
label.setText("The button was clicked!");
}
}
public class SwingProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
3) Now try inherit from MyGui and put the actionPerformed method in the child class. Okay, so you can't figure out how to make it work. Now at least you have a simple example to post.
The problem with your button is: you never specified that the actionPerformed() method in the subclass should be the listener for the button. Here is a solution to your problem:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyGui {
protected JLabel label = new JLabel("Hello");
protected JButton button = new JButton("Click me");
public MyGui() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(300, 100, 500, 300);
JPanel panel = new JPanel();
panel.add(label);
panel.add(button);
Container cpane = frame.getContentPane();
cpane.add(panel);
frame.setVisible(true);
}
}
class StartListener extends MyGui implements ActionListener {
public StartListener(){
super();
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
label.setText("The button text changed.");
}
}
public class SwingProg {
private static void createAndShowGUI() {
new StartListener();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Don't try to solve problems in the middle of a complex program. Instead, extrapolate the problem out into a new program, and solve the problem in the new program.

Categories