Java gif image consuming CPU and memory - java

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

Related

Adding Data to JTable from different Class

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;
}
}

Why can't I insert my JTextField inside my JPanel?

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 !

JLabel: setPreferredSize manually but getPreferredSize after setText

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

Swing: Panel Size Issue

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 :

JavaSwing (FileReader) read txt.file and write into JList - randomly works Oo

Hi
I'm working on a JavaSwing application but there's a problem with... I don't know exactly but I think it's maybe a (re)paint-problem :S - anyway here's my code:
MAIN:
public class QickSort {
protected static ArrayList<String> input;
private static File file = new File("C:/Users/save.txt");
public static void main(String[] args) throws Exception {
BufferedReader reader;
String line = null;
try {
input = new ArrayList<String>();
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
input.add(line);
}
reader.close();
} catch (Exception ex) {
System.out.println("Can't load file on path.. - " + ex);
ex.printStackTrace();
}
System.out.println(input.size());
JFrame.setDefaultLookAndFeelDecorated(false);
MasterWin win = new MasterWin(input);
}
}
UI:
public class MasterWin {
private JFrame frame;
private JTextField txtFieldPath;
private JButton btnBrowse;
private JButton btnAddPathTo;
private JLabel lblChosenFolderpaths;
private JButton btnRemove;
private JButton btnNext;
protected static ImageIcon icon = new ImageIcon(MasterWin.class.getResource("/View/logo_sml.gif"));
private JScrollPane scrollPane;
private JList linkList;
private List<String> test;
/**
* Create the application.
*/
public MasterWin(ArrayList<String> fileInput) {
test = fileInput;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setIconImage(icon.getImage());
frame.setTitle("QickSort - Start");
frame.setResizable(false);
frame.setBounds(100, 100, 645, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{480, 127, 0};
gridBagLayout.rowHeights = new int[]{135, 60, 0, 0, 0, 115, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
frame.setVisible(true);
JLabel logo = new JLabel("");
logo.setIcon(new ImageIcon(MasterWin.class.getResource("/View/Logo.gif")));
GridBagConstraints gbc_logo = new GridBagConstraints();
gbc_logo.fill = GridBagConstraints.HORIZONTAL;
gbc_logo.gridwidth = 2;
gbc_logo.insets = new Insets(0, 0, 5, 0);
gbc_logo.anchor = GridBagConstraints.SOUTH;
gbc_logo.gridx = 0;
gbc_logo.gridy = 0;
frame.getContentPane().add(logo, gbc_logo);
JLabel lblChosePathYou = new JLabel("Choose paths you want to use:");
GridBagConstraints gbc_lblChosePathYou = new GridBagConstraints();
gbc_lblChosePathYou.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblChosePathYou.insets = new Insets(0, 60, 5, 5);
gbc_lblChosePathYou.gridx = 0;
gbc_lblChosePathYou.gridy = 1;
frame.getContentPane().add(lblChosePathYou, gbc_lblChosePathYou);
txtFieldPath = new JTextField();
txtFieldPath.setEditable(false);
GridBagConstraints gbc_txtFieldPath = new GridBagConstraints();
gbc_txtFieldPath.fill = GridBagConstraints.HORIZONTAL;
gbc_txtFieldPath.insets = new Insets(0, 60, 5, 5);
gbc_txtFieldPath.gridx = 0;
gbc_txtFieldPath.gridy = 2;
frame.getContentPane().add(txtFieldPath, gbc_txtFieldPath);
txtFieldPath.setColumns(10);
btnBrowse = new JButton("Browse...");
btnBrowse.setMinimumSize(new Dimension(89, 25));
btnBrowse.setMaximumSize(new Dimension(89, 25));
GridBagConstraints gbc_btnBrowse = new GridBagConstraints();
gbc_btnBrowse.anchor = GridBagConstraints.WEST;
gbc_btnBrowse.insets = new Insets(0, 10, 5, 0);
gbc_btnBrowse.gridx = 1;
gbc_btnBrowse.gridy = 2;
frame.getContentPane().add(btnBrowse, gbc_btnBrowse);
lblChosenFolderpaths = new JLabel("Chosen folderpaths:");
GridBagConstraints gbc_lblChosenFolderpaths = new GridBagConstraints();
gbc_lblChosenFolderpaths.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblChosenFolderpaths.insets = new Insets(0, 60, 5, 5);
gbc_lblChosenFolderpaths.gridx = 0;
gbc_lblChosenFolderpaths.gridy = 3;
frame.getContentPane().add(lblChosenFolderpaths, gbc_lblChosenFolderpaths);
btnAddPathTo = new JButton("Add to list");
GridBagConstraints gbc_btnAddPathTo = new GridBagConstraints();
gbc_btnAddPathTo.anchor = GridBagConstraints.WEST;
gbc_btnAddPathTo.insets = new Insets(5, 10, 5, 0);
gbc_btnAddPathTo.gridx = 1;
gbc_btnAddPathTo.gridy = 3;
frame.getContentPane().add(btnAddPathTo, gbc_btnAddPathTo);
btnRemove = new JButton("Remove");
btnRemove.setToolTipText("Delete selected path");
btnRemove.setPreferredSize(new Dimension(89, 25));
btnRemove.setMinimumSize(new Dimension(89, 25));
btnRemove.setMaximumSize(new Dimension(89, 25));
GridBagConstraints gbc_btnRemove = new GridBagConstraints();
gbc_btnRemove.anchor = GridBagConstraints.NORTHWEST;
gbc_btnRemove.insets = new Insets(5, 10, 5, 0);
gbc_btnRemove.gridx = 1;
gbc_btnRemove.gridy = 4;
frame.getContentPane().add(btnRemove, gbc_btnRemove);
btnNext = new JButton("Accept");
btnNext.setPreferredSize(new Dimension(89, 25));
btnNext.setMinimumSize(new Dimension(89, 25));
btnNext.setMaximumSize(new Dimension(89, 25));
GridBagConstraints gbc_btnNext = new GridBagConstraints();
gbc_btnNext.anchor = GridBagConstraints.SOUTHWEST;
gbc_btnNext.insets = new Insets(0, 10, 25, 0);
gbc_btnNext.gridx = 1;
gbc_btnNext.gridy = 5;
frame.getContentPane().add(btnNext, gbc_btnNext);
scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridheight = 2;
gbc_scrollPane.insets = new Insets(0, 60, 25, 5);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 4;
frame.getContentPane().add(scrollPane, gbc_scrollPane);
//JList I copy the array
linkList = new JList(test.toArray());
scrollPane.setViewportView(linkList);
}
}
The Problem:
It's really strange! Sometimes the text is shown on my JList - but if I start the program once again there's just a empty ScrollPane without the JList or the inputs.
Its more or less random that the text appears.
I tried a various kinds of Array(List)s, to impl. - with AbstractModel() oder just toArray(). Always same result..
Does someone know this problem?
Change:
protected static ArrayList<String> input;
To:
protected static final ArrayList<String> input = new ArrayList<String>();
Remove the assignment to input in main.
Wrap the calls to swing code in an invokeLater:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame.setDefaultLookAndFeelDecorated(false);
MasterWin win = new MasterWin(input);
};
});
After setting your list as the viewport view you should call invalidate() on the JList which will tell the underlying Swing graphics system that it needs to check the component as well as any possibly affected components whether or not these require updating.
Do not call repaint() because that will trigger a repaint of the component as it is, it will not ensure that other affected components are properly updated as well -- and because this JList is wrapped in a JScrollPane it will not behave as expected.
user268396's answer about layout validation is correct, but you should never need to be in this situation in the first place. Your layout is invalidated because you're adding components after you've made your JFrame visible. Simply by moving the call to frame.setVisible(true) to the end of the initialize() method, you should see the problem goes away, because the layout is now finalized and it will validate and render correctly first time.
I solved this issue:
I kicked out my Scrollpane and used only a JList. But that didn't work either.
I call now updateUI() after I create the JList - now it works.

Categories

Resources