SO I have this Test Client which will run the program and i want this class to populate a JTable in a JPanel class named StartScreenPlayerPanel.
I've tried several methods which failed.
TestClient Class
import view.MainFrame;
import view.StartScreenPlayerPanel;
public class TestClientGUI {
private static final Logger logger = Logger.getLogger(SimpleTestClientGUI.class.getName());
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
MainFrame mainframe;
StartScreenPlayerPanel startScreenPlayerPanel;
public static void main(String args[]) {
final GameEngine gameEngine = new GameEngineImpl();
//GUI - new MainFrame
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
The Class with the JTable - "StartScreenPlayerPanel"
public class StartScreenPlayerPanel extends JPanel {
MainFrame mainframe;
//private JTable table;
private DefaultTableModel model = new DefaultTableModel();
public StartScreenPlayerPanel() {
setLayout(new BorderLayout());
JTable table = new JTable(model);
table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 16));
model.addColumn("Player");
model.addColumn("Initial Points");
//model.addRow(new Object[]{"v1", "v2"});
add(table.getTableHeader(), BorderLayout.NORTH);
add(table, BorderLayout.CENTER);
}
public void setModel(String c1, String c2) {
model.addRow(new Object[]{c1, c2});
model.fireTableDataChanged();
}
public DefaultTableModel getModel() {
return this.model;
}
}
What I tried So far ;
//Add players to GUI
StartScreenPlayerPanel startScreenPlayerPanel = new StartScreenPlayerPanel();
startScreenPlayerPanel.setModel("CoinMaster","TheLoser");
startScreenPlayerPanel.getModel().addRow(new Object[]{"CoinMaster", "TheLoser"});
startScreenPlayerPanel.getModel().setValueAt("TheLoser", 2, 2);
Nothing I tried worked, except doing it in the same class
Thanks For your help.
Edit - Added code for MainFrame:
public class MainFrame extends JFrame {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private StartScreenPlayerPanel startScreenPlayerPanel;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
System.out.println(screenSize);
frame.setMinimumSize(new Dimension(screenSize.width/2, screenSize.height/2));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
startScreenPlayerPanel = new StartScreenPlayerPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, (screenSize.width * 2 / 3), (screenSize.height * 2 / 3));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{1200, 0};
gbl_contentPane.rowHeights = new int[]{74, 0, 446, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblTitle = new JLabel("The Coin Game",SwingConstants.CENTER);
lblTitle.setFont(new Font("Arial", Font.PLAIN, (int)screenSize.width/30));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.gridwidth = 2;
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.anchor = GridBagConstraints.NORTH;
gbc_lblTitle.fill = GridBagConstraints.HORIZONTAL;
gbc_lblTitle.gridx = 0;
gbc_lblTitle.gridy = 0;
contentPane.add(lblTitle, gbc_lblTitle);
JPanel StartScreenBtnPanel = new JPanel();
GridBagConstraints gbc_StartScreenBtnPanel = new GridBagConstraints();
gbc_StartScreenBtnPanel.gridwidth = 0;
gbc_StartScreenBtnPanel.insets = new Insets(0, 0, 5, 0);
gbc_StartScreenBtnPanel.fill = GridBagConstraints.BOTH;
gbc_StartScreenBtnPanel.gridx = 0;
gbc_StartScreenBtnPanel.gridy = 1;
contentPane.add(StartScreenBtnPanel, gbc_StartScreenBtnPanel);
StartScreenBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnAddPlayer = new JButton("Add Player");
btnAddPlayer.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnAddPlayer);
JButton btnStartGame = new JButton("Start Game");
btnStartGame.setFont(new Font("Tahoma", Font.PLAIN, 16));
StartScreenBtnPanel.add(btnStartGame);
GridBagConstraints gbc_playerPanel = new GridBagConstraints();
gbc_playerPanel.gridwidth = 2;
gbc_playerPanel.insets = new Insets(0, 0, 5, 0);
gbc_playerPanel.fill = GridBagConstraints.BOTH;
gbc_playerPanel.gridx = 0;
gbc_playerPanel.gridy = 2;
contentPane.add(startScreenPlayerPanel, gbc_playerPanel);
}
public StartScreenPlayerPanel getStartScreenPlayerPanel() {
return startScreenPlayerPanel;
}
}
Related
My JTextField isn't showing on, only the paintComponent
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
private JTextField txt;
public Painel(){
super();
setFocusable(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setLayout(new FlowLayout());
txt = new JTextField();
txt.setBounds(400, 300, 50, 20);
}
You have to set the number of columns in your text field or give a default text to it. The following code should work for you. I have updated the previous answer to use the Gridbag layout. However still you need to set the number of columns in JTextField to render it.
public class TestFrame extends JFrame {
public static void main(String[] args) {
new TestFrame();
}
private TestFrame() throws HeadlessException {
super();
this.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 100, 0 };
gbl_contentPane.rowHeights = new int[] { 0, 0, 0 };
gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
contentPane.setLayout(gbl_contentPane);
JTextField textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(textField, gbc_textField);
textField.setColumns(10);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
Hope this helps. Happy coding !
I am trying to get some Java skills back because i worked for a long time in webdevelopment. Now I am just create a main Jframe where are a little Menu and a Class createSchueler extends JPanel.
So what I want to do if you go into the Menu click Neu > Schueler
A new Jpanel should be created and added to the Window
Main Class
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 807, 541);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel createSchueler = new createSchueler();
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Neu");
mnNewMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
createSchueler.setVisible(true);
frame.getContentPane().add(createSchueler);
}
});
menuBar.add(mnNewMenu);
JMenuItem mntmSchler = new JMenuItem("Sch\u00FCler");
mnNewMenu.add(mntmSchler);
JMenu mnBearbeiten = new JMenu("Bearbeiten");
menuBar.add(mnBearbeiten);
JMenuItem mntmSchler_1 = new JMenuItem("Sch\u00FCler");
mnBearbeiten.add(mntmSchler_1);
}
}
The createSchueler Class extends JPanel that i want to add to the frame
public class createSchueler extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Create the panel.
*/
public createSchueler() {
setLayout(null);
JLabel lblNeuenSchuelerErstellen = new JLabel("Neuen Schueler erstellen");
lblNeuenSchuelerErstellen.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblNeuenSchuelerErstellen.setBounds(29, 27, 268, 27);
add(lblNeuenSchuelerErstellen);
JLabel lblVorname = new JLabel("Vorname");
lblVorname.setBounds(29, 102, 46, 14);
add(lblVorname);
textField = new JTextField();
textField.setBounds(97, 99, 172, 20);
add(textField);
textField.setColumns(10);
JLabel lblNachname = new JLabel("Nachname");
lblNachname.setBounds(29, 133, 69, 14);
add(lblNachname);
textField_1 = new JTextField();
textField_1.setBounds(97, 130, 172, 20);
add(textField_1);
textField_1.setColumns(10);
JLabel lblGeburtstag = new JLabel("Geburtstag");
lblGeburtstag.setBounds(29, 169, 69, 14);
add(lblGeburtstag);
textField_2 = new JTextField();
textField_2.setBounds(97, 166, 172, 20);
add(textField_2);
textField_2.setColumns(10);
ButtonGroup bg = new ButtonGroup();
JRadioButton rdbtnMnnlich = new JRadioButton("M\u00E4nnlich");
rdbtnMnnlich.setBounds(29, 206, 69, 23);
bg.add(rdbtnMnnlich);
JRadioButton rdbtnWeiblich = new JRadioButton("Weiblich");
rdbtnWeiblich.setBounds(97, 206, 109, 23);
bg.add(rdbtnWeiblich);
}
}
Everything is important hopefully :D
Use a CardLayout to swap JPanels rather than adding them by hand. If you must add them by hand, be sure that the receiving container's layout manager is up to the task and handles the addition well. For example BorderLayout would take it fine, but GroupLayout won't. If you do add or remove by hand, call revalidate(); and repaint() on the container after these changes.
Also you're using null layout in your added JPanel and contentPane which will completely ruin it's preferredSize calculation. Never use this layout. Learn to use and then use the layout managers. This is your main mistake.
For more on this, please read: Why is it frowned upon to use a null layout in Swing?
For example:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MainGui {
public static final String SCHUELER_PANEL = "Schueler Panel";
public static final String EMPTY = "Empty Panel";
private JPanel mainPanel = new JPanel();
private JMenuBar menuBar = new JMenuBar();
private CardLayout cardLayout = new CardLayout();
private SchuelerPanel schuelerPanel = new SchuelerPanel();
public MainGui() {
mainPanel.setLayout(cardLayout);
mainPanel.add(new JLabel(), EMPTY); // empty label
mainPanel.add(schuelerPanel, SCHUELER_PANEL);
JMenu menu = new JMenu("Panel");
menu.add(new JMenuItem(new SwapPanelAction(EMPTY)));
menu.add(new JMenuItem(new SwapPanelAction(SCHUELER_PANEL)));
menuBar.add(menu);
}
public JPanel getMainPanel() {
return mainPanel;
}
public JMenuBar getMenuBar() {
return menuBar;
}
#SuppressWarnings("serial")
private class SwapPanelAction extends AbstractAction {
public SwapPanelAction(String title) {
super(title);
int mnemonic = (int) title.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(mainPanel, (String) getValue(NAME));
}
}
private static void createAndShowGui() {
MainGui mainGui = new MainGui();
JFrame frame = new JFrame("Main Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainGui.getMainPanel());
frame.setJMenuBar(mainGui.getMenuBar());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
and
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class SchuelerPanel extends JPanel {
private static final String TITLE_TEXT = "Lorem Ipsum Dolor Sit Amet";
public static final String[] LABEL_STRINGS = {"Monday", "Tuesday", "Wednesday"};
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public SchuelerPanel() {
JLabel titleLabel = new JLabel(TITLE_TEXT, JLabel.CENTER);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
for (int i = 0; i < LABEL_STRINGS.length; i++) {
addToPanel(labelFieldPanel, LABEL_STRINGS[i], i);
}
// Don't do what I'm doing here: avoid "magic" numbers!
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(10, 10));
add(titleLabel, BorderLayout.PAGE_START);
add(labelFieldPanel, BorderLayout.CENTER);
}
// get the text from the JTextField based on the JLabel associated with it
public String getText(String labelText) {
JTextField textField = labelFieldMap.get(labelText);
if (textField == null) {
throw new IllegalArgumentException("For labelText: " + labelText);
}
return textField.getText();
}
private void addToPanel(JPanel gblUsingPanel, String labelString, int row) {
JLabel label = new JLabel(labelString);
label.setFont(label.getFont().deriveFont(Font.BOLD));
JTextField textField = new JTextField(10);
labelFieldMap.put(labelString, textField);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(5, 5, 5, 5);
gblUsingPanel.add(label, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gblUsingPanel.add(textField, gbc);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SchuelerPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SchuelerPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
i want to set the size of a JLabel to a specific (minimum) size via setPreferredSize().
If the text inside the JLabel doesn't fit anymore, the JLabel should grow.
The problem now is:
after label.setPreferredSize(new Dimension(50,20));
i do setText("new long text"); but the size won't change
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class LabelTest
{
public static void createWindow()
{
JFrame frame = new JFrame();
JLabel label = new JLabel("Text");
System.out.println(label.getPreferredSize().width); // 25
label.setText("New long text");
System.out.println(label.getPreferredSize().width); // 77 - JLabel grows as expected
label.setText("Text");
System.out.println(label.getPreferredSize().width); // 25
label.setPreferredSize(new Dimension(50, 20));
System.out.println(label.getPreferredSize().width); // 50 - JLabel grows to given size as expected
label.setText("New long text");
System.out.println(label.getPreferredSize().width); // 50 - it should be 77 again
frame.add(label);
frame.setPreferredSize(new Dimension(200, 100));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createWindow();
}
});
}
}
So i need a solution to get the new preferred size when a text is set after i already set the preferred size manually.
If you need more information just ask.
Thanks in advance!
You can reach what you want using a LayoutManager
Below is a example with GridBag Layout
public class GridBagExample extends JFrame {
private JPanel contentPane;
private JLabel lblMyLabel;
private JTextField textField;
private JButton btnChangeMyLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
GridBagExample frame = new GridBagExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GridBagExample() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 94);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 0, 344, 0 };
gbl_contentPane.rowHeights = new int[] { 0, 0, 0 };
gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
gbl_contentPane.rowWeights = new double[] { 1.0, 1.0, Double.MIN_VALUE };
contentPane.setLayout(gbl_contentPane);
lblMyLabel = new JLabel(" My Label");
GridBagConstraints gbc_lblMyLabel = new GridBagConstraints();
gbc_lblMyLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblMyLabel.anchor = GridBagConstraints.EAST;
gbc_lblMyLabel.gridx = 0;
gbc_lblMyLabel.gridy = 0;
contentPane.add(lblMyLabel, gbc_lblMyLabel);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(textField, gbc_textField);
textField.setColumns(10);
btnChangeMyLabel = new JButton("Change My Label");
btnChangeMyLabel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
lblMyLabel.setText("This is the new text of my JLabel");
}
});
GridBagConstraints gbc_btnChangeMyLabel = new GridBagConstraints();
gbc_btnChangeMyLabel.gridwidth = 2;
gbc_btnChangeMyLabel.gridx = 0;
gbc_btnChangeMyLabel.gridy = 1;
contentPane.add(btnChangeMyLabel, gbc_btnChangeMyLabel);
}
Hope it helps.
To set a minimum size, use setMinimumSize(Dimension). In most cases, it is better to place the JLabel in a container with a suitable layout manager, and to set size on it.
Return value of getPreferredSize() is automatically calculated until you set an explicit preferred size. After this, getPreferredSize() will be return with this specific size. If you reset preferred size (by setting it to null), then automatic size will be again available. In your case:
label.setText("Text");
System.out.println(label.getPreferredSize().width); // 25
label.setPreferredSize(new Dimension(50, 20));
System.out.println(label.getPreferredSize().width); // 50
label.setText("New long text");
System.out.println(label.getPreferredSize().width); // 50
label.setPreferredSize(null);
System.out.println(label.getPreferredSize().width); // 77
I am designing an application, in which there should be 5 different JPanels containing different Swing components. For the JRadioButton part, I ran into an issue for which couldn't find proper solution. The 'radioSizePanel' is supposed to be placed somewhere in upper middle of the main panel. Has anyone solved this problem before ? Here is the code, that I am using :
import java.awt.*;
import javax.swing.*;
public class PizzaShop extends JFrame
{
private static final long serialVersionUID = 1L;
private JRadioButton[] radio_size = new JRadioButton[3];
private JRadioButton[] radio_type = new JRadioButton[3];
public PizzaShop()
{
initializaUI();
}
private void initializaUI()
{
setSize(700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel container to wrap checkboxes and radio buttons
JPanel panel = new JPanel();
//sizes radio buttons
String Size[] = {"Small: $6.50", "Medium: $8.50", "Large: $10.00"};
JPanel radioSizePanel = new JPanel(new GridLayout(3, 1));
ButtonGroup radioSizeGroup = new ButtonGroup();
for (int i=0; i<3; i++)
{
radio_size[i] = new JRadioButton(Size[i]);
radioSizePanel.add(radio_size[i]);
radioSizeGroup.add(radio_size[i]);
}
radioSizePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Size"));
radioSizePanel.setPreferredSize(new Dimension(100, 200));
//
panel.add(radioSizePanel);
setContentPane(panel);
setContentPane(radioSizePanel);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PizzaShop().setVisible(true);
}
});
}
}
Here is what I want as an expected OUTPUT :
Please do watch the code example and Please do watch everything carefully , the sequence of adding things to the JFrame. Since in your example you calling setSize() much before something has been added to the JFrame, hence first add components to the container, and then call it's pack()/setSize() methods, so that it can realize that in a good way.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PizzaLayout
{
/*
* Five JPanels we will be using.
*/
private JPanel headerPanel;
private JPanel footerPanel;
// This JPanel will contain the middle components.
private JPanel centerPanel;
private JPanel toppingPanel;
private JPanel sizePanel;
private JPanel typePanel;
private JPanel buttonPanel;
private String[] toppings = {
"Tomato",
"Green Pepper",
"Black Olives",
"Mushrooms",
"Extra Cheese",
"Pepproni",
"Sausage"
};
private JCheckBox[] toppingsCBox;
private String[] sizePizza = {
"Small $6.50",
"Medium $8.50",
"Large $10.00"
};
private JRadioButton[] sizePizzaRButton;
private String[] typePizza = {
"Thin Crust",
"Medium Crust",
"Pan"
};
private JRadioButton[] typePizzaRButton;
private JButton processButton;
private ButtonGroup bGroupType, bGroupSize;
private JTextArea orderTArea;
private StringBuilder sBuilderOrder;
private void displayGUI()
{
JFrame frame = new JFrame("Pizza Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*
* This JPanel is the base of all the
* other components, and at the end
* we will set this as Content Pane
* for the JFrame.
*/
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(10, 10, 10, 10));
/*
* TOP PART of the LAYOUT.
*/
headerPanel = new JPanel();
JLabel headerLabel = new JLabel(
"Welcome to Home Style Pizza Shop"
, JLabel.CENTER);
headerLabel.setForeground(Color.RED);
headerPanel.add(headerLabel);
/*
* CENTER PART of the LAYOUT.
*/
centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.weightx = 0.3;
gbc.weighty = 1.0;
/*
* Above Constraints are for this part.
*/
toppingPanel = new JPanel();
toppingPanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Each Topping $1.50"));
JPanel checkBoxesPanel = new JPanel();
checkBoxesPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
checkBoxesPanel.setLayout(new GridLayout(0, 1, 5, 5));
toppingsCBox = new JCheckBox[toppings.length];
for (int i = 0; i < toppings.length; i++)
{
toppingsCBox[i] = new JCheckBox(toppings[i]);
checkBoxesPanel.add(toppingsCBox[i]);
}
toppingPanel.add(checkBoxesPanel);
centerPanel.add(toppingPanel, gbc);
// Till this.
gbc.gridx = 1;
gbc.gridheight = 1;
gbc.weighty = 0.7;
/*
* Above Constraints are for this part.
*/
sizePanel = new JPanel();
sizePanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Pizza Size"));
JPanel radioBoxesPanel = new JPanel();
radioBoxesPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
radioBoxesPanel.setLayout(new GridLayout(0, 1, 10, 10));
sizePizzaRButton = new JRadioButton[sizePizza.length];
bGroupSize = new ButtonGroup();
for (int i = 0; i < sizePizza.length; i++)
{
sizePizzaRButton[i] = new JRadioButton(sizePizza[i]);
bGroupSize.add(sizePizzaRButton[i]);
radioBoxesPanel.add(sizePizzaRButton[i]);
}
sizePanel.add(radioBoxesPanel);
centerPanel.add(sizePanel, gbc);
// Till this.
gbc.gridx = 2;
gbc.weighty = 0.7;
/*
* Above Constraints are for this part.
*/
typePanel = new JPanel();
typePanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Pizza Type"));
JPanel radioBoxesTypePanel = new JPanel();
radioBoxesTypePanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
radioBoxesTypePanel.setLayout(new GridLayout(0, 1, 10, 10));
typePizzaRButton = new JRadioButton[typePizza.length];
bGroupType = new ButtonGroup();
for (int i = 0; i < typePizza.length; i++)
{
typePizzaRButton[i] = new JRadioButton(typePizza[i]);
bGroupType.add(typePizzaRButton[i]);
radioBoxesTypePanel.add(typePizzaRButton[i]);
}
typePanel.add(radioBoxesTypePanel);
centerPanel.add(typePanel, gbc);
// Till this.
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weighty = 0.3;
gbc.gridwidth = 2;
processButton = new JButton("Process Selection");
processButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
sBuilderOrder = new StringBuilder();
sBuilderOrder.append("Pizza type : ");
for (int i = 0; i < typePizza.length; i++)
{
if (typePizzaRButton[i].isSelected())
sBuilderOrder.append(typePizzaRButton[i].getText());
}
sBuilderOrder.append("\n");
sBuilderOrder.append("Pizza Size : ");
for (int i = 0; i < sizePizza.length; i++)
{
if (sizePizzaRButton[i].isSelected())
sBuilderOrder.append(sizePizzaRButton[i].getText());
}
sBuilderOrder.append("\n");
sBuilderOrder.append("Toppings : ");
/*
* I hope you can do this part yourself now :-)
*/
orderTArea.setText(sBuilderOrder.toString());
}
});
centerPanel.add(processButton, gbc);
footerPanel = new JPanel();
footerPanel.setLayout(new BorderLayout(5, 5));
footerPanel.setBorder(
BorderFactory.createTitledBorder("Your Order : "));
orderTArea = new JTextArea(10, 10);
footerPanel.add(orderTArea, BorderLayout.CENTER);
contentPane.add(headerPanel, BorderLayout.PAGE_START);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new PizzaLayout().displayGUI();
}
});
}
}
Here is the output of the same :
in my application i do intensive use of animated gif images displayed in a JEditorPane (this is a chat).
Now i realyzed that the GIFs consume a lot of CPU (near 100% in some cases), and the memory used continued to increase indefinitely.
How to avoid this? Or, can you suggest another component to replace JEditorPane for better performance?
This is an example that can show the memory increase and the CPU usage.
public class TestCPU extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestCPU frame = new TestCPU();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestCPU() {
setIconImage(Toolkit.getDefaultToolkit().getImage(TestCPU.class.getResource("/images/asd.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
contentPane.add(scrollPane, gbc_scrollPane);
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
String html = "<html>";
for (int i = 0; i < 500; i++) {
html = html + "<img src="+ TestCPU.class.getResource("/images/asd.gif") + ">";
}
editorPane.setText(html);
scrollPane.setViewportView(editorPane);
}
}
the image used in the test