I am trying to implement an image appearing when a button is pressed. For this purpose I thought I could just copy the concept of button 4 (which works) and exchange the System.exit(0) with code to add an image, but while I've been able to use that code elsewhere successfully, here it does not seem to work.
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JSpinner;
import java.awt.Color;
import java.util.ArrayList;
public class Mainframe {
private JFrame frmOceanlife;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe window = new Mainframe();
window.frmOceanlife.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.getContentPane().setLayout(null);
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.setBounds(640, 6, 81, 29);
frmOceanlife.getContentPane().add(btnNewButton_4);
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JButton btnNewButton_5 = new JButton("Einfügen");
btnNewButton_5.setBounds(410, 34, 103, 29);
frmOceanlife.getContentPane().add(btnNewButton_5);
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
// label.setBounds(25,25,50,50);
frmOceanlife.getContentPane().add(label);
}
});
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
lblNewLabel_2.setBounds(6, 539, 334, 16);
frmOceanlife.getContentPane().add(lblNewLabel_2);
}
}
The problem is that you are creating a new JLabel and trying to add it to the frame, once the button is pressed. Instead, you should just change the Icon of the label that is already added to the frame (i.e., piclabel), using piclabel.setIcon(icon);. So, you should declare picLabel at the start of your code, so that it can be accessible in the actionPerformed method of your button.
public class Mainframe {
private JFrame frmOceanlife;
JLabel piclabel;
...
Then, instantiate the label in the initialize() method as below:
...
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
...
Finally, your actionPerformed method for btnNewButton_5 (please consider using descriptive names instead) should look like this:
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
piclabel.setIcon(icon);
}
});
Update
If, however, what you want is to add a new JLabel each time, and not change the icon of the existing one, you could use Box object with BoxLayout added to a ScrollPane. Then add the ScrollPane to your JFrame. Working example is shown below, based on the code you provided (again, please consider using descriptive names and removing unecessary code):
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
public class Mainframe {
private JFrame frmOceanlife;
Box box;
JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe mf = new Mainframe();
mf.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JButton insertBtn = new JButton("Einfügen");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(label);
frmOceanlife.repaint();
frmOceanlife.revalidate();
Rectangle bounds = label.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new image
}
});
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
box = new Box(BoxLayout.Y_AXIS);
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
box.add(piclabel);
scrollPane = new JScrollPane(box);
Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
scrollPane.getViewport().setPreferredSize(dim);
scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height);
scrollPane.getViewport().setBackground(Color.WHITE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(insertBtn);
controlPanel.add(quitBtn);
JLabel titleLbl = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!", SwingConstants.CENTER);
frmOceanlife = new JFrame();
frmOceanlife.getContentPane().add(titleLbl, BorderLayout.NORTH);
frmOceanlife.getContentPane().add(scrollPane, BorderLayout.CENTER);
frmOceanlife.getContentPane().add(controlPanel, BorderLayout.SOUTH);
frmOceanlife.setTitle("OceanLife");
frmOceanlife.pack();
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLocationRelativeTo(null);
frmOceanlife.setVisible(true);
}
}
Here is a sample application demonstrating the use of CardLayout. Note that I used [Eclipse] WindowBuilder. All the below code was generated by WindowBuilder apart from the ActionListener implementations. Also note that the ActionListener implementation for quitButton uses a lambda expression while the insertButton implementation uses a method reference.
More notes after the code.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class MainFram {
private JFrame frame;
private JPanel cardsPanel;
private JPanel firstPanel;
private JLabel firstLabel;
private JPanel secondPanel;
private JLabel secondLabel;
private JPanel buttonsPanel;
private JButton insertButton;
private JButton quitButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFram window = new MainFram();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainFram() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getCardsPanel(), BorderLayout.CENTER);
frame.getContentPane().add(getButtonsPanel(), BorderLayout.SOUTH);
}
private JPanel getCardsPanel() {
if (cardsPanel == null) {
cardsPanel = new JPanel();
cardsPanel.setLayout(new CardLayout(0, 0));
cardsPanel.add(getFirstPanel(), "first");
cardsPanel.add(getSecondPanel(), "second");
}
return cardsPanel;
}
private JPanel getFirstPanel() {
if (firstPanel == null) {
firstPanel = new JPanel();
firstPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
firstPanel.add(getFirstLabel());
}
return firstPanel;
}
private JLabel getFirstLabel() {
if (firstLabel == null) {
firstLabel = new JLabel("");
firstLabel.setIcon(new ImageIcon(getClass().getResource("underwater-600x450.png")));
}
return firstLabel;
}
private JPanel getSecondPanel() {
if (secondPanel == null) {
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
secondPanel.add(getLabel_1());
}
return secondPanel;
}
private JLabel getLabel_1() {
if (secondLabel == null) {
secondLabel = new JLabel("");
secondLabel.setIcon(new ImageIcon(getClass().getResource("Stone.png")));
}
return secondLabel;
}
private JPanel getButtonsPanel() {
if (buttonsPanel == null) {
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
buttonsPanel.add(getInsertButton());
buttonsPanel.add(getQuitButton());
}
return buttonsPanel;
}
private JButton getInsertButton() {
if (insertButton == null) {
insertButton = new JButton("Einfügen");
insertButton.addActionListener(this::insertAction);
}
return insertButton;
}
private JButton getQuitButton() {
if (quitButton == null) {
quitButton = new JButton("Quit");
quitButton.addActionListener(e -> System.exit(0));
}
return quitButton;
}
private void insertAction(ActionEvent event) {
CardLayout cardLayout = (CardLayout) cardsPanel.getLayout();
cardLayout.next(cardsPanel);
}
}
The above code requires that the image files, i.e. underwater-600x450.png and Stone.png, be located in the same directory as file MainFram.class. Refer to How to Use Icons.
When you click on the insertButton, the panel containing the underwater-600x450.png image is hidden and the panel containing the Stone.png image is displayed. Clicking the insertButton a second time will hide Stone.png and display underwater-600x450.png. In other words, clicking the insertButton toggles the images.
The first thing to do is using layout managers instead of setting bounds manually:
import java.awt.*;
import javax.swing.*;
public class Mainframe {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
new Mainframe();
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
//frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frmOceanlife.getContentPane().setLayout(null);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.addActionListener(e -> System.exit(0));
//btnNewButton_4.setBounds(640, 6, 81, 29);
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(btnNewButton_4);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton btnNewButton_5 = new JButton("Insert");
//btnNewButton_5.setBounds(410, 34, 103, 29);
btnNewButton_5.addActionListener(e -> {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
//label.setBounds(25,25,50,50);
stonesPanel.add(label);
frmOceanlife.revalidate();
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(btnNewButton_5);
frmOceanlife.getContentPane().add(insertPanel);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
//panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(700,550));
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
//lblNewLabel_2.setBounds(6, 539, 334, 16);
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(lblNewLabel_2);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
}
Next, let's introduce better names and use publicly available images to make the code more readable and more of an mre:
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
JLabel stoneLbl = new JLabel(icon);
stonesPanel.add(stoneLbl);
frmOceanlife.revalidate();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
JPanel oceanPanel = new JPanel();
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new FlowLayout());
oceanPanel.setPreferredSize(new Dimension(700,550));
try {
JLabel oceanLbl = new JLabel(new ImageIcon(new URL(OCEAN)));
oceanPanel.add(oceanLbl);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
And add some final touchups :
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
private ImageIcon oceanIcon;
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
JLabel stoneLbl = new JLabel();
stonesPanel.add(stoneLbl);
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
stoneLbl.setIcon(icon);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
try {
oceanIcon = new ImageIcon(new URL(OCEAN));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
JLabel oceanLbl = new JLabel();
oceanLbl.setIcon(oceanIcon);
JPanel oceanPanel = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(oceanIcon.getIconWidth()+100, oceanIcon.getIconHeight());
};
};
oceanPanel.add(oceanLbl);
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new GridBagLayout()); //center image in panel
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is "+oceanIcon+oceanIcon.getIconWidth()+
"x"+oceanIcon.getIconHeight()+"!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
Related
I am making an UI in a minecraft plugin. Everything is working, except I have a JPanel and it doesn't fill the whole JFrame. So what I want is the JPanel fill the entire JFrame even if we re-scale the window.
I use Layout manager (FlowLayout) for the JPanel.
I tried using a Layout manager for the JFrame, well it didn't solved my problem because it didn't resize the JPanel.. I tried setting the size of the JPanel to the JFrame's size, but when it's resized it doesn't scale with it.
So, how can I do this?
My plugin creates a button for every player and when I click the button it kicks the player.
My code (I can't really post less because I don't know where I need to change something):
public static JFrame f;
public static JTextField jtf;
public static JPanel jp;
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setLayout(new FlowLayout(FlowLayout.LEFT));
jp.setBackground(Color.GRAY);
jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
jp.add(jtf);f.add(jp, BorderLayout.CENTER);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
Bukkit.getPlayer(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.add(jp, BorderLayout.CENTER);
}
The question should include an mcve reproducing the problem so we can test it.
It could look like this :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setSize(new Dimension(200,200));
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
f.setLayout(null);
f.setSize(500,500);
f.add(jp, BorderLayout.CENTER);
f.setVisible(true);
}
}
To make the JPanel fill the entire frame simply remove this line :
f.setLayout(null);
and let the default BorderLayout manager do its work.
Here is a modified version with some additional comments:
public class Mcve {
private static List<String> players = Arrays.asList(new String[]{"Player A", "Player B"});
public static void main(String[] args) {
creategui();
}
public static void creategui()
{
JPanel jp = new JPanel();
jp.setBackground(Color.GRAY);
JTextField jtf = new JTextField("Reason");
jtf.setPreferredSize(new Dimension(200,20));
jtf.setToolTipText("Write the reason here.");
jp.setPreferredSize(new Dimension(250,200)); // set preferred size rather than size
jp.add(jtf);
for (final String p : players)
{
final JButton b = new JButton();
b.setText(p);
b.setBackground(Color.GREEN);
b.addActionListener(e -> {
if (!b.getBackground().equals(Color.RED))
{
b.setBackground(Color.RED);
}
});
jp.add(b);
}
JFrame f = new JFrame("Players");
//f.setLayout(null); null layouts are bad practice
//f.setSize(500,500); let layout managers set the sizes
f.add(jp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
A 1x1 grid layout does the job quite nicely.
window = new JFrame();
panel = new JPanel();
window.setLayout(new java.awt.GridLayout(1, 1));
window.add(panel);
Either set the layout manager for jp (the JPanel in the code you posted) to BorderLayout and add jtf (the JTextField in the code you posted) to the CENTER of jp, as in:
f = new JFrame();
jp = new JPanel(new BorderLayout());
jtf = new JTextField(30); // number of columns
jp.add(jtf, BorderLayout.CENTER);
f.add(jp, BorderLayout.CENTER);
or dispense with jp and add jtf directly to f (the JFrame in the code you posted), as in:
f = new JFrame();
jtf = new JTextField(30);
f.add(jtf, BorderLayout.CENTER);
The key is that the CENTER component of BorderLayout expands to fill the available space.
So I fixed it somehow, this is the code:
public static void creategui()
{
System.out.println("GUI created.");
f = new JFrame("Players");
jp = new JPanel();
jp.setBackground(Color.GRAY);
jp.setSize(200,200);
jtf = new JTextField(30);
jtf.setToolTipText("Write the reason here.");
jp.add(jtf);
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
getplr(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
jp.add(b);
System.out.println("Button added.");
}
f.setLayout(new BorderLayout());
f.add(jp, BorderLayout.CENTER);
f.setSize(500,500);
f.pack();
f.setVisible(true);
}
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;
}
}
In Class UserInterface I am setting a String (filePath) in JTextField after clicking on the browser button. Now I want to close my window and return the String stored in JTextField to the MainClass that called UserInterface
This is the MainClass
public class MainClass {
public void mainClass(String IDEFilePath) throws IOException
{
UserInterface userInterface = new UserInterface();
String filePath = userInterface.createInterface();
System.out.println(filePath);
}
}
This is the UserInterface Class
package com.mycompany.prototype2;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class UserInterface {
JButton browseButton;
JTextField pathField;
JFrame frame;
String IdeFilePath;
JPanel panel, topPanel, bottomPanel;
UserInterface()
{
// Creating instance of JFrame
frame = new JFrame("Convert IDEJUnit to WebDriver");
// Setting the width and height of frame
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel(new BorderLayout());
topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
bottomPanel = new JPanel(new BorderLayout());
bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(topPanel, BorderLayout.NORTH);
panel.add(bottomPanel, BorderLayout.SOUTH);
}
public String createInterface() {
//Top Panel
JLabel IDEFilePathLabel = new JLabel("IDE File Path", JLabel.CENTER);
pathField = new JTextField(10);
browseButton = new JButton("Browse");
browseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
String defaultDirectoryPath = "C:\\Users\\Parul\\Desktop";
JFileChooser chooser = new JFileChooser(defaultDirectoryPath);
int returnVal = chooser.showOpenDialog(frame);
chooser.setDialogTitle("Select Location");
if (returnVal == JFileChooser.APPROVE_OPTION)
{
java.io.File file = chooser.getSelectedFile();
pathField.setText(chooser.getSelectedFile().toString());
IdeFilePath = pathField.getText();
}
}
});
topPanel.add(IDEFilePathLabel, BorderLayout.WEST);
topPanel.add(pathField, BorderLayout.CENTER);
topPanel.add(browseButton, BorderLayout.EAST);
//Bottom Panel
JButton okButton = new JButton("OK");
bottomPanel.add(okButton, BorderLayout.CENTER);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
frame.add(panel);
frame.setVisible(true);
return IdeFilePath ;
}
}
Add the flollowing code to you MainClass, and make sure to make filePath static,
public static void setString(String text)
{
filePath = text;
}
and call this method from UserInterface like so:
MainClass.setText(pathField.getText());
before the line:
frame.dispose();
As you can see from the image above some of the text is being cut off :(
Code:
package malgm.school.clockui.ui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
import malgm.school.clockui.ClockUI;
import malgm.school.clockui.ResourceLoader;
public class ClockFrame extends JFrame {
private static final long serialVersionUID = 1L;
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 200;
public ClockFrame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
}
public void relocalize() {
//Wipe controls
this.getContentPane().removeAll();
this.setLayout(null);
initComponents();
}
#SuppressWarnings("unused")
private void initComponents() {
setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
speakButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec(ClockUI.dir + "/SpeakingClock.exe");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
FONT: http://www.dafont.com/digital-7.font
Any help will be greatly appreciated
A key to success with Swing layouts is to avoid setLayout(null) and to pack() the enclosing Window. This lets the contained components adopt their preferred sizes, as shown below. To avoid this pitfall, don't invoke setResizable(false).
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/23551260/230513 */
public class ClockFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ClockFrame cf = new ClockFrame();
}
});
}
public ClockFrame() {
setTitle("Clock");
setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
#SuppressWarnings("unused")
private void initComponents() {
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
JLabel time = new JLabel("00:00");
time.setFont(time.getFont().deriveFont(72f));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
After
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
Add time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
After it will look like:
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
change your constructor definition to (EDITED)
public Frame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
setSize(850, 650);
setLocationRelativeTo(null);
setVisible(true);
}
I want to know how to add components dynamically to a JDialog. I know there is a similar question on SO here, but as you can see, I have his solution as a part of my code.
So the idea is that on click of the button, I need to add a component on the dialog. The sample code is below:
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
Test test = new Test();
test.createDialog();
}
public void createDialog() {
DynamicDialog dialog = new DynamicDialog(this);
dialog.setSize(300, 300);
dialog.setVisible(true);
}
}
class DynamicDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
public DynamicDialog(final JFrame owner) {
super(owner, "Dialog Title", Dialog.DEFAULT_MODALITY_TYPE);
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createRigidArea(new Dimension(3, 10)));
panel.add(createLabel("Click on add"));
panel.add(Box.createRigidArea(new Dimension(23, 10)));
panel.add(createLabel("To add another line of text"));
panel.add(Box.createHorizontalGlue());
mainPanel.add(panel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(Box.createHorizontalGlue());
JButton button = new JButton();
button.setText("Add another line");
buttonPanel.add(button);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Container contentPane = owner.getContentPane();
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
contentPane.add(_panel);
contentPane.validate();
contentPane.repaint();
owner.pack();
}
});
pack();
setLocationRelativeTo(owner);
this.add(mainPanel);
}
JLabel createLabel(String name) {
JLabel label = new JLabel(name);
return label;
}
}
If you add it to the main panel it will work, you were adding it to the content pane of the frame which it seems it does not show up anywhere.
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
mainPanel.add(_panel);
mainPanel.validate();
mainPanel.repaint();
owner.pack();
}
})