What I am looking to do is a similar principle to adding attachments to emails, you can click a button and a new browse box would open increasing the number of separate attachments you can have.
I'm fairly new so if someone could point me towards an example?
Sample code to add Buttons on the fly dynamically.
panel.add(new JButton("Button"));
validate();
Full code:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
public class AddComponentOnJFrameAtRuntime extends JFrame implements ActionListener {
JPanel panel;
public AddComponentOnJFrameAtRuntime() {
super("Add component on JFrame at runtime");
setLayout(new BorderLayout());
this.panel = new JPanel();
this.panel.setLayout(new FlowLayout());
add(panel, BorderLayout.CENTER);
JButton button = new JButton("CLICK HERE");
add(button, BorderLayout.SOUTH);
button.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
this.panel.add(new JButton("Button"));
this.panel.revalidate();
validate();
}
public static void main(String[] args) {
AddComponentOnJFrameAtRuntime acojfar = new AddComponentOnJFrameAtRuntime();
}
}
Resource
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
frame.add(new JButton(new AbstractAction("Click to add") {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.add(new JLabel("Bla"));
frame.validate();
frame.repaint();
}
});
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
Component was not visible until setSize() was called:
component.setSize(100,200);
jPanel.add(component);
jPanel.revalidate();
jPanel.repaint();
panel.add(button);
panel.revalidate();
panel.repaint();
Java : Dynamically add swing components
for Example : count=3
//Java Swing: Add Component above method
public void dya_addcomp(int count)
{
//Dynamicaly Delete Image_icon
BufferedImage Drop_Tablefield = null;
try {
Drop_Tablefield = ImageIO.read(this.getClass().getResource("/images/drop.png"));
} catch (IOException ex) {
msg(" Error: drop and edit icon on Table, "+ex);
}
//count Items: 3 times for loop executed..
for(int i=0;i<count;i++)
{
//cnt++;
//lblcount.setText("Count : "+cnt);
JTextField txtcolnm=new JTextField("",20);
JComboBox cmbtype=new JComboBox();
JTextField txtcolsize=new JTextField("",20);
JButton Drop_Table_Field = new JButton(new ImageIcon(Drop_Tablefield));
cmbtype.addItem("INTEGER"); cmbtype.addItem("FLOAT");
cmbtype.addItem("STRING"); cmbtype.addItem("BOOLEAN");
colnamepanel.add(txtcolnm); colnamepanel.add(cmbtype);
colnamepanel.add(txtcolsize); colnamepanel.add(Drop_Table_Field);
colnamepanel.setAutoscrolls(true);
//refresh panel
colnamepanel.revalidate();
colnamepanel.repaint();
//set the layout on Jpanel
colnamepanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0));
}//end for loop
}//end method
Related
I need help with this code, I'm trying to make a simple cookie clicker type game, I have most the code done, but for some reason, when I try to add the JLabel to the frame, it creates an error, I was hoping one of you guys could help me out, I'm fairly new to Java, thanks for the help!
//Variables
static int clicked = 0;
private FlowLayout layout;
private Container container;
public static void main(String [] args) {
//Declaring the buttons, panels, etc...
JButton button = new JButton("Click");
JPanel panel = new JPanel();
panel.add(button);
final JFrame frame = new JFrame("Button Pressed");
frame.setSize(400, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
//Action Listener Code
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
clicked++;
System.out.println("Button pressed " + clicked + " times!");
}
}
}
You can add an JLabel then update its text when button is clicked.
Note: call JFrame.setVisible(true) in the end when all the component is added.
sample code:
// Declaring the buttons, panels, etc...
JButton button = new JButton("Click");
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
clicked++;
label.setText("Button pressed " + clicked + " times!");
}
});
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
final JFrame frame = new JFrame("Button Pressed");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
Find more examples here and here
The basic principle is relatively easy. In order to add something to something else, you first need to have access (or a reference to) the thing you want to add to.
While there are a number of ways you might achieve this, the simplest might be to use an instance/class field. This field would then be accessible from anywhere within the class, for example
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClickTest {
public static void main(String[] args) {
new ClickTest();
}
private JPanel panel;
public ClickTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
//Declaring the buttons, panels, etc...
JButton button = new JButton("Click");
panel = new JPanel();
panel.add(button);
final JFrame frame = new JFrame("Button Pressed");
frame.setSize(400, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(panel);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel.add(new JLabel("You clicked me"));
panel.revalidate();
}
});
}
});
}
}
Take a look at Creating a GUI With JFC/Swing and Understanding Class Members for more details
I'm having a problem trying to change JPanels by using buttons. I have a JFrame with 2 panels, 1 of them is for the buttons, which i want them to always be showed. The other one is the one that i will be switching everytime i press one ot the buttons of the other panel. The problem is that everytime i press them nothing really ever displays, i keep my buttons but the other panel that i call does not appear.
Code for one of the buttons is as follows
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ReparacaoPanel r = new ReparacaoPanel(this, this.jPanel1);
this.getContentPane().remove(this.jPanel1);
this.getContentPane().add(r);
//this.setContentPane(r);
this.visiblePanel.setVisible(false);
this.visiblePanel = r;
this.pack();
this.setVisible(true);
r.setLocation(200, 200);
this.getContentPane().revalidate();
this.repaint();
}
If i try to use "this.setContentPane(r);" (it sets the frame to only show the panel) the panel shows. But when i try to call it as i'm trying to do in the code above nothing is showed apart from the panel that has the buttons.
I have no idea what i'm doing wrong, it does not seem to be a problem with the JPanel that i'm trying to call as it shows if used alone.
Anyone can help me out?
Consider this working example for switching manually between panels. Which produces this output.
.........
Some tiny NumberPanel
Every new instance shows another number in the center.
import javax.swing.JPanel;
public class NumberPanel extends JPanel {
private static int counter = 0;
public NumberPanel() {
setLayout(new BorderLayout(0, 0));
JLabel lblNewLabel = new JLabel("" + counter++);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(lblNewLabel);
}
}
Setting up a frame
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.SOUTH);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().remove(numberPanel);
numberPanel = new NumberPanel();
frame.getContentPane().add(numberPanel, BorderLayout.CENTER);
frame.pack();
}
});
panel.add(btnNewButton);
numberPanel = new NumberPanel();
frame.getContentPane().add(numberPanel, BorderLayout.CENTER);
frame.pack();
}
Testprogram
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestPanelSwitch {
private JFrame frame;
private NumberPanel numberPanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestPanelSwitch window = new TestPanelSwitch();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestPanelSwitch() {
initialize();
}
private void initialize() {
// see above
}
}
Back to the Question
I think you only need to pack your frame, like in the anonymous ActionListener.
frame.getContentPane().remove(numberPanel);
numberPanel = new NumberPanel();
frame.getContentPane().add(numberPanel, BorderLayout.CENTER);
frame.pack();
EDIT
As leonidas mentioned it is also possible to revalidate the frame. This requires only to replace the upper call to pack by theese.
frame.invalidate();
frame.validate();
I am trying to align the Jlabel to left but i'm failing to do it let me know how can i tackle this problem any suggestions regarding this would be greatly appreciated
I have attempted with this slice of code yet it is not solving the problem
Jlabel=new JLabel("Label text",SwingConstants.LEFT);
Jlabel.setHorizontalAlignment(SwingConstants.LEFT);
here is my complete code
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyGui1 extends JPanel implements ActionListener {
/**
*
*/
static JScrollPane jsp;
protected JPanel panel;
protected JTextArea textarea;
static JFrame frame;
JLabel Jlabel=null;
public MyGui1() {
//to lay out the container's components in a rectangular grid
super(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
JButton jbutton=new JButton("button");
jbutton.setActionCommand("button");
jbutton.addActionListener(this);
add(jbutton,c);
c.gridy=1;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
setBackground(Color.cyan);
panel=new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
jsp=new JScrollPane(panel);
jsp.setPreferredSize(new Dimension(300,300));
jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
add(jsp, c);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
public void actionPerformed(ActionEvent evt) {
if("button".equals(evt.getActionCommand())){
execute();
}
}
synchronized public void execute(){
// to remove all the content of panel
panel.removeAll();
// to refresh the window
for(int i=0;i<20 ;i++){
Jlabel=new JLabel("Labe1l"+i,SwingConstants.LEFT);
// Jlabel.setAlignmentX(CENTER_ALIGNMENT);
// Jlabel.setAlignmentY(LEFT_ALIGNMENT);
textarea=new JTextArea();
textarea.setText("sample text");
if(i==2){
textarea.setText("sample text........................\nsample text.................. ");
}
if(i==5){
textarea.setText("sample text.\nsample text.sample text.\nsample text. ");
}
if(i==7){
textarea.setText("sample text.\nsample text.sample text.\nsample text sample text..\nsample text.sample text..\nsample text. ");
}
textarea.append("\n");
textarea.setEditable(false);
Jlabel.setLayout(new BorderLayout());
Jlabel.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(Jlabel);
// in order to wrap up the data in text area
textarea.setLineWrap(true);
panel.add(textarea);
Jlabel.setPreferredSize(new Dimension(240,30));
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// textarea.setPreferredSize(getMinimumSize());
// panel.setPreferredSize(getSize());
panel.revalidate();
panel.repaint();
jsp.getVerticalScrollBar().setValue(0);
jsp.validate();
}
});
}
jsp.revalidate();
jsp.repaint();
frame.repaint();
frame.revalidate();
}
#SuppressWarnings("static-access")
private static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("DesktopSearchEngine");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//adding window listener for exit operation
frame.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
JFrame frame = (JFrame)e.getSource();
int result = JOptionPane.showConfirmDialog(
frame,
"Are you sure you want to exit the application?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else if(result==JOptionPane.NO_OPTION){
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
//Add contents to the window GUI part and to perform all operations
frame.add(new MyGui1());
//Display the window.
frame.pack();
//to keep the frame visible
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You could wrap the label in JPanel with FlowLayout.LEADING
JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.LEADING,0, 0));
wrapper.add(Jlabel);
panel.add(wrapper);
Also remember to follow Java naming convention. variables begin with lower case letters using camel casing: Jlabel → jLabel
I'm having a problem with this. I have a JPanel and normally I would create a JLabel like this:
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 135, 14);
panel.add(lblNewLabel);
but I want each time I click a button, in that panel to be created a new JLabel with the same size, but with a different height possition. I tried:
panel.add(new JLabel(stringName));
but this way I don't get to set it's bounds. stringName I get from a JTextField.
First off, use a layout. Done correctly the layout will place the components like you want. Secondly, when dynamically adding a component to a layout you need to tell the layout to update. Here is an example, it adds a label each time a button is pressed:
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
frame.add(new JButton(new AbstractAction("Click to add") {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.add(new JLabel("Bla"));
frame.validate();
frame.repaint();
}
});
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
frame.setVisible(true);
}
});
}
As said by #AndrewThompson use a correct LayoutManager, you should not be messing with setBounds etc.
Here is an example I made (Simply adds a JLabel to the JPanel each time the JButton is clicked):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test {
public Test() {
createAndShowUI();
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel();
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
int count = 1;
#Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label " + count);//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
count++;
}
});
frame.add(panel, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
Try swapping the order of of your commands, add the panel first then set the location.
I have a Swing window which contains a button a text box and a JLabel named as flag. According to the input after I click the button, the label should change from flag to some value.
How to achieve this in the same window?
Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:
jLabel.setText("new Value");
A simple demo code will be:
JFrame frame = new JFrame("Demo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,100);
final JLabel label = new JLabel("flag");
JButton button = new JButton("Change flag");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("new value");
}
});
frame.add(label, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setVisible(true);
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}