Change button's text with an external combobox java - java

I've two class. Can i change a text of a button in a class "home" with an actionlistener of the combobox in a class "panelGestisciImpianti"? I don't unterstand becasue don't works.
The code is this:
//home
package s;
public class home extends JFrame {
private JPanel contentPane;
private panelImpostazioni panel5= new panelImpostazioni();
private JButton btnImpostazioni = new JButton("no"); //$NON-NLS-1$
public static void main(String[] args) {
home frame = new home();
frame.setVisible(true);
}
public home() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState( JFrame.MAXIMIZED_BOTH) ;
setBounds(0, 0, 1963, 688);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
btnImpostazioni.setBounds(0, 560, 140, 140);
contentPane.add(btnImpostazioni);
btnImpostazioni.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.add(panel5);
revalidate();
repaint();
}
});
}
public void changetext() {
btnImpostazioni.setText("yes");
}
}
//panelGestisciImpostazioni
package s;
public class panelImpostazioni extends JPanel {
private JComboBox comboboxLingua = new JComboBox();
static home h=new home();
public panelImpostazioni() {
setBounds(140, 0, 800, 560);
setLayout(null);
comboboxLingua.setBounds(100, 24, 150, 45);
comboboxLingua.setModel(new DefaultComboBoxModel(new String[] {"italiano", "inglese"}));
add(comboboxLingua);
comboboxLingua.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
h.changetext();
}
});
}
}
Thank you.

Its because when you create panel5 you have a new home created.
static home h = new home ().
So when you call changetext method you do it in a new invisible frame.
In order to make this work (it is really really bad) you have to pass your visible "home" as an argument to your panel5. Which means you have to initiate it in home's constructor and not as a field.
public panelImpostazioni(home h)
And in your combobox action listener
h.changetext ()

Related

Java : Can't display JPanel above a JLabel with image

here's my problem : I display an ArrayList of JLabel with image and a JPanel with buttons inside a JPanel and I want to display my JPanel above my JLabel when I press a button. But when I press the button, my JPanel is under the JLabels.
Please don't tell me to use a JLayerPane cause if I can do without it it would be best.
Thanks for your solutions.
Here's an exemple of my code :
To run this put the image 100x100 found here :
http://www.html5gamedevs.com/topic/32190-image-very-large-when-using-the-dragging-example/
in a file named image
Main :
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("test");
frame.setSize(900,700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanelControler ctrl = new JPanelControler();
frame.add(ctrl.getMyJpanel());
frame.setVisible(true);
}
}
MyJPanelControler :
public class JPanelControler {
private MyJPanel myJpanel;
public JPanelControler() {
myJpanel = new MyJPanel();
myJpanel.createJLabel();
myJpanel.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myJpanel.displayJPanel();
}
});
}
public MyJPanel getMyJpanel() {
return myJpanel;
}
}
MyJPanel :
public class MyJPanel extends JPanel {
private JButton button;
private ArrayList<JLabel> labels;
//a JPanel that contains buttons,... I won't put this class here
private JPanel panel;
public MyJPanel() {
setLayout(null);
button = new JButton("X");
button.setBounds(600,600,50,50);
add(button);
}
public void createJLabel() {
labels = new ArrayList<>();
JLabel label;
try {
BufferedImage image = ImageIO.read(new File("images/image.jpg"));
for(int i=0; i<2; i++) {
label = new JLabel(new ImageIcon(image));
label.setBounds(i*100,50,image.getWidth(), image.getHeight());
labels.add(label);
add(label);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayJPanel() {
panel = new JPanel();
panel.setLayout(null);
JButton b = new JButton("Ok");
b.setBounds(0,0,100, 50);
JButton b2 = new JButton("Cancel");
b2.setBounds(0,50,100, 50);
panel.setBounds(150,50, 100, 100);
panel.add(b);
panel.add(b2);
add(panel);
refresh();
}
public void refresh() {
invalidate();
revalidate();
repaint();
}
public JButton getButton() {return this.button; }
}
If you want the buttons to appear over plain images, then you have one of two options:
Draw the images in a paintComponent override in the main JPanel and not as ImageIcons within a JLabel. This will allow you to add components to this same JPanel, including buttons and such, and the images will remain in the background. If you go this route, be sure to call the super.paintComponent(g); method first thing in your override.
Or you could use a JLayeredPane (regardless of your not wanting to do this). You would simply put the background JPanel into the JLayeredPane.DEFAULT_LAYER, the bottom layer (constant is Integer 0), and place the newly displayed JButton Panel in the JLayeredPane.PALETTE_LAYER, which us just above the default. If you go this route, be sure that the added JPanel is not opaque, else it will cover over all images completely.
For an example of the 2nd suggestion, please see below:
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
public class JPanelControler {
private MyJPanel myJpanel;
public JPanelControler() {
myJpanel = new MyJPanel();
myJpanel.createJLabel();
myJpanel.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myJpanel.displayJPanel();
}
});
}
public MyJPanel getMyJpanel() {
return myJpanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("test");
frame.setSize(900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanelControler ctrl = new JPanelControler();
frame.add(ctrl.getMyJpanel());
frame.setVisible(true);
}
}
class MyJPanel extends JLayeredPane {
private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia"
+ "/commons/thumb/f/fc/Gros_Perr%C3%A9.jpg/100px-Gros_Perr%C3%A9.jpg";
private JButton button;
private ArrayList<JLabel> labels;
// a JPanel that contains buttons,... I won't put this class here
private JPanel panel;
public MyJPanel() {
setLayout(null);
button = new JButton("X");
button.setBounds(600, 600, 50, 50);
add(button, JLayeredPane.DEFAULT_LAYER); // add to the bottom
}
public void createJLabel() {
labels = new ArrayList<>();
JLabel label;
try {
URL imgUrl = new URL(IMG_PATH); // ** added to make program work for all
BufferedImage image = ImageIO.read(imgUrl);
for (int i = 0; i < 2; i++) {
label = new JLabel(new ImageIcon(image));
label.setBounds(i * 100, 50, image.getWidth(), image.getHeight());
labels.add(label);
add(label);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayJPanel() {
panel = new JPanel();
panel.setLayout(null);
panel.setOpaque(false); // ** make sure can see through
JButton b = new JButton("Ok");
b.setBounds(0, 0, 100, 50);
JButton b2 = new JButton("Cancel");
b2.setBounds(0, 50, 100, 50);
panel.setBounds(150, 50, 100, 100);
panel.add(b);
panel.add(b2);
add(panel, JLayeredPane.PALETTE_LAYER); // add it above the default layer
refresh();
}
public void refresh() {
// invalidate(); // not needed
revalidate();
repaint();
}
public JButton getButton() {
return this.button;
}
}

A basic logic issue whilst using setters and getters with Swing

Im writing a basic program to simulate a conversation between a user and the computer. I am trying to use a setter and getter to change the text in a textField in another class. The button is clicked and nothing appears in the textField. here is my code:
public class DialogueWindow extends JFrame {
SuperDialogue SD = new SuperDialogue();
JTextField textField = new JTextField();
JButton Answer1 = new JButton();
public DialogueWindow() {
initUI();
}
public void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton Answer1 = new JButton();
Answer1.setBounds(102, 149, 113, 30);
Answer1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textField.setText(SD.getReply1());
}
});
panel.add(Answer1);
textField = new JTextField();
textField.setBounds(56, 74, 174, 45);
panel.add(textField);
setTitle("Dialogue");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class SuperDialogue {
private String answer;
public String getReply1(){
return this.answer;
}
public void setReply1(String a1){
this.answer = a1;
}
}
public class Conversation1 extends SuperDialogue {
public void Convo(){
String firstLine = "hello";
setReply1(firstLine);
DialogueWindow DW = new DialogueWindow();
DW.setVisible(true);
DW.setSize(300,300);
}
}
public class Main {
public static void main(String[] args) {
Conversation1 c1 = new Conversation1();
c1.Convo();
}
}
The SuperDialogue in your JFrame class is not the same as the one created in your main.
SuperDialogue SD = new SuperDialogue();
This line is creating a separate SuperDialog which does not has the same values. This one is never set, so getReply1() returns nothing.

How to add an JPanel from an other class to an existing Frame

I have my MainWindow class where menue buttons and everything else are. In the middle of it is an Panel called content. I want to load JPanels from other classes into this field. But when i start the code below nothing shows up.
MainWindow Class:
public class MainWindow {
private JFrame frame;
private JScrollPane Content;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel TopPanel = new JPanel();
scrollPane.setColumnHeaderView(TopPanel);
JLabel lblNewLabel = new JLabel("Made by " + Globals.Author);
TopPanel.add(lblNewLabel);
JButton btnHome = new JButton("Home");
TopPanel.add(btnHome);
btnHome.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Content.add(new Home());
}
});
Content = new JScrollPane();
scrollPane.setViewportView(Content);
}
}
JPanel Class:
public class Home extends JPanelContentTemplate {
/**
* Create the panel.
*/
protected void InitializeComponents(){
setLayout(new BorderLayout(0, 0));
JPanel OptionsMenuePanel = new JPanel();
add(OptionsMenuePanel, BorderLayout.WEST);
JPanel ConentPanel = new JPanel();
add(ConentPanel, BorderLayout.CENTER);
ConentPanel.setLayout(new GridLayout(1, 2, 0, 0));
JLabel lblConnectedWith = new JLabel("Connected With:");
ConentPanel.add(lblConnectedWith);
JTextPane textServerIP = new JTextPane();
ConentPanel.add(textServerIP);
}
#Override
protected void Refresh() {
// TODO Auto-generated method stub
}
}
The InitializeComponents method comes from an Self Created Superclass:
public abstract class JPanelContentTemplate extends JPanel {
/**
* Create the panel.
*/
public JPanelContentTemplate() {
InitializeComponents();
}
protected abstract void InitializeComponents();
protected abstract void Refresh();
}
I also tried an repaint etc.
Thanks for Help
Nothing shows up because you add nothing but empty JScrollPanes to your GUI:
Content = new JScrollPane();
scrollPane.setViewportView(Content);
Here is a simple example of adding separate panels to the MainFrame. I hope it helps you.
public class SidePanel extends JPanel {
private JLabel label;
public SidePanel() {
setBorder(BorderFactory.createEtchedBorder());
label = new JLabel("Hello");
setVisible(true);
/* More Code Goes Here */
}
}
public class CenterPanel extends JPanel {
/* Center Panel Code */
}
public class MainFrame extends JFrame {
private SidePanel sidePanel;
private CenterPanel centerPanel;
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
sidePanel = new SidePanel();
centerPanel = new CenterPanel();
add(sidePanel, BorderLayout.WEST);
add(centerPanel, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
}
}
/* Main App */
public static void main(String [] args) {
try {
/* Lambda Expression */
SwingUtitlities.InvokeLater(() -> new MainFrame());
} catch(Exception ex) {
ex.printStackTrace();
}
}

Use If-Else statement in SubmitListener

Trying to develop a GUI, but I've hit a snag:
I am using a submit button, which will look at a txtEnter field. If the user types "yes" in the txtEnter field and clicks submit, it will execute a shell script. If the user types "no" there will be no action. I know the command to run shell script is Runtime.getRuntime().exec(myShellScript);
How I can use an if-else statement in the SubmitListner to check for the user's input?
import javax.swing.*; import javax.swing.event.DocumentListener;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Executer private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious, btSubmit;
private JPanel panel;
public static void main(String[] args) {
new Executer();
}
public Executer() {
JFrame frame = new JFrame("Script Executer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
frame.setVisible(true);
myPanel();
Text();
Fields();
Buttons();
frame.add(panel);
frame.setVisible(true);
}
public void myPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void Text(){
lblCommand = new JLabel("Enter Here");
lblCommand.setBounds(145, 100, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblCommand.setFont(styleOne);
panel.add(lblCommand);
}
public void Fields () {
txtEnter = new JTextField();
txtEnter.setBounds(230, 100, 120, 20);
panel.add(txtEnter);
}
public void Buttons() {
btNext = new JButton ("Next");
btNext.setBounds(300,215,100,20);
panel.add(btNext);
btPrevious = new JButton ("Previous");
btPrevious.setBounds(190,215,100,20);
panel.add(btPrevious);
btSubmit = new JButton("Submit");
btSubmit.setBounds(80,215,100,20);
panel.add(btSubmit);
}
class SubmitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
}}}
You have to assign your Actionlistener to your button:
btSubmit = new JButton();
btSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// here the click happend so you can check your Textfield
String userEntered = txtEnter.getText();
if(userEntered.equalsIgnoreCase("yes"))
{
//run your script
}
}
});

Java: Position JButtons in JFrame/JPanel

Hi I made some buttons align nicely next to each other but now I want them at the bottom of my panel/frame.
How can I do this? I thought about setalignment but that doesn't seem to work.
Thanks in advance:
public class mainMenu extends JFrame {
private JButton start, highscore, help, stoppen;
public mainMenu() {
super("Master Mind");
maakComponenten();
maakLayout();
toonFrame();
}
private void maakComponenten() {
start = new JButton("Start") {
{
setSize(150, 30);
setMaximumSize(getSize());
}
};
highscore = new JButton("Highscore") {
{
setSize(150, 30);
setMaximumSize(getSize());
}
};
help = new JButton("Help") {
{
setSize(150, 30);
setMaximumSize(getSize());
}
};
stoppen = new JButton("Stoppen") {
{
setSize(150, 30);
setMaximumSize(getSize());
}
};
}
private void maakLayout() {
JPanel hoofdmenu = new JPanel();
hoofdmenu.setLayout(new BoxLayout(hoofdmenu, BoxLayout.X_AXIS));
hoofdmenu.add(start);
hoofdmenu.add(highscore);
hoofdmenu.add(help);
hoofdmenu.add(stoppen);
super.add(hoofdmenu);
}
private void toonFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(500, 500);
}
public static void main(String[] args) {
new mainMenu();
}
}
A common approach is to make a JPanel with a LayoutManager of BorderLayout. You would put all of the contents of the panel (which could be a collection of subpanels) in BorderLayout.CENTER, and put the panel containing just your buttons in BorderLayout.SOUTH.
See: How to Use Layouts
and How To Use BorderLayout

Categories