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);
}
Related
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
}
}
I am adding dynamic JTextField and JLabel in panel1 but I am not able to set the layout of JTextField and JLabel. I need to add JTextfield and JLabel to panel1 and I add panel1 to panel. I need to add JTextFields and JLabels in a Top-Bottom manner and set layout. panel1 and panel are instances of JPanel.
My code :
public class MakeScrollablePanel extends JFrame implements ActionListener
{
static JButton jButton11,jButton12;
static JPanel panel,panel1;
static JTextField jTextFields;
static JLabel label;
static JComboBox<String> jComboBox;
static Dimension dime,dime1,dime2,dime3,dime4,dime5;
static JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
BoxLayout bx=null;// #jve:decl-index=0:
int count=1,i=0;
public MakeScrollablePanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11);
add(scroll);
dime=new Dimension(600,550);
setSize(dime);
setTitle("Priyank Panel");
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
private void Show()
{
jButton11=new JButton("Add Designation");
panel=new JPanel();
bx=new BoxLayout(panel,BoxLayout.Y_AXIS);
scroll=new JScrollPane(panel);
dime1=new Dimension(500,3000);
dime5=new Dimension(500,450);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230 , 255));
jButton11.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==jButton11)
{
label=new JLabel("Add Designation "+count +" :-");
jTextFields=new JTextField(30);
panel1=new JPanel();
panel1.setBackground(new Color(204, 230 , 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel1.revalidate();
panel.revalidate();
panel.updateUI();
count++;
i++;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}
still not working
still I can't see thre any problem with (depsite fact that there is used BoxLayout instead of GridLayout, but result could be very similair in the case that is used many JTextFields)
.
.
from (little bit) modifyied OPs code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class MakeScrollablePanel extends JFrame implements ActionListener {
private JButton jButton11, jButton12;
private JPanel panel, panel1;
private JTextField jTextFields;
private JLabel label;
private JComboBox<String> jComboBox;
private Dimension dime, dime1, dime2, dime3, dime4, dime5;
private JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
private BoxLayout bx = null;// #jve:decl-index=0:
private int count = 1, i = 0;
public MakeScrollablePanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11, BorderLayout.NORTH);
add(scroll);
setTitle("Priyank Panel");
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
private void Show() {
jButton11 = new JButton("Add Designation");
panel = new JPanel();
bx = new BoxLayout(panel, BoxLayout.Y_AXIS);
scroll = new JScrollPane(panel);
dime5 = new Dimension(500, 150);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230, 255));
jButton11.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton11) {
label = new JLabel("Add Designation " + count + " :-");
jTextFields = new JTextField(30);
panel1 = new JPanel();
panel1.setBackground(new Color(204, 230, 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel.revalidate();
panel.repaint();
count++;
i++;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}
I'm trying to build a dynamic log window (basically a auto-scrolling jtext-area).
The problem I'm having is that although I'm printing 500 lines in the text area, it displays as below:
Below you have my code:
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
public class Main {
private static JFrame mainFrame;
public static void main(String args[]) {
mainFrame = new JFrame();
mainFrame.setSize(500, 500);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ControlPanel cp = new ControlPanel();
mainFrame.add(cp);
mainFrame.setVisible(true);
}
}
class ControlPanel extends JPanel {
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
actionLog.setPreferredSize(new Dimension(500, 300));
actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
pointsLog.setPreferredSize(new Dimension(500, 300));
pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for(int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Hopefully someone with a bit more Swing experience can take the time to point me the right way with this.
Never do this:
actionLog.setPreferredSize(new Dimension(500, 300));
Since by doing this you artificially restrict the size of the JTextArea causing the effect that is currently vexing you. Note also that it's generally a good idea to avoid setting preferred sizes on anything.
Instead set the column and row counts of the JTextARea. This can be done via setter methods or via a simple constructor call: JTextArea myTextArea = new JTextArea(rows, columns);
As an aside: I wonder if a JList will work better for you.
MCVE Example:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class Main2 {
private static void createAndShowGUI() {
JPanel mainPanel = new ControlPanel();
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class ControlPanel extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LOG_COLS = 40;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
// !! actionLog.setPreferredSize(new Dimension(500, 300));
// !! actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setRows(LOG_ROWS); // !!
actionLog.setColumns(LOG_COLS); // !!
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
// !! pointsLog.setPreferredSize(new Dimension(500, 300));
// !! pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setRows(LOG_ROWS); // !!
pointsLog.setColumns(LOG_COLS); // !!
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Edit
Example with nested layouts and JLists:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Main2B {
private static void createAndShowGUI() {
ControlPanel2B controlPanel = new ControlPanel2B();
controlPanel.setBorder(BorderFactory.createEtchedBorder());
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.add(controlPanel, gbc);
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
#SuppressWarnings("serial")
class ControlPanel2B extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LIST_WIDTH = 500;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private DefaultListModel<String> actionLogListModel = new DefaultListModel<>();
private JList<String> actionLogList = new JList<String>(actionLogListModel);
private DefaultListModel<String> pointsLogListModel = new DefaultListModel<>();
private JList<String> pointsLogList = new JList<String>(pointsLogListModel);
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel2B() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
actionLogList.setVisibleRowCount(LOG_ROWS);
pointsLogList.setVisibleRowCount(LOG_ROWS);
actionLogList.setFixedCellWidth(LIST_WIDTH);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
pointsScroll = new JScrollPane(pointsLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLogListModel.addElement("Line: " + i);
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
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();
}
})
I made a small program with two buttons. I label
the buttons one exiting the program and the second importing files.
I actually let them both to exit the program when ever someone pressed on it
the problem is the buttons taking all the window, why?
I tried GridBagConstraints to resize the buttons some how but no luck anyway here's the full class without imports..
public class Window2 extends JFrame{
private static final long serialVersionUID = 1L;
public Window2(){
super ("ALANAZ imagtor");
setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pnl1 = new JPanel(new GridLayout());
JPanel pnl2 = new JPanel();
//button
JButton butn1 = new JButton("EXIT");
JButton butn2 =new JButton("IMPORT");
butn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, "exiting ... bye...");
System.exit(0);
}
});
butn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null, "can't import now exiting");
System.exit(0);
}
});
GridBagConstraints gb1 = new GridBagConstraints();
gb1.insets = new Insets(15,15,15,15);
//Jlabel
JLabel lbl1 = new JLabel("exit or import an image");
pnl1.add(butn1);
pnl1.add(butn2);
pnl2.add(lbl1);
add(pnl2, BorderLayout.SOUTH);
add(pnl1, BorderLayout.CENTER);
}}
You are misusing your layout managers. Your pnl1 JPanel uses GridLayout (without any row or column constants?!), and if you only add one component to it, it will take up the entire JPanel. You seem to have GridBagConstraints in your code, but no GridBagLayout, which is confusing to me.
The solution is to read up on and understand how to use layout managers. Please have a look at the tutorial link: Laying Out Components Within a Container.
Key is to keep remembering that you can nest JPanels within JPanels. For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class Window2 extends JFrame {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 600;
private static final int PREF_H = 400;
public Window2() {
super("ALANAZ imagtor");
setDefaultCloseOperation(EXIT_ON_CLOSE);
int gap = 3;
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, gap, 0));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
JPanel pnl2 = new JPanel();
JButton butn1 = new JButton("EXIT");
JButton butn2 = new JButton("IMPORT");
butn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "exiting ... bye...");
System.exit(0);
}
});
butn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "can't import now exiting");
System.exit(0);
}
});
JLabel lbl1 = new JLabel("exit or import an image");
buttonPanel.add(butn1);
buttonPanel.add(butn2);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(buttonPanel, BorderLayout.SOUTH);
pnl2.add(lbl1);
add(pnl2, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public static void main(String[] args) {
Window2 win2 = new Window2();
win2.pack();
win2.setLocationRelativeTo(null);
win2.setVisible(true);
}
}
If you initialize your panel with a BorderLayout instead, and add your buttons using EAST, NORTH, WEST, SOUTH, you will have a quick fix - however I do also recommend reading up on layout managers
JPanel pnl1 = new JPanel(new BorderLayout());
pnl1.add(new JButton(), BorderLayout.SOUTH);