I have a class of buttons called Keys.java which returns a panel of buttons to the class called Control.java. I have a JLabel in Control.java, but what I want to do is change a JLabel when a button is pressed. How would you go about doing this?
I have tried setting a string in Keys.java which changes based on the button and then setting the JLabel's text equal to the string but it doesn't seem to work.
Any thoughts on how to achieve this?
It may be that you are updating the wrong string or setting the corresponding label's text incorrectly. Both are required. In the example below (using your names), the two updates are tightly coupled in the button's actionPerformed(). A more loosely coupled approach is shown here.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/questions/9053824 */
public class JavaGUI extends JPanel {
private Control control = new Control();
private Keys keys = new Keys("Original starting value.");
public JavaGUI() {
this.setLayout(new GridLayout(0, 1));
this.add(keys);
this.add(control);
}
private class Control extends JPanel {
public Control() {
this.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Command: " + e.getActionCommand());
keys.string = String.valueOf(System.nanoTime());
keys.label.setText(keys.string);
}
}));
}
}
private class Keys extends JPanel {
private String string;
private JLabel label = new JLabel();
public Keys(String s) {
this.string = s;
label.setText(s);
this.add(label);
}
}
private void display() {
JFrame f = new JFrame("JavaGUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JavaGUI().display();
}
});
}
}
Related
I am creating a NotePad app in Java Swing but when I am trying to open a popup to set a title, it is not showing up.
The class that calls the popup:
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class NewFile implements ActionListener{
public static String title;
public void actionPerformed(ActionEvent e){
PopupFileName popup = new PopupFileName();
/*try{
Thread.sleep(30000);
}catch (InterruptedException o){
o.printStackTrace();
}*/
JTextArea titl = popup.title;
title = titl.getText();
try{
File writer = new File(title+".txt");
if(writer.createNewFile()){
System.out.println("file created");
}else{
System.out.println("file exists");
}
}catch (IOException i) {
System.out.println("An error occurred.");
i.printStackTrace();
}
}
}
The popup class that is supposed to open:
import javax.swing.*;
public class PopupFileName{
static JFrame popup = new JFrame("File Title");
static JLabel titlel = new JLabel("Title:");
static public JTextArea title = new JTextArea();
public static void main(String[] args){
popup.setSize(200,300);
popup.setVisible(true);
popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popup.add(titlel);
popup.add(title);
}
}
Is there any way I can make it visible and make it able to get the text before it is created?
Start by taking a look at:
Creating a GUI With Swing
How to Write an Action Listener
How to Use Scroll Panes
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Dialogs
You're running in an event driven environment, this means, something happens and then you respond to it.
The problem with your ActionListener is, it's trying to present a window and then, immediately, trying to get some result from it. The problem is, the window probably isn't even present on the screen yet.
What you need is some way to "stop" the code execution until after the user responds. This is where a modal dialog comes in.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String title = PopupFileName.getTitle(TestPane.this);
System.out.println(title);
}
});
add(btn);
}
}
public static class PopupFileName extends JPanel {
private JLabel titlel = new JLabel("Title:");
private JTextArea title = new JTextArea(20, 40);
public PopupFileName() {
setLayout(new BorderLayout());
add(titlel, BorderLayout.NORTH);
add(new JScrollPane(title));
}
public String getTitle() {
return title.getText();
}
public static String getTitle(Component parent) {
PopupFileName popupFileName = new PopupFileName();
int response = JOptionPane.showConfirmDialog(parent, popupFileName, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
switch (response) {
case JOptionPane.OK_OPTION:
return popupFileName.getTitle();
default: return null;
}
}
}
}
I've a main frame on which there is a side panel with some buttons, and central panel used to display the tables and data generated from buttons on the side panel and its sub-panels
On the start my central panel is blank and I want it to always return to its initial state( blank ) after each click on a button before generating any data
I've use some sort of observer pattern (I'm not so experienced) but my problem is that the central panel must display data after clicks on some buttons that are on panels that also need a click on the side panel before to be generated
I've tried to make an executable example on the following classes, my real application displays some tables on the central panel and i send the models via the update method of the observers
hope its clear for you and I hope if you can really help me
1 - the main frame:
package tests;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame implements MyObserver{
private SidePanel sidePanel;
private JPanel centralPanel;
private JFrame frame;
private JLabel title;
public MainFrame(){
frame = new JFrame("TEST");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
sidePanel = new SidePanel();
sidePanel.addObserver(this);
centralPanel = new JPanel();
title = new JLabel();
initialise(0);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private void initialise(int i) {
if( i == 0){
centralPanel.setPreferredSize(new Dimension(400,300));
centralPanel.setBackground(Color.green);
title.setText("GREEN");
centralPanel.add(title, BorderLayout.CENTER);
frame.add(sidePanel, BorderLayout.WEST);
frame.add(centralPanel, BorderLayout.CENTER);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
#Override
public void update(int color) {
if(color == 0){
centralPanel.setBackground(Color.yellow);
title.setText("YELLOW");
}else{
centralPanel.setBackground(Color.pink);
title.setText("PINK");
}
}
}
2 - The side Panel
package tests;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class SidePanel extends JPanel implements MyObserver,MyObservable{
private JPanel panel;
private JButton test;
private MyObserver observer;
private ButtonPanel buttonPanel;
public SidePanel(){
panel = new JPanel();
panel.setPreferredSize(new Dimension(140, 300));
panel.setBackground(Color.blue);
panel.setLayout(new BoxLayout(panel, 0));
test = new JButton("Lunch buttons");
test.setPreferredSize(new Dimension(80,30));
buttonPanel = new ButtonPanel();
buttonPanel.addObserver(this);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
buttonPanel.setVisible(true);
}
});
panel.add(Box.createVerticalGlue());
panel.add(test);
panel.add(Box.createVerticalGlue());
panel.setVisible(true);
this.add(panel, BorderLayout.CENTER);
}
#Override
public void addObserver(MyObserver obs) {
this.observer = obs;
}
#Override
public void updateObserver(MyObserver obs, int color) {
obs.update(color);
}
#Override
public void update(int color) {
updateObserver(observer, color);
}
}
3 - the buttons panel, generally the source of any data to be displayed on the central panel
package tests;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
public class ButtonPanel extends JDialog implements MyObservable{
private JButton yellow;
private JButton orange;
private JPanel panel;
private MyObserver observer;
public ButtonPanel(){
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 40));
panel.setLayout(new FlowLayout());
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setContentPane(panel);
yellow = new JButton("YELLOW");
yellow.setPreferredSize(new Dimension(100,30));
yellow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
updateObserver(observer, 0);
}
});
orange = new JButton("ORANGE");
orange.setPreferredSize(new Dimension(100,30));
orange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateObserver(observer, 1);
}
});
panel.add(yellow);
panel.add(orange);
pack();
setLocationRelativeTo(null);
}
#Override
public void addObserver(MyObserver obs) {
this.observer = obs;
}
#Override
public void updateObserver(MyObserver obs, int color) {
obs.update(color);
}
}
Finally, the customized observer and observable interfaces, note in the real app i use a table model not just an int - I'm not sure it's a good way -
package tests;
public interface MyObservable {
public void addObserver(MyObserver obs);
public void updateObserver(MyObserver obs, int color);
}
package tests;
public interface MyObserver {
public void update(int color);
}
CHANGED ANSWER:
In SidePanel.java add:
private MainFrame frame;
Then make your constructor take a MyFrame object as parameter. Do this:
public SidePanel(MainFrame frame){
this.frame = frame;
//rest not changed
//
}
Change the actionPerformed() of test button to:
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
buttonPanel.setVisible(true);
frame.initialise(0); // this line is added
}
});
In MainFrame.java:
Change sidePanel = new SidePanel(); to sidePanel = new SidePanel(this);
AND
Change private void initialise(int i) to public void initialise(int i)
This does what you are trying to achieve.
Right now all I have is created the black background and uploaded my image I wanted. I want to make it so the image is behind a transparent background. I initially had this all in separate class files but put them all in one main class
package Flashlight;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Flashlight3 extends JFrame {
public class FlashLabelChange extends JPanel {
Flashlight.FlashDisp flashDisp;
public FlashLabelChange(Flashlight.FlashDisp _flashDisp) {
flashDisp = _flashDisp;
JButton btn1 = new JButton("Start");
add(btn1);
class Button implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Start")) {
flashDisp.UpdateLabel("Start");
}
}
}
ActionListener button = new Button();
btn1.addActionListener(button);
}
}
public class FlashDisp extends JPanel {
private JLabel lblName;
private String sLabel;
private JLabel lblImage;
public FlashDisp() {
lblImage = new JLabel();
add(lblImage);
lblName = new JLabel("Start?");
add(lblName); //add it to the Frame
}
void UpdateLabel(String _sNew) {
sLabel = _sNew;
lblName.setText(sLabel);
}
void UpdateBackground(String _sNew) {
sLabel = _sNew;
if (sLabel == ("Black")) {
setBackground(Color.black);
lblImage.setIcon(new ImageIcon("Hallway.png"));
}
}
}
public class FlashColour extends JPanel {
FlashDisp flashDisp;
public FlashColour(FlashDisp _flashDisp) {
flashDisp = _flashDisp;
setLayout(new GridLayout(3, 1));
JButton btnDark = new JButton("Dark");
add(btnDark);
class ColourChangeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Dark")) {
flashDisp.UpdateBackground("Black");
}
}
}
ActionListener colourChangeListener = new ColourChangeListener();
btnDark.addActionListener(colourChangeListener);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
FlashMain flashMain = new FlashMain();
frame.setSize(400, 400);
frame.setTitle("FLAAAASH LIGHT");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(flashMain);
frame.setVisible(true);
}
}
I think that you need to use the opaque method.
Have a look here
setOpaque(true/false); Java for using opaque.
Hope that helps.
I am trying to make an applet run as a JFrame. The code I have below is simple but should work. It will run as an JApplet but when I go to RUN AS --> nothing appears.
import java.awt.*;
import java.applet.Applet;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LifeCycle extends Applet
{
private static final long serialVersionUID = 1L;
String output = "test";
String event;
public void init()
{
gui(); //I am not certain if this needs to be there.
event = "\nInitializing...";
printOutput();
}
public void start()
{
event = "\nStarting...";
printOutput();
}
public void stop()
{
event = "\nStopping...";
printOutput();
}
public void destroy()
{
event = "\nDestroying...";
printOutput();
}
private void printOutput()
{
System.out.println(event);
output += event;
repaint();
}
private void gui() {
JFrame f = new JFrame("Not resizable");
JPanel d = new JPanel();
// LifeCycle a = new LifeCycle();
// a.init();//not working
d.setLayout(new BorderLayout());
d.add(new JButton("a"));
d.add(new JButton("b"));
d.setBackground(Color.RED);
//f.add(new LifeCycle());
f.add(d);
f.setSize(545,340);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setTitle("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//a.destroy();
}
public void paint(Graphics g)
{
System.out.println("Graphics Paint Method!");
g.drawString(output, 100, 100);
}
public static void main(String[] args) {
LifeCycle l = new LifeCycle();
l.gui();
}
}
I would like to see the code that should be changed, but I cannot seem to find why this will not work. I have added to buttons to the panel to be displayed.
Don't mix AWT (Applet) with Swing components. Stick with just Swing.
Gear your class towards creating JPanels. Then you can place it in a JApplet if you want an applet or a JFrame if you want a JFrame.
Read up on use of BorderLayout -- you're adding multiple components to the default BorderLayout.CENTER position, and only one component, the last one added, will show.
For example ...
LifeCycle2.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
class LifeCycle2 {
private static final int GAP = 5;
private static final int PREF_W = 545;
private static final int PREF_H = 340;
private JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return LifeCycle2.this.getPreferredSize();
}
};
public LifeCycle2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
buttonPanel.add(new JButton("A"));
buttonPanel.add(new JButton("B"));
buttonPanel.setOpaque(false);
JPanel flowLayoutPanel = new JPanel();
flowLayoutPanel.setOpaque(false);
flowLayoutPanel.add(buttonPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.setBackground(Color.red);
mainPanel.add(flowLayoutPanel, BorderLayout.NORTH);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public JComponent getMainPanel() {
return mainPanel;
}
}
Show as a JFrame,
LifeCycleFrame.java
import javax.swing.*;
public class LifeCycleFrame {
private static void createAndShowGui() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
JFrame frame = new JFrame("LifeCycleTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(lifeCycle2.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Show as an applet,
LifeCycleApplet.java
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class LifeCycleApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
LifeCycle2 lifeCycle2 = new LifeCycle2();
getContentPane().add(lifeCycle2.getMainPanel());
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
Add f.setVisible(true); to the end of the gui() method. Without this call your frame won't be shown.
Please read the "How to Make Frames" Tutorial
I have a JFrame containing a JTabbedPane containing a JPanel in a Tab.
In this JPanel, I want a JPopupMenu to show at Mouse Position when clicking the right mouse button.
To do this, I use the show(invoker, x, y) method.
My Problem: The JPopupMenu has a very strange behaviour; sometimes it displays without containing everything (just a grey box) and sometimes it displays in the top left corner of the Panel, behaving completely as expected.
Code:
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
class Testframe extends JFrame {
public static JFrame frame;
private static final long serialVersionUID = 1L;
public Testframe(String string) {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle(string);
setSize(200,200);
setVisible(true);
}
public static void main(String[] args) {
frame = new Testframe("Title");
JTabbedPane tabpane = new JTabbedPane(JTabbedPane.TOP);
tabpane.addTab("title", new TestPanel());
frame.add(tabpane);
tabpane.setVisible(true);
}
}
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
public class TestPanel extends JPanel implements MouseListener {
private static final long serialVersionUID = 1L;
JPopupMenu activeDropdown;
TestPanel() {
setBackground(Color.GREEN);
setVisible(true);
addMouseListener(this);
}
private void dropdown(MouseEvent e) {
activeDropdown = new JPopupMenu();
JMenuItem item = new JMenuItem("Eintrag 0");
activeDropdown.add(item);
activeDropdown.show(Testframe.frame, e.getX(), e.getY());
this.add(activeDropdown);
}
#Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)) {
if (activeDropdown != null)
this.remove(activeDropdown);
dropdown(e);
}
}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
}
If I try to put the JTabbedPane into a separate Class, the JPopupMenu appears anywhere (seems to be a fixed position) on the screen, completely independent from the window position.
Change your dropdown method as below. That should work as expected.
private void dropdown(MouseEvent e) {
activeDropdown = new JPopupMenu();
JMenuItem item = new JMenuItem("Eintrag 0");
activeDropdown.add(item);
this.add(activeDropdown);
activeDropdown.show(this, e.getX(), e.getY());
}
However, I don't understand why you are removing the existing JPopMenu and adding a new one on every right-mouse click.
You can simply use JComponent.setComponentPopupMenu to handle righ-click popup-menus. This is much simpler and will handle all the wiring code for you.
Small example with your code:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class TestPanel extends JPanel {
private static final long serialVersionUID = 1L;
JPopupMenu activeDropdown;
TestPanel() {
setBackground(Color.GREEN);
activeDropdown = new JPopupMenu();
JMenuItem item = new JMenuItem("Eintrag 0");
activeDropdown.add(item);
setComponentPopupMenu(activeDropdown);
}
protected void initUI() {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabpane = new JTabbedPane(JTabbedPane.TOP);
tabpane.addTab("title", this);
frame.add(tabpane);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestPanel().initUI();
}
});
}
}
NB: Avoid using static variables!