I have created a JPanel over JFrame and added a JButon and JLabel to the JPanel. But the ActionlListener does not seems work. When i click on JButton, Nothing Happens. Please someone Help me. Thanks in Advance.
Here is my code
public class Trials implements ActionListener {
JButton scoreButton;
JLabel score;
JPanel MyPanel;
int ScoreAmount=0;
public JPanel createPanel()
{
JPanel MyPanel =new JPanel();
MyPanel.setLayout(null);
MyPanel.setSize(50, 50);
MyPanel.setBackground(Color.cyan);
JLabel score =new JLabel(""+ScoreAmount);
score.setSize(50, 50);
score.setLocation(250,50);
score.setForeground(Color.red);
MyPanel.add(score);
JButton scoreButton =new JButton("add");
scoreButton.setSize(100, 50);
scoreButton.setLocation(100,50);
scoreButton.setBackground(Color.red);
scoreButton.addActionListener(this);
MyPanel.add(scoreButton);
MyPanel.setOpaque(true);
MyPanel.setVisible(true);
return MyPanel;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==scoreButton)
{
ScoreAmount = ScoreAmount+1;
score.setText(""+ScoreAmount);
}
}
public static void display()
{
JFrame MyFrame = new JFrame();
Trials tr =new Trials();
MyFrame.setContentPane(tr.createPanel());
MyFrame.setSize(500, 500);
MyFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
display();
}
});
}
}
you shadowing local variables declared for public class Trials implements ActionListener {
JButton scoreButton;
JLabel score;
JPanel MyPanel;
int ScoreAmount=0;
should be in public JPanel createPanel()
MyPanel = new JPanel();
score = new JLabel("" + ScoreAmount);
scoreButton = new JButton("add");
not
JPanel MyPanel = new JPanel();
JLabel score = new JLabel("" + ScoreAmount);
JButton scoreButton = new JButton("add");
remove MyPanel.setLayout(null);, default FlowLayout implemented in JPanel do that by default, then add JComponents to JPanel only MyPanel.add(componentVariable) witout any sizing for JPanels childs
call MyFrame.pack() instead of MyFrame.setSize(500, 500);
When you define your score button you do not assign the class level field, instead you create a new local variable.
JButton scoreButton =new JButton("add");
scoreButton.setSize(100, 50);
scoreButton.setLocation(100,50);
scoreButton.setBackground(Color.red);
scoreButton.addActionListener(this);
MyPanel.add(scoreButton);
Should become:
this.scoreButton =new JButton("add");
scoreButton.setSize(100, 50);
scoreButton.setLocation(100,50);
scoreButton.setBackground(Color.red);
scoreButton.addActionListener(this);
MyPanel.add(scoreButton);
So when the actionPerformed method is called the scoreButton is probably null
Related
I've hit a problem in getting a JPanel to update.
My simple program uses a custom JPanel which displays a label and a textfield. A Jbutton on the main panel is used to replace the JPanel with a new JPanel. The initial panel shows up fine but when the button is pressed the panel is not updated with a new MyPanel. I can tell that a new object is being created as count is being incremented.
public class SwingTest extends JFrame{
private JPanel mp;
private JPanel vp;
private JButton button;
public static void main(String[] args) {
SwingTest st = new SwingTest();
}
public SwingTest() {
vp = new MyPanel();
mp = new JPanel(new BorderLayout());
mp.add(vp, BorderLayout.CENTER);
button = new JButton("Change");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
vp = new MyPanel();
vp.revalidate();
}
});
mp.add(button, BorderLayout.SOUTH);
this.add(mp);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(250, 150);
pack();
setVisible(true);
}
}
and my custom panel....
public class MyPanel extends JPanel{
private JLabel label;
private JTextField tf;
static int count = 0;
public MyPanel(){
count++;
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setPreferredSize(new Dimension(400, 200));
c.gridx = 0;
c.gridy = 0;
label = new JLabel(String.valueOf(count));
tf = new JTextField(10);
add(label,c);
c.gridx = 1;
add(tf, c);
}
}
You state:
A Jbutton on the main panel is used to replace the JPanel with a new JPanel.
And yet this code:
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
vp = new MyPanel();
vp.revalidate();
}
});
and yet this code does not do this at all. All it does is change the JPanel referenced by the vp variable, but has absolutely no effect on the JPanel that is being displayed by the GUI, which suggests that you're confusing reference variable with reference or object. To change the JPanel that is displayed, you must do exactly this: add the new JPanel into the container JPanel into the BorderLayout.CENTER (default) position, then call revalidate() and repaint() on the container.
e.g.,
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
// vp = new MyPanel();
// vp.revalidate();
mp.remove(vp); // remove the original MyPanel from the GUI
vp = new MyPanel(); // create a new one
mp.add(vp, BorderLayout.CENTER); // add it to the container
// ask the container to layout and display the new component
mp.revalidate();
mp.repaint();
}
});
Or better still -- use a CardLayout to swap views.
Or better still -- simply clear the value held by the JTextField.
For more on the distinction between reference variable and object, please check out Jon Skeet's answer to this question: What is the difference between a variable, object, and reference?
I have a GUI class which contains a JButton:
public class GUI {
static JFrame mainFrame;
static JLabel headerLabel;
static JLabel statusLabel;
static JPanel controlPanel;
static JButton sub;
public GUI(){
prepareGUI();
}
public static void prepareGUI(){
mainFrame = new JFrame("Service 2 - Evaluate Sensor Values");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
sub = new JButton("Send Subscribe to Service 1");
showButtonDemo();
mainFrame.setVisible(true);
}
public static void showButtonDemo(){
headerLabel.setText("Configuration Phase");
headerLabel.setFont(new Font("Serif", Font.PLAIN, 14));
sub.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Monitor.createWaterSubscriptionResources();
Monitor.createTemperatureSubscriptionResources();
}
});
controlPanel.add(sub);
mainFrame.setVisible(true);
}
}
In other class, I will process something, and when the process done, I would like to disable the button in the GUI class, something like:GUI.sub.setEnabled(false). How can I do that?
Thank you in advanced!
In your other class event, you call Frame.getFrames() that returns an array of all frames. Then you get your GUI frame and call GUI.sub.setEnabled(false)
You should put a getter method for your JButton in the Gui class, Like this:
public static JButton getSubButton(){
return this.sub;
}
and to disable the Button from another class you do this:
Gui.getsubButton().setEnabled(false);
There are no errors in the code but i cant seem to see the Jlabels in the window. Im not sure if the panel was added or if the jlabels were added to the panel .
public class JDemoResistance extends JFrame{
private final JButton button1;
private JPanel panel;
private final int WINDOW_WIDTH = 320;
private final int WINDOW_HEIGHT = 320;
public JDemoResistance() {
super("JDemoResistance");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JLabels Configs
JLabel label1 = new JLabel("Too expensive");
JLabel label2 = new JLabel("Bad reviews");
JLabel label3 = new JLabel("Bad quality");
JLabel label4 = new JLabel("Not worth it");
JLabel label5 = new JLabel("Dosent work");
//Button Configs
button1 = new JButton("Button");
button1.addActionListener(new ButtonListener());
//Panel Configs
panel = new JPanel();
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(button1);
setVisible(true);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
}
}
public static void main(String[] args) {
JDemoResistance jdr = new JDemoResistance();
}
}
You haven't added the panel to the frame, that's why you can't see any of the components. Add it before setting the JFrame visible.
//Add the panel to the frame
this.add(panel)
setVisible(true);
You must add the panel to the JFrame as well.
panel.add(...);
add(panel); // <-- you forgot this
setVisible(true);
I create two jbuttons in one panel(can be Box).i create same panel dynamically several times in same frame.so if two panels created dynamically those button make with same variable name.But i want to identify buttons one by one for put actions.how to identify dynamically created buttons one by one?
button creating code
public class Jscrollpanetest extends JFrame {
JScrollPane scrollPane;
Box box;
private static int panelCount = 0;
public Jscrollpanetest() {
setPreferredSize(new Dimension(200, 400));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(15);
box = Box.createVerticalBox();
scrollPane.getViewport().add(box);
this.add(scrollPane);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
box.add(new TestPanel(), box.size());
scrollPane.validate();
}
});
t.setRepeats(true);
t.start();
}
public class TestPanel extends JPanel {
int myId = panelCount++;
public TestPanel() {
this.setLayout(new GridBagLayout());
this.setBorder(BorderFactory.createBevelBorder(1));
JButton up = new JButton("^");
JLabel rate = new JLabel("1");
JButton down = new JButton("^");
JLabel label = new JLabel("" + myId);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
this.setMaximumSize(new Dimension(1000, 200));
this.setPreferredSize(new Dimension(1000, 100));
this.add(label);
this.add(up);
this.add(rate);
this.add(down);
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Jscrollpanetest testScrollPane = new Jscrollpanetest();
}
});
}
}
If use and dynamic created ActionListener there will be no problem. So each button will have its own ActionListener.
If using a common ActionListener must add tags to each button as extend JButton.
This is the JPanel
public class DisplayBoard {
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//The main panel
JPanel main = new JPanel();
main.setPreferredSize(new Dimension(600,800) );
main.setLayout(new BorderLayout());
//The title panel
JPanel title = new JPanel();
title.setPreferredSize(new Dimension(400, 120));
title.setBackground(Color.YELLOW);
JLabel test1 = new JLabel("Title goes here");
title.add(test1);
//The side bar panel
JPanel sidebar = new JPanel();
sidebar.setPreferredSize(new Dimension(200, 800));
sidebar.add(AddSubtract);
sidebar.setBackground(Color.GREEN);
JLabel test2 = new JLabel("Sidebar goes here");
sidebar.add(test2);
//The panel that displays all the cards
JPanel cardBoard = new JPanel();
cardBoard.setPreferredSize(new Dimension(400,640) );
//adding panels to the main panel
main.add(cardBoard, BorderLayout.CENTER);
main.add(title, BorderLayout.NORTH);
main.add(sidebar, BorderLayout.WEST);
frame.setContentPane(main);
frame.pack();
frame.setVisible(true);
}
}
and I want to add this class into the sidebar panel
public class AddSubtract {
int Number = 0;
private JFrame Frame = new JFrame("Math");
private JPanel ContentPane = new JPanel();
private JButton Button1 = new JButton("Add");
private JButton Button2 = new JButton("Subtract");
private JLabel Num = new JLabel ("Number: " + Integer.toString (Number));
public AddSubtract() {
Frame.setContentPane(ContentPane);
ContentPane.add(Button1);
ContentPane.add(Button2);
ContentPane.add(Num);
Button1.addActionListener(new Adding());
Button2.addActionListener(new Subtracting());
}
public class Adding implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number++;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public class Subtracting implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number--;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public void launchFrame(){
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.pack();
Frame.setVisible(true);
}
public static void main(String args[]){
AddSubtract Test = new AddSubtract();
Test.launchFrame();
}
}
Can someone explain to me how I can do this ?
I have a feeling that this is not going to work, but I really want to learn the way to do it.
This definately is not going to work. For starters, you have two main() methods. Second, if you want to add a class to your Frame, it should extend from JComponent. Basically, your code should look like this:
public class MainFrame extends JFrame {
public MainFrame() {
this.add(new MainPanel())
//insert all settings here.
}
}
public class MainPanel extends JPanel {
public MainPanel() {
this.add(new AddSubtract());
this.add(/*more panels*/)
}
}
public class AddSubtract extends JPanel {
public AddSubtract() {
//add buttons and stuff here
}
}
and variables do NOT start with capitals.
Edit: And when you have some JFrame, it's usually best to have a main() method with just one line:
public static void main(String[] args) {
new MainFrame();
}
just set the settings and configuration of the JFrame in the constructor.