Java function pack(), JFrame size - java

I'm having some problems with function pack(), as I know it should set size of JFrame to minimum.
Here is my masterpiece:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Okno extends JFrame{
public Okno(String naslov){
setTitle(naslov);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int sirina = d.width;
int visina = d.height;
setBounds(sirina/4,visina/4,sirina/2,visina/2);
}
}
public class Pretvori{
public static class Plosca extends JPanel implements ActionListener{
JTextField vnesiC , izracunajF;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
public void actionPerformed(ActionEvent e) {
String c = vnesiC.getText();
Double dc = Double.parseDouble(c);
Double df = 1.80 * dc + 32.0;
String f = String.format("%f", df);
izracunajF.setText(f);
}
}
public static void main(String[] args){
Okno okno = new Okno("Pretvornik");
okno.setLayout(new BorderLayout());
Plosca p = new Plosca();
okno.add(p);
okno.pack();
okno.setResizable(false);
okno.setVisible(true);
}
}
Download link: http://pastebin.com/download.php?i=kGkpCrHe
And I am sorry for bad language.

One big problem is that you are adding components to your Plosca instance during each call to paintComponent. You should add your components in a Plosca constructor instead. Then when you call pack() it will have components so its preferred size won't be so small.
public static class Plosca extends JPanel implements ActionListener{
JTextField vnesiC , izracunajF;
public Plosca() {
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
// do not need paintComponent()
public void actionPerformed(ActionEvent e) {
. . .
}
}

No, pack sizes the frame to its contents preferred size (based on the requirements of the layout managers), but since your Plosca doesn't have a preferred size, it's returning 0x0, therefore your frame thinks the preferred size is 0x0
This...
protected void paintComponent(Graphics g) {
super.paintComponent(g);
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
isn't how you should prepare your UI, paintComponent is used for performing custom painting, not adding to or changing the UI.
Instead, you should start adding your components from within the constructor
public Plosca() {
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
Take a look at How to create a GUI with Swing for more details...

Related

I have problems creating and showing the panel in the class MyPanel

I am working on an Uni Project using Java Swing. I want to create a statistics panel containing Temperature and other variables.
I have problems creating and showing the panel in the class MyPanel.
When I replace MyPanel p = new MyPanel() in the Class Main with the content of the method paintComponent in the Class MyPanel it works but not the other way around . I want to create the panel in a separate class and just call on it.
public class Main extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel p = createAndShowGUI();
}
});
}
private static JPanel createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel p = new MyPanel();
f.add(p);
//f.add(new MyPanel());
f.pack();
f.setVisible(true);
return p;
}
}
public class MyPanel extends JPanel {
private JLabel TemperaturLabel ;
private JTextField Temperatur ;
private JLabel LuftfeuchtigkeitLabel;
private JTextField Luftfeuchtigkeit;
private JLabel luftdruckLabel;
private JTextField luftdruck;
private JLabel VorhersageLabel;
private JPanel Panel;
protected void paintComponent(Graphics g) {
TemperaturLabel = new JLabel("Temperatur: ");
Temperatur = new JTextField(2);
LuftfeuchtigkeitLabel = new JLabel("Luftfeuchtigkeit: ");
Luftfeuchtigkeit = new JTextField(3);
luftdruckLabel = new JLabel("Luftdruck: ");
luftdruck = new JTextField(4);
Panel= new JPanel( new GridBagLayout());
VorhersageLabel = new JLabel("Vorhersage:------");
GridBagConstraints c = new GridBagConstraints();
c.insets= new Insets(10,10,10,10);
c.gridx=0;
c.gridy=1;
Panel.add(TemperaturLabel,c);
c.gridx=1;
c.gridy=1;
Panel.add(Temperatur,c);
c.gridx=0;
c.gridy=2;
Panel.add(LuftfeuchtigkeitLabel,c);
c.gridx=1;
c.gridy=2;
Panel.add(Luftfeuchtigkeit,c);
c.gridx=0;
c.gridy=3;
Panel.add(luftdruckLabel,c);
c.gridx=1;
c.gridy=3;
Panel.add(luftdruck,c);
c.gridx=0;
c.gridy=4;
Panel.add(VorhersageLabel,c);
c.gridx=1;
c.gridy=4;
}
public Dimension getPreferredSize() {
return new Dimension(900,700);
}
}
So you're expecting to see something like this?
There were a number of logical errors in that code that caused a number of problems. Here is the corrected code with comments on most of them. (Some were not fixed as they did not make much difference in the end.)
The fundamental problem came from both extending and creating an instance of the JPanel. What ended up in the frame was the extended panel to which nothing had been added!
import java.awt.*;
import javax.swing.*;
// Use meaningful names for classes, attributes and methods!
// Don't. Extend. JFrame!
// public class Main extends JFrame {
public class MyPanelDisplayProblem {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// See comments below
// JPanel p = createAndShowGUI();
createAndShowGUI();
}
});
}
// why is this method returning anything? It makes no sense to do that.
// private static JPanel createAndShowGUI() {
private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "
+ SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Oh my! This clashes with another name in my 'junk code' package!
// Again. Descriptive names!
// MyPanel p = new MyPanel();
WeatherPanel p = new WeatherPanel();
f.add(p.getPanel());
//f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
/* Don't extend panels either, unless custom painting. */
//class WeatherPanel extends JPanel {
class WeatherPanel {
/*
* Please learn common Java nomenclature (naming conventions - e.g.
`EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`,
`firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`)
and use it consistently.
*/
private JLabel TemperaturLabel ;
private JTextField Temperatur ;
private JLabel LuftfeuchtigkeitLabel;
private JTextField Luftfeuchtigkeit;
private JLabel luftdruckLabel;
private JTextField luftdruck;
private JLabel VorhersageLabel;
private JPanel Panel;
/*
The resoning here is entirely wrong. Components should be created and
added from within a constructor!
*/
// protected void paintComponent(Graphics g) {
public WeatherPanel() {
TemperaturLabel = new JLabel("Temperatur: ");
Temperatur = new JTextField(2);
LuftfeuchtigkeitLabel = new JLabel("Luftfeuchtigkeit: ");
Luftfeuchtigkeit = new JTextField(3);
luftdruckLabel = new JLabel("Luftdruck: ");
luftdruck = new JTextField(4);
Panel= new JPanel( new GridBagLayout());
VorhersageLabel = new JLabel("Vorhersage:------");
GridBagConstraints c = new GridBagConstraints();
c.insets= new Insets(10,10,10,10);
c.gridx=0;
c.gridy=1;
Panel.add(TemperaturLabel,c);
c.gridx=1;
c.gridy=1;
Panel.add(Temperatur,c);
c.gridx=0;
c.gridy=2;
Panel.add(LuftfeuchtigkeitLabel,c);
c.gridx=1;
c.gridy=2;
Panel.add(Luftfeuchtigkeit,c);
c.gridx=0;
c.gridy=3;
Panel.add(luftdruckLabel,c);
c.gridx=1;
c.gridy=3;
Panel.add(luftdruck,c);
c.gridx=0;
c.gridy=4;
Panel.add(VorhersageLabel,c);
c.gridx=1;
c.gridy=4;
}
// Now to get the panel that is created, we can add a 'get panel' method.
public JPanel getPanel() {
return Panel;
}
/**
* This is both unnecessary and counterproductive.
* See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size
* methods in Java Swing?](http://stackoverflow.com/q/7229226/418556)
* (Yes.)
*/
/*
public Dimension getPreferredSize() {
return new Dimension(900,700);
}
*/
}
I took your code, rearranged it, and added a few things to get this GUI.
I redid your createAndShowGUI method to remove the static and use a new getPanel method I created.
I redid your TemperaturePanel class to create and show a JPanel. I organized your Swing components in column, row order so I could visually verify the Swing components. I added the missing JTextField. I created getter methods so you could actually get and set the values in the JTextFields.
I formatted the code and used proper camelCase variable names.
Here's the revised code. I made the TemperaturePanel an inner class so I could post this code as one block.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TemperatureGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TemperatureGUI().createAndShowGUI();
}
});
}
private void createAndShowGUI() {
System.out.println("Created GUI on EDT? " +
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TemperaturePanel p = new TemperaturePanel();
f.add(p.getPanel());
// f.add(new MyPanel());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public class TemperaturePanel {
private JTextField temperatur;
private JTextField luftfeuchtigkeit;
private JTextField luftdruck;
private JTextField vorhersage;
private JPanel panel;
public TemperaturePanel() {
this.panel = createAndShowPanel();
}
private JPanel createAndShowPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.insets = new Insets(10, 10, 10, 10);
c.gridx = 0;
c.gridy = 1;
JLabel temperaturLabel = new JLabel("Temperatur: ");
panel.add(temperaturLabel, c);
c.gridx = 1;
c.gridy = 1;
temperatur = new JTextField(10);
panel.add(temperatur, c);
c.gridx = 0;
c.gridy = 2;
JLabel luftfeuchtigkeitLabel = new JLabel("Luftfeuchtigkeit: ");
panel.add(luftfeuchtigkeitLabel, c);
c.gridx = 1;
c.gridy = 2;
luftfeuchtigkeit = new JTextField(10);
panel.add(luftfeuchtigkeit, c);
c.gridx = 0;
c.gridy = 3;
JLabel luftdruckLabel = new JLabel("Luftdruck: ");
panel.add(luftdruckLabel, c);
c.gridx = 1;
c.gridy = 3;
luftdruck = new JTextField(10);
panel.add(luftdruck, c);
c.gridx = 0;
c.gridy = 4;
JLabel vorhersageLabel = new JLabel("Vorhersage:------");
panel.add(vorhersageLabel, c);
c.gridx = 1;
c.gridy = 4;
vorhersage = new JTextField(10);
panel.add(vorhersage, c);
return panel;
}
public JTextField getTemperatur() {
return temperatur;
}
public JTextField getLuftfeuchtigkeit() {
return luftfeuchtigkeit;
}
public JTextField getLuftdruck() {
return luftdruck;
}
public JTextField getVorhersage() {
return vorhersage;
}
public JPanel getPanel() {
return panel;
}
}
}

Combining a constructor class with am main class

Can someone guide me on how can I combine these two classes into one file? One is a constructor class and the other one is a main.
Thanks;
Main Class:
public class JHelloDemo
{
public static void main(String[] args)
{
JHelloFrame frame = new JHelloFrame();
frame.setVisible(true);
}
}
Constructor class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHelloFrame extends JFrame implements ActionListener{
JLabel question = new JLabel("What is your name?");
Font bigFont = new Font("Arial", Font.BOLD, 16);
JTextField answer = new JTextField(10);
JButton pressMe = new JButton("Press me");
JLabel greeting = new JLabel("");
final int WIDTH = 275;
final int HEIGHT = 225;
public JHelloFrame(){
super("Hello Frame");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
question.setFont(bigFont);
greeting.setFont(bigFont);
add(question);
add(answer);
add(pressMe);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pressMe.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
String name = answer.getText();
String greet = "Hello, " + name;
greeting.setText(greet);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHelloFrame extends JFrame implements ActionListener{
JLabel question = new JLabel("What is your name?");
Font bigFont = new Font("Arial", Font.BOLD, 16);
JTextField answer = new JTextField(10);
JButton pressMe = new JButton("Press me");
JLabel greeting = new JLabel("");
final int WIDTH = 275;
final int HEIGHT = 225;
public JHelloFrame(){
super("Hello Frame");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
question.setFont(bigFont);
greeting.setFont(bigFont);
add(question);
add(answer);
add(pressMe);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pressMe.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
String name = answer.getText();
String greet = "Hello, " + name;
greeting.setText(greet);
}
public static void main(String[] args)
{
JHelloFrame frame = new JHelloFrame();
frame.setVisible(true);
}
}
There you go
You could simply move the main() method to JHelloFrame, which is the answer to your question. However, your existing design separates concerns, so I would leave it alone.
BTW, you should wrap frame.setVisible(true) in a Runnable and pass it to EventQueue.invokeLater(). See this question for more explanation.

Sending variables between classes

I have a JFrame class and a JPanel class.
When I click on a button in my JFrame my variable addIp take the entered String.
How can I access to this variable in my JPanel class ?
Here's my JFrame class:
public class Window extends JFrame{
public static void main(String[] args) {
new Window();
}
}
public Window()
{
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
stop = new JButton("STOP");
ListenForButton lForButton = new ListenForButton();
ip.addActionListener(lForButton);
centerPanel.add(start);
centerPanel.add(stop);
north.add(centerPanel, BorderLayout.CENTER);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
this.setContentPane(container);
this.setVisible(true);
}
public class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ip)
{
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
if(!address_t.getText().isEmpty())
{
addIp=address_t.getText();
}
}
}
And I want the addIP variable be accessible in my JPanel class:
public class GraphDisplay extends JPanel implements ActionListener {
double rand, lastrand, max, min, total, degr, average, temp, length;
ArrayList<Double> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
ArrayList<String> dateL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255, 0, 0);
Color green = new Color(0, 200, 0);
Color blue = new Color(0, 0, 200);
Color yellow = new Color(200, 200, 0);
int i, k = 0, inc, j, t;
public GraphDisplay() {
super();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
I copied you just the beginning of the class because the rest isn't interesting for this kind of problem.
You have several options:
Have the object that holds the information "push" it into the other object. To do this, your Window class would need to hold an instance of the GraphDisplay class, and call a method that GraphDisplay has, say, setIPaddress(String ip), passing in the String into GraphDisplay. Note that the instance hold by Window has to be the visualized GraphDisplay instance, and not any old instance.
Or you could have GraphDisplay "pull" the information in. Here Window would notify any listeners that the addIP variable has changed, and so the listeners, here this could be the GraphDisplay instance, could call getAddIP() from Window and thereby get the new value. To do this, you'd have to use Swing's notification mechanism, such as a ChangeListener or a PropertyChangeListener.

How to change the size of button in a Scroll Panel

I want to change the size of buttons. I want to set a SQUARE type view of each button but unfortunately it is giving a rectangular look. I am getting a square type look only if I set the number of rows to 20 or 25. Right now my GUI looks like the following: .
I have tried to change it from buttons[i][j].setMaximumSize(new Dimension( 20, 20)) , Where buttons is the name of array. I have also tried buttons[i][j].setsize but still it has no effect on it. I am setting it from : bPanel.setLayout(new GridLayout(x,y)) and I thing this is the main cause of the problem. Can any one also tell me that how can I set it to layout manager?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.event.*;
import javax.swing.JFrame;
import sun.util.calendar.Gregorian;
public class Final_GUI extends JFrame implements ActionListener {
JLabel label;
ButtonGroup cbg;
JRadioButton radio_1;
JRadioButton radio_2;
JRadioButton radio_3;
JCheckBox checkbox_1;
JCheckBox checkbox_2;
JCheckBox checkbox_3;
JScrollPane scrollpane_1;
JComboBox combobox_1;
JList list_1;
JScrollPane sp_list_1;
JComboBox combobox_2;
JButton Orange;
JButton Exit;
JLabel for_text;
int x=200;
int y=100;
int check [][]= new int [x][y];
JFrame frame = new JFrame();
JButton[][] buttons = new JButton[x][y];
JPanel mPanel = new JPanel();
JPanel bPanel = new JPanel();
JPanel cPanel = new JPanel();
JTextArea scoreKeeper = new JTextArea();
int[][] intArray = new int[x][y];
public Final_GUI() {
butGen();
score();
Final_GUILayout customLayout = new Final_GUILayout();
getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
getContentPane().setLayout(customLayout);
label = new JLabel("Shortest Path Finding Algorithm");
getContentPane().add(label);
cbg = new ButtonGroup();
radio_1 = new JRadioButton("radio_1", false);
cbg.add(radio_1);
getContentPane().add(radio_1);
radio_2 = new JRadioButton("radio_2", false);
cbg.add(radio_2);
getContentPane().add(radio_2);
radio_3 = new JRadioButton("radio_3", false);
cbg.add(radio_3);
getContentPane().add(radio_3);
checkbox_1 = new JCheckBox("checkbox_1");
getContentPane().add(checkbox_1);
checkbox_2 = new JCheckBox("checkbox_2");
getContentPane().add(checkbox_2);
checkbox_3 = new JCheckBox("checkbox_3");
getContentPane().add(checkbox_3);
bPanel.setLayout(new GridLayout(x,y));
mPanel.setLayout(new BorderLayout());
mPanel.add(bPanel, BorderLayout.CENTER);
scrollpane_1 = new JScrollPane(mPanel);
scrollpane_1.setViewportView(mPanel);
getContentPane().add(scrollpane_1);
combobox_1 = new JComboBox();
combobox_1.addItem("Size1");
combobox_1.addItem("Size2");
getContentPane().add(combobox_1);
DefaultListModel listModel_list_1 = new DefaultListModel();
listModel_list_1.addElement("Black");
listModel_list_1.addElement("Green");
list_1 = new JList(listModel_list_1);
sp_list_1 = new JScrollPane(list_1);
getContentPane().add(sp_list_1);
combobox_2 = new JComboBox();
combobox_2.addItem("Additional Data");
combobox_2.addItem("Additional Data2");
getContentPane().add(combobox_2);
Orange = new JButton("Orange");
getContentPane().add(Orange);
Exit = new JButton("Exit");
getContentPane().add(Exit);
for_text = new JLabel("Just For some text");
getContentPane().add(for_text);
setSize(getPreferredSize());
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private void butGen()
{
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
buttons[i][j] = new JButton(String.valueOf(i)+"x"+String.valueOf(j));
buttons[i][j].setActionCommand("button" +i +"_" +j);
buttons[i][j].addActionListener(this);
buttons[i][j].setMaximumSize(new Dimension( 20, 20));
bPanel.add(buttons[i][j]);
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
intArray[i][j]++;
if(check[i][j]!=1){
buttons[i][j].setBackground(Color.black);
check[i][j]=1;
}
else{
buttons[i][j].setBackground(null);
check[i][j]=0;
}
System.out.println(e.getActionCommand() +" " +(i) +" " +(j));
score();
if(checkbox_1.isSelected())
{
buttons[i][j].setBackground(Color.GREEN);
}
}
}
private void score()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
buttons[i][j].setText("");
}
public static void main(String args[]) {
Final_GUI window = new Final_GUI();
window.setTitle("SHORTEST PATH FINDING ALGORITHM");
window.setBackground(Color.black);
// window.setSize(800, 300);
window.setResizable(true);
window.resize(200, 500);
window.pack();
window.show();
}
}
GUI LAYOUT
class Final_GUILayout implements LayoutManager {
public Final_GUILayout() {
}
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
Insets insets = parent.getInsets();
dim.width = 1053 + insets.left + insets.right;
dim.height = 621 + insets.top + insets.bottom;
return dim;
}
public Dimension minimumLayoutSize(Container parent) {
Dimension dim = new Dimension(0,0);
return dim;
}
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
Component c;
c = parent.getComponent(0);
if (c.isVisible()) {c.setBounds(insets.left+368,insets.top+24,304,64);}
c = parent.getComponent(1);
if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+120,72,24);}
c = parent.getComponent(2);
if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+144,72,24);}
c = parent.getComponent(3);
if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+168,72,24);}
c = parent.getComponent(4);
if (c.isVisible()) {c.setBounds(insets.left+88,insets.top+120,72,24);}
c = parent.getComponent(5);
if (c.isVisible()) {c.setBounds(insets.left+88,insets.top+144,72,24);}
c = parent.getComponent(6);
if (c.isVisible()) {c.setBounds(insets.left+88,insets.top+168,72,24);}
c = parent.getComponent(7);//Panel
if (c.isVisible()) {
c.setBounds(insets.left+168,insets.top+120,704,488);
}
c = parent.getComponent(8);
if (c.isVisible()) {c.setBounds(insets.left+880,insets.top+120,160,160);}
c = parent.getComponent(9);
if (c.isVisible()) {c.setBounds(insets.left+24,insets.top+232,128,216);}
c = parent.getComponent(10);
if (c.isVisible()) {c.setBounds(insets.left+880,insets.top+296,160,216);}
c = parent.getComponent(11);
if (c.isVisible()) {c.setBounds(insets.left+904,insets.top+528,112,24);}
c = parent.getComponent(12);
if (c.isVisible()) {c.setBounds(insets.left+888,insets.top+568,144,32);}
c = parent.getComponent(13);
if (c.isVisible()) {c.setBounds(insets.left+16,insets.top+472,120,48);}
}
}
GridLayout works by providing equal amount of space to each of the components, making each component fill each cell.
Take a look at How to use GridLayout for more details.
If you want a LayoutManager that provides you with the finest of control, but which will (unless you tell it otherwise) use the components preferred/minimum/maximum size hints, you should consider trying something like GridBagLayout instead
Take a look at How to use GridBagLayout for more details
Using GridBagLayout you can set the size of the components inside.
Another way to do it would be to create a custom button inherited from JButton class and overwrite the method SetSize(int width, int height) and setting width=height.
You can do something like this:
public class SquareButton extends JButton{
#Override
public void setSize(int width, int height) {
super.setSize(width, width);
}
}
With that, you are defining a new class of JButton that inherits all the methods from JButton, but all the instances of this SquareButton class will have the same width and height.
Maybe you don't need to do it, but I think it works. On the other hand, using this new class you don't be able to set another size relationship for your buttons.
Another way could be to create a new method in the new SquareButton class to set your desired size (or relationship width/height), instead of overwrite the SetSize(int width, int height).

Unstable GUI in Java

I am writing a very simple GUI, that contains 3 buttons, 2 labels, 2 text fields and one text area. Strangely, the result is unstable: when running the class the GUI appears with random number of the controls. I tried various layout managers, changing the order among the control - nothing.
Can someone help?
package finaltestrunner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FinalTestGUI extends JFrame implements ActionListener
{
public Boolean startState = false;
JButton sofButton;
JButton startStopButton;
JButton exitButton;
JTextField loopCounts;
JTextField trSnField;
JTextArea resultField = null;
public FinalTestGUI()
{
// The constructor creates the panel and places the controls
super(); // Jframe constructor
JFrame trFrame = new JFrame();
trFrame.setSize(1000, 100);
trFrame.setVisible(true);
trFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trFrame.setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
// trFrame.setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
trFrame.add(trControlPanel);
// cpl.add(trResultField);
startStopButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trStartStopButton)
{
startState = !startState;
if (startState)
{
startStopButton.setText("Run ");
startStopButton.setForeground(Color.red);
}
else
{
startStopButton.setText("Stop");
startStopButton.setForeground(Color.green);
}
}
});
sofButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trSofButton)
{
loopCounts.setText("SOF\n");
}
});
exitButton.addActionListener (new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trExitButton)
{
System.exit(0);
}
});
} // End of the constructor
#Override
public void actionPerformed (ActionEvent ae) { }
public void atpManager ()
{
String selectedAtp = "";
}
}
There are a couple of issues with this code:
You are already inheriting from JFrame, so you do not need to create yet another JFrame
You are showing your frame with setVisible(true) and afterwards adding components to it. This invalidates your layout, you need to revalidate afterwards (or move setVisible() to a position where you already added your components)
You are adding your components to the JFrame directly, but you need to use its contentpane. Starting with Java 1.5, the JFrame.add() methods automatically forward to the content pane. In earlier versions, it was necessary to retrieve the content pane with JFrame.getContentPane() to add the child components to the content pane.
Try this:
public FinalTestGUI() {
// The constructor creates the panel and places the controls
super(); // Jframe constructor
setSize(1000, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
// getContentPane().add(trControlPanel); // pre 1.5
add(trControlPanel); // 1.5 and greater
setVisible(true);
}

Categories

Resources