Im developing an little "clicker" but, if i press the button, and i should get 1+ Score, it dont work! Is there any way to reload or anything else?
Heres my code: (ClickEvent)
public class event implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("PRESS");
game.timesClicked.add(1);
points.setText(game.seePoints);
}
}
And there is my JFrame:
public class game extends JFrame
{
public static JButton buttonStart;
JButton buttonCredits;
JButton buttonBack;
JButton buttonLeave;
public static JFrame panel = new game();
public static ArrayList<Integer> timesClicked = new ArrayList<Integer>();
public static JLabel label1;
public static JLabel points;
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
public game()
{
setLayout(null);
label1 = new JLabel("ButtonClicker");
points = new JLabel(seePoints);
points.setFont(new Font("Tahoma", Font.BOLD, 15));
points.setBounds(0, 0, 200, 200);
label1.setFont(new Font("Tahoma", Font.BOLD, 50));
label1.setBounds(315, 50, 500, 200);
event e1 = new event();
JButton b = new JButton("KNOPF");
b.setBackground(new Color(96, 140, 247));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 15));
b.setBounds( 402, 380, 180, 50 );
b.addActionListener(e1);
add(b);
add(label1);
add(points);
}
}
(Sorry For My Bad English)
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
This is only being called once at the start of your program. When you add to timesClicked, it does not recalculate seePoints.
You will need to set this variable to the correct value every time you click.
Related
this button does nothing what would be the mistake?
its a login, I dont know why it doesnt work seems pretty well, could somebody help me to indentify the issue?.....................................................................................................................
package Operaciones_Logicas;
import Mainargs.FirstClass;
import java.awt.event.*;
import javax.swing.*;
public class Main1 extends JFrame implements ActionListener {
private JLabel usuario;
private JLabel contraseña;
public JButton blogin;
public JTextField jtusuario, jtcontra;
public static String susuario = "", scontra = "";
public Main1() {
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Cajero Automatico");
JLabel usuario = new JLabel();
usuario.setVisible(true);
usuario.setBounds(20, 100, 100, 50);
add(usuario);
JLabel contraseña = new JLabel();
contraseña.setBounds(20, 300, 100, 50);
add(contraseña);
JButton blogin = new JButton("Login");
blogin.setBounds(50, 400, 100, 30);
blogin.addActionListener(this);
add(blogin);
JTextField jtusuario = new JTextField();
jtusuario.setBounds(20, 120, 150, 30);
add(jtusuario);
JTextField jtcontra = new JTextField();
jtcontra.setBounds(20, 150, 150, 30);
add(jtcontra);
}
//control para el login
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == blogin) {
susuario = jtusuario.getText();
scontra = jtcontra.getText();
if (susuario.equals("josmart96") && (scontra.equals("rojo2000"))) {
FirstClass secondwindow = new FirstClass();
secondwindow.setBounds(0, 0, 600, 360);
secondwindow.setVisible(true);
secondwindow.setResizable(false);
secondwindow.setLocationRelativeTo(null);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "Usuario y/o Contraseña
incorrectas");
}
}
}
public static void main(String[] args) {
Main1 firstwindow = new Main1();
firstwindow.setBounds(0, 0, 360, 600);
firstwindow.setVisible(true);
firstwindow.setResizable(false);
firstwindow.setLocationRelativeTo(null);
}
}
no erros just doesnt work, when hit button does nothing I can compile it and everything is good I think it could be the IDE itself
You are using local variable blogin instead of using instance variable blogin
Inside the contructor, change
JButton blogin = new JButton("Login");
to
blogin = new JButton("Login");
you also need to use other declared instance variables rather than declaring local variables inside the constructor
I'm making a gui program everything going right but add background image in frame so i take jpanel private variable.Also i add image in src which is
but how to use this jpanel variable to add background image in frame.
Code:
public class App extends JFrame{
private JPanel panel;
private JTextField field1;
private JTextField print;
private JLabel label;
private JLabel label2;
private JButton button;
public App(){
super();
getContentPane().setLayout(null);
label = new JLabel("Value");
label.setForeground(Color.RED);
label.setFont(new Font("SansSerif", Font.PLAIN, 18));
label.setBounds(178, 46, 51, 26);
getContentPane().add(label);
label2 = new JLabel("Print");
label2.setForeground(Color.RED);
label2.setFont(new Font("SansSerif", Font.PLAIN, 18));
label2.setBounds(178, 143, 42, 26);
getContentPane().add(label2);
field1 = new JTextField();
field1.setBounds(178, 72, 76, 26);
getContentPane().add(field1);
print = new JTextField();
print.setBounds(178, 181, 77, 26);
getContentPane().add(print);
button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String w= field1.getText();
print.setText(w);
}
});
button.setBounds(178, 219, 77, 26);
getContentPane().add(button);
}
}
Main Method:
public class Main {
public static void main(String[] args) {
App object = new App();
object.setSize(450, 400);
object.setDefaultCloseOperation(object.EXIT_ON_CLOSE);
object.setLocationRelativeTo(null);
object.setVisible(true);
}
}
You have set Layout to null which is making a problem. Whenever we make layout null we have to set bounds for it.
Folow this method:
first of all copy your background image and paste in src of code
than set layout to borderlayout like this:
setLayout(new BorderLayout());
now add this code:
setContentPane(new JLabel new ImageIcon(getClass().getResource("image.jpg"))));
Note: add your image name here "image.jpg"
I have an issue where when I include the JPanel in my JFrame, it covers the entire screen. My code reads
import java.awt.*;
import javax.swing.*;
public class TestFrameExample extends JPanel {
static String TheQuestion;
static String QN1 = "Question 1: ";
static String Q1 = "What is Lead's chemical symbol?";
static String brk = "___________________";
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(new Color(135, 206, 250));
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(QN1, 80, 100);
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(brk, 60, 130);
g.setFont(new Font("Tahoma", Font.PLAIN, 36));
g.setColor(Color.WHITE);
g.drawString(Q1, 80, 200);
}
public static void main(String[] args) {
TestFrameExample graphics = new TestFrameExample();
JFrame ThisFrame = new JFrame();
TheQuestion = QN1;
JTextField txt = new JTextField(10);
JPanel Panel = new JPanel();
ThisFrame.setTitle("Question 1");
ThisFrame.setSize(720, 480);
ThisFrame.setLocationRelativeTo(null);
ThisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThisFrame.setVisible(true);
ThisFrame.add(graphics);
Panel.setBackground(new Color(135, 206, 250));
Panel.setSize(null);
Panel.setLocation(null);
Panel.add(txt);
ThisFrame.add(Panel);
}
}
However, when I change
Panel.setLocation(null)
to
Panel.setLocation(80, 250)
It covers the entire screen.
Could someone please help me put it in the right spot on the screen?
UPDATE
I made the modifications as I said in my comment, with the code reading
import java.awt.*;
import javax.swing.*;
public class TestFrameExample extends JPanel {
static String TheQuestion;
static String QN1 = "Question 1: ";
static String Q1 = "What is Lead's chemical symbol?";
static String brk = "___________________";
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(new Color(135, 206, 250));
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(QN1, 80, 100);
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(brk, 60, 130);
g.setFont(new Font("Tahoma", Font.PLAIN, 36));
g.setColor(Color.WHITE);
g.drawString(Q1, 80, 200);
}
public static void main(String[] args) {
TestFrameExample graphics = new TestFrameExample();
JFrame ThisFrame = new JFrame();
TheQuestion = QN1;
JTextField txt = new JTextField(20);
JPanel panel = new JPanel();
ThisFrame.setTitle("Question 1");
ThisFrame.setSize(720, 480);
ThisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThisFrame.add(graphics);
panel.setBackground(new Color(135, 206, 250));
panel.add(txt);
ThisFrame.add(panel);
ThisFrame.add(panel, BorderLayout.PAGE_END);
ThisFrame.setLocationRelativeTo(null);
ThisFrame.setVisible(true);
}
}
It places the input txt at the bottom of the screen, but the rest of the screen remains grey.
But I simply don't understand the second set of code that you posted; it's far beyond my skill set (I've only been learning Java for the last 6 weeks). All I'm looking for at this stage is make the panel not blank out the rest of the screen.
Is this possible just by modifying the current set of code, or would I have to completely rewrite the code?
A JFrame's contentPane uses BorderLayout by default, and you can use that to your advantage:
Add your TestFrameExample object BorderLayout.CENTER to your JFrame
Add your other JPanel, or perhaps just a JTextField to the JFrame in the BorderLayout.PAGE_END position. This will add the component to the bottom of the GUI.
Don't call setLocation(...) on your components as that's inviting use of null layouts, a layout that leads to rigid GUI's that are hard to debug and upgrade.
For more details, read up on the BorderLayout in the tutorials.
e.g.,
public static void main(String[] args) {
TestFrameExample graphics = new TestFrameExample();
JFrame thisFrame = new JFrame();
TheQuestion = QN1;
JTextField txt = new JTextField(10);
JPanel panel = new JPanel();
thisFrame.setTitle("Question 1");
thisFrame.setSize(720, 480); // better to not do this, but to pack instead
// thisFrame.setLocationRelativeTo(null);
thisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// thisFrame.setVisible(true); // *** not yet ***
thisFrame.add(graphics, BorderLayout.CENTER);
panel.setBackground(new Color(135, 206, 250));
// panel.setSize(null); // *** don't do this ***
// panel.setLocation(null); // *** don't do this ***
panel.add(txt);
thisFrame.add(panel, BorderLayout.PAGE_END);
thisFrame.setLocationRelativeTo(null);
thisFrame.setVisible(true); // *** HERE ***
}
Note that myself, I'd avoid direct painting if possible and instead would use components and layout managers. This should make it easier to display different kinds of questions. For example, run the following program and by pressing the <enter> key repeatedly, scroll the questions to see just what I mean:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class TestQuestion2 extends JPanel {
private static final Color BACKGROUND = new Color(135, 206, 250);
private static final Color LABEL_FOREGROUND = Color.white;
private static final int EB_GAP = 60;
private static final int PREF_W = 720;
private static final int PREF_H = 480;
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 48);
private static final Font Q_FONT = TITLE_FONT.deriveFont(Font.PLAIN, 36f);
private JLabel questionTitleLabel = new JLabel();
private JTextArea questionArea = new JTextArea(4, 10);
private JTextField answerField = new JTextField(20);
private Question question;
private List<Question> questionList;
private int questionListIndex = 0;
public TestQuestion2(List<Question> questionList) {
this.questionList = questionList;
questionTitleLabel.setFont(TITLE_FONT);
questionTitleLabel.setForeground(LABEL_FOREGROUND);
JSeparator separator = new JSeparator();
separator.setForeground(LABEL_FOREGROUND);
questionArea.setFont(Q_FONT);
questionArea.setForeground(LABEL_FOREGROUND);
questionArea.setWrapStyleWord(true);
questionArea.setLineWrap(true);
questionArea.setBorder(null);
questionArea.setOpaque(false);
questionArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(questionArea);
scrollPane.setBorder(null);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
JPanel answerPanel = new JPanel();
answerPanel.add(answerField);
answerPanel.setOpaque(false);
setBackground(BACKGROUND);
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(questionTitleLabel);
add(Box.createHorizontalStrut(10));
add(separator);
add(Box.createHorizontalStrut(5));
add(scrollPane);
add(Box.createHorizontalGlue());
add(answerPanel);
setQuestion(questionList.get(questionListIndex));
answerField.addActionListener(new AnswerListener());
}
public void setQuestion(Question question) {
this.question = question;
questionTitleLabel.setText("Question " + question.getNumber() + ":");
questionArea.setText(question.getQuestion());
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class AnswerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
questionListIndex++;
questionListIndex %= questionList.size();
setQuestion(questionList.get(questionListIndex));
}
}
private static void createAndShowGui() {
List<Question> questionList = new ArrayList<>();
questionList.add(new Question(1, "What is Lead's chemical symbol?"));
questionList.add(new Question(2, "Who is buried in Grant's tomb?"));
questionList.add(new Question(3, "What ..... is your quest?"));
questionList.add(new Question(4, "What ..... is your favorite color?"));
questionList.add(new Question(5, "What is the capital of Assyria?"));
questionList.add(new Question(6, "What is the airspeed velocity of the unladen laden swallow?"));
questionList.add(new Question(7, "This will be a very long question, one that shows the display "
+ "of multiple lines, and a JTextArea that looks like a JLabel. "
+ "What do you think of it?"));
TestQuestion2 testQuestion2Panel = new TestQuestion2(questionList);
JFrame frame = new JFrame("Question");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(testQuestion2Panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Question {
private int number;
private String question;
private List<String> possibleAnswers;
public Question(int number, String question) {
this.number = number;
this.question = question;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
I almost have this code working. I can launch the GUI, however, when I press any of the buttons, I get the following error message:
The type TextFieldDemo must implement the inherited abstract method ActionListener
I have looked around online and can't see any issues with the code. Can someone help me please?
Thanks :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextFieldDemo implements ActionListener{
private JLabel lblName, lblAddress, lblPhone;
private JTextField txtName, txtAddress, txtPhone;
private JButton btnUpper, btnLower, btnExit;
private JPanel panel;
private JFrame frame;
public static void main(String[] args){
new TextFieldDemo();
}
public TextFieldDemo(){
createForm();
addFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Student Form");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void addFields(){
txtName = new JTextField("Fred Bloggs");
txtName.setBounds(110, 50, 150, 20);
panel.add(txtName);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
txtAddress = new JTextField ("Ashley Road");
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
lblPhone = new JLabel ("Phone Number");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
txtPhone= new JTextField("01202 191 3333");
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
lblName = new JLabel("Student Name");
lblName.setBounds(10, 50, 100, 20);
panel.add(lblName);
}
public void addButtons(){
btnUpper = new JButton ("UpperCase");
btnUpper.setBounds(50, 200, 100, 20);
btnUpper.addActionListener(this);
panel.add (btnUpper);
btnLower = new JButton ("LowerCase");
btnLower.setBounds(150, 200, 100, 20);
btnLower.addActionListener(this);
panel.add (btnLower);
btnExit = new JButton ("Exit");
btnExit.setBounds(250, 200, 100, 20);
btnExit.addActionListener(this);
panel.add (btnExit);
}
class UpperCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toUpperCase());
txtAddress.setText(txtAddress.getText().toUpperCase());
}
class LowerCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toLowerCase());
txtAddress.setText(txtAddress.getText().toLowerCase());
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
}
}
You say TextFieldDemo implements ActionListener, but it doesn't have an actionPerformed() method, so it's not actually implementing the interface.
Either implement the method or don't claim it implements the interface.
I didn't think it would compile like you have it, but there you go!
The error should make you check the documentation of ActionListener to find out what method(s) is missing. Sometimes eclipse will prompt you to add stubs for the missing methods.
The documentation shows the interface ActionListener has one method to be implemented, actionPerformed();
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
Strange, the compiler should throw an error on this.
So I'm starting a new project and I was wondering how can I setup multiple classes for my different JPanels. It looks very messy in one class. Let me show you the example. I would like the JPanel for a menu screen in it's own class.
import java.awt.EventQueue;
public class TakeAwayLogin {
private JFrame frmTakeAwaySystem;
private JTextField textFieldId;
private JPasswordField passwordField;
/**
* Launch the application.
* #return
*/
public void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TakeAwayLogin window = new TakeAwayLogin();
window.frmTakeAwaySystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TakeAwayLogin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTakeAwaySystem = new JFrame();
frmTakeAwaySystem.setTitle("Take Away System Alpha");
frmTakeAwaySystem.setBounds(100, 100, 450, 300);
frmTakeAwaySystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTakeAwaySystem.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panelLogin = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelLogin, "name_254735117500687");
panelLogin.setLayout(null);
panelLogin.setVisible(true);
final JLabel lblIncorrect = new JLabel("Incorrect login, try again");
lblIncorrect.setHorizontalAlignment(SwingConstants.CENTER);
lblIncorrect.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblIncorrect.setForeground(Color.RED);
lblIncorrect.setBounds(148, 74, 139, 14);
panelLogin.add(lblIncorrect);
lblIncorrect.setVisible(false);
final JPanel panelPassword = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPassword, "name_254738265432897");
panelPassword.setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(112, 157, 205, 41);
panelLogin.add(passwordField);
passwordField.setHorizontalAlignment(JPasswordField.CENTER);
JButton btnNewButton = new JButton("Lock Application");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPassword.setVisible(false);
panelLogin.setVisible(true);
passwordField.setText("");
textFieldId.disable();
}
});
btnNewButton.setBounds(135, 155, 172, 50);
panelPassword.add(btnNewButton);
panelPassword.setVisible(false);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String login = textFieldId.getText();
char[] pass = passwordField.getPassword();
String p = new String(pass);
String password = "pass";
if (login.equalsIgnoreCase("milan") && p.equals(password)) {
panelPassword.setVisible(true);
panelLogin.setVisible(false);
}else {
lblIncorrect.setVisible(true);
}
}
});
btnLogin.setBounds(160, 209, 97, 41);
panelLogin.add(btnLogin);
textFieldId = new JTextField();
textFieldId.setBounds(112, 88, 205, 43);
panelLogin.add(textFieldId);
textFieldId.setColumns(10);
textFieldId.setHorizontalAlignment(JTextField.CENTER);
JLabel lblId = new JLabel("Enter the business login:");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setBounds(112, 63, 205, 14);
panelLogin.add(lblId);
JLabel lblEnterYourPassword = new JLabel("Enter your password");
lblEnterYourPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterYourPassword.setBounds(148, 142, 139, 14);
panelLogin.add(lblEnterYourPassword);
JPanel panelPizza = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPizza, "name_254741096954780");
}
}
So help would be great.
Thanks very much.
I don't know why creating a second class would be necessary. If you just want the code to look less messy, then add comment separators between Panels or something to that effect. I think that splitting up the Panels into their own classes would be just cause you to have to write more calls to be able to create the same functionality. But if you must, then make a class within your initiate class and work from there.
Simplifying, you want something like:
public class MyMainJFrame extends JFrame{
private JPanel panel1 = new MyFooPanel();
private JPanel panel2 = new MyBarPanel();
public MyMainPanel(){
initialize();
}
void initialize(){
//init the JFrame
this.setTitle("Take Away System Alpha");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new CardLayout(0, 0));
//and add the panels
this.add(panel1);
this.add(panel2);
}
}
// a file for each one
public class MyFooPanel extends JPanel{
private JButton button;
//... add components and logic
}
public class MyBarPanel extends JPanel{
private JTextField field;
//... add components and logic
}
If you want to use specific methods for each custom panel, then change the type of variable for the same name of the custom class.