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;
}
}
}
Related
I have a pretty basic GUI organized with a GridBagLayout. The most complex portion is the bottom where West is populated with ScrollPane and the right is a panel with a CardLayout that has multiple ChartPanels so I can switch between a few graphs.
My issue comes when I start the program.
The resizing issue goes away after I resize the frame in any direction. I have confirmed the chartpanel is the issue because not adding this to the CardLayout panel fixes it. I create a blank ChartPanel and populate it later after some action is taken but this is what I've done:
public class Tester {
public static void main(String[] args) {
JFrame frame = new JFrame("Chipmunk: Variant Data Collection Tool");
JPanel hotspotPanel = new JPanel(new CardLayout());
ChartPanel subHotspotPanel = new ChartPanel(null);
JPanel indelHotspotPanel = new JPanel(new BorderLayout());
JTextPane resultPane = new JTextPane();
JPanel main = new JPanel(new GridBagLayout());
JPanel header = new JPanel(new BorderLayout());
header.setBackground(Color.WHITE);
frame.setLayout(new BorderLayout());
frame.setMinimumSize(new Dimension(875, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
resultPane.setOpaque(false);
resultPane.setEditable(false);
GridBagConstraints c = new GridBagConstraints();
DocumentFilter filter = new UppercaseDocumentFilter();
JTextField geneField = new JTextField(10);
((AbstractDocument) geneField.getDocument()).setDocumentFilter(filter);
geneField.setMinimumSize(geneField.getPreferredSize());
JTextField proEffField = new JTextField(10);
proEffField.setMinimumSize(proEffField.getPreferredSize());
String[] mutTypes = { "missense", "nonsense", "frameshift", "nonframeshift"};
JComboBox<String> mutTypeComboBox = new JComboBox<String>(mutTypes);
JButton saveResultsButton = new JButton("Save to TSV");
JPanel glass = (JPanel) frame.getGlassPane();
JButton clearButton = new JButton("Clear");
JButton cosmicButton = new JButton("To COSMIC");
JButton dataButton = new JButton("Show Data");
dataButton.setEnabled(false);
JButton goButton = new JButton("GO");
c.weightx = 1.0;c.gridx = 0;c.gridy = 0;c.anchor = GridBagConstraints.EAST;c.ipadx=5;c.ipady=5;
main.add(new JLabel("Gene: "), c);
c.gridx = 1;c.gridy = 0;c.anchor = GridBagConstraints.WEST;
main.add(geneField, c);
c.gridx = 0;c.gridy = 1;c.anchor = GridBagConstraints.EAST;
main.add(new JLabel("Protein Effect: "), c);
c.gridx = 1;c.gridy = 1;c.anchor = GridBagConstraints.WEST;
main.add(proEffField, c);
c.gridx =0;c.gridy = 2;c.anchor = GridBagConstraints.EAST;
main.add(new JLabel("Mutation Type: "), c);
c.gridx =1;c.gridy = 2;c.anchor = GridBagConstraints.WEST;
main.add(mutTypeComboBox, c);
c.gridx =0;c.gridy = 3;c.anchor = GridBagConstraints.WEST;
main.add(saveResultsButton, c);
c.gridx = 0;c.gridy = 3;c.anchor = GridBagConstraints.EAST;
main.add(goButton, c);
c.gridx = 1;c.gridy = 3;c.anchor = GridBagConstraints.WEST;
main.add(clearButton,c);
c.gridx = 0;c.gridy = 3;c.anchor = GridBagConstraints.CENTER;
main.add(dataButton,c);
c.gridx = 1;c.gridy = 3;c.anchor = GridBagConstraints.EAST;
main.add(cosmicButton,c);
c.gridx = 0; c.gridy =4;c.gridwidth =1; c.weightx = 1.0;c.weighty = 1.0; c.fill = GridBagConstraints.BOTH;
JScrollPane scrollPane = new JScrollPane(resultPane);
main.add(scrollPane, c);
c.gridx = 1; c.gridy =4;c.gridwidth = 1; c.weightx = 1.0;c.weighty = 1.0; c.fill = GridBagConstraints.BOTH;
hotspotPanel.add(subHotspotPanel, "SUBPANEL");
hotspotPanel.add(indelHotspotPanel, "INDELPANEL");
hotspotPanel.add(new JPanel(), "BLANK");
main.add(hotspotPanel, c);
frame.add(header, BorderLayout.NORTH);
frame.add(main, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Using this example, it's clear that a ChartPanel works correctly in a CardLayout. The example below overrides getPreferredSize(), as shown here, to establish an initial size for the ChartPanel. The use of GridLayout on each card allows the chart to fill the panel as the enclosing frame is resized.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
/**
* #see https://stackoverflow.com/a/36392696/230513
* #see https://stackoverflow.com/a/36243395/230513
*/
public class CardPanel extends JPanel {
private static final Random r = new Random();
private static final JPanel cards = new JPanel(new CardLayout());
private final String name;
public CardPanel(String name) {
super(new GridLayout());
this.name = name;
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("One", r.nextInt(10) + 10);
pieDataset.setValue("Two", r.nextInt(20) + 10);
pieDataset.setValue("Three", r.nextInt(30) + 10);
JFreeChart chart = ChartFactory.createPieChart3D(
"3D Pie Chart", pieDataset, true, true, true);
chart.setTitle(name);
this.add(new ChartPanel(chart) {
#Override
public Dimension getPreferredSize() {
return new Dimension(500, (int)(500 * 0.62));
}
});
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i < 9; i++) {
CardPanel p = new CardPanel("Chart " + String.valueOf(i));
cards.add(p, p.toString());
}
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("\u22b2Prev") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.previous(cards);
}
}));
control.add(new JButton(new AbstractAction("Next\u22b3") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
}));
f.add(cards, BorderLayout.CENTER);
f.add(control, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
I need some help centering my JButtons. Right now, they are centered horizontally, but they refuse to center vertically. Here is the code for the two classes Game and Menu. Also, is there anyway to put spaces between my buttons using blocklayout.
Game class:
package main;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JFrame{
private static final long serialVersionUID = -7071532049979466544L;
public static final int WIDTH = 1280, HEIGHT = WIDTH/12 * 9;
private Handler handler;
public STATE state = STATE.Menu;
JPanel screen;
//State of the game
public enum STATE{
Menu,
DeckConstructor,
Game;
}
//Game Launch
public Game() {
screen = new JPanel(new CardLayout());
screen.add(new Menu(this).getMenu(), "MENU");
screen.add(new DeckConstructor(this).getDeckConstructor(), "DECK_CONSTRUCTOR");
getContentPane().add(screen,BorderLayout.CENTER);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setVisible(true);
}
public static void main(String[]args){
new Game();
}
}
Menu class:
package main;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Menu extends JFrame implements ActionListener{
private JPanel buttonPanel;
private JButton play;
private JButton deckConstructor;
private JButton quit;
private Game game;
public Menu(Game game){
this.game = game;
buttonPanel = new JPanel();
play = new JButton("Play");
play.addActionListener(this);
deckConstructor = new JButton("Deck Constructor");
deckConstructor.addActionListener(this);
quit = new JButton("Quit");
quit.addActionListener(this);
buttonPanel.add(play);
buttonPanel.add(deckConstructor);
buttonPanel.add(quit);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
play.setAlignmentX(Component.CENTER_ALIGNMENT);
deckConstructor.setAlignmentX(Component.CENTER_ALIGNMENT);
quit.setAlignmentX(Component.CENTER_ALIGNMENT);
}
public JPanel getMenu(){
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(deckConstructor.equals((JButton) e.getSource())){
CardLayout c1 = (CardLayout)(game.screen.getLayout());
c1.show(game.screen, "DECK_CONSTRUCTOR");
}
}
}
Instead of a BoxLayout, I used GridBagLayout and GridBagConstraints.
Code:
public Menu(Game game) {
this.game = game;
buttonPanel = new JPanel(new GridBagLayout());
play = new JButton("Play");
play.addActionListener(this);
deckConstructor = new JButton("Deck Constructor");
deckConstructor.addActionListener(this);
quit = new JButton("Quit");
quit.addActionListener(this);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
// top, left, bottom, right
c.insets = new Insets(0, 0, 50, 0);
buttonPanel.add(play, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
// top, left, bottom, right
c.insets = new Insets(0, 0, 50, 0);
buttonPanel.add(deckConstructor, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.CENTER;
buttonPanel.add(quit, c);
}
To center it, I used GridBagConstraints#anchor and to add spacing,
I used GridBagConstraints#insets.
The original frame:
Frame using GridBagLayout:
I'm fairly new to java and I'm having a problem trying to put more than one button on a row,
at the moment I'm adding both buttons to the panel, but I don't know how to separate their x locations, i.e. they are both being added directly on to of each other.
Do I need to create a new layout or can I find a solution using what I have at the moment?
public class Question1 {
public static void main (String[] args){
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame{
MyFrame(String title){
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init(){
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
this.setContentPane(mainPanel);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf,cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JButton b = new JButton("Submit");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
b = new JButton("Cancel");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
this.pack();
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) ;
this.setVisible(true);
}
Just increment the gridx value:
JButton b = new JButton("Submit");
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
b = new JButton("Cancel");
cButton.gridx++;
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
Also you need to use the constraints created when adding your component to the grid bag layout using container.
e.g.,
import java.awt.*;
import javax.swing.*;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
private static final int GAP = 2;
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JTextField tf = new JTextField(20);
mainPanel.add(tf, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
JButton b = new JButton("Submit");
mainPanel.add(b, gbc);
b = new JButton("Cancel");
gbc.gridx++;
mainPanel.add(b, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
Try the following code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf, cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JPanel demoPanel = new JPanel();
JButton b = new JButton("Submit");
gbLayout.setConstraints(demoPanel, cButton);
demoPanel.add(b);
b = new JButton("Cancel");
// gbLayout.setConstraints(b,cButton);
demoPanel.add(b);
mainPanel.add(demoPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
I have just put the two buttons inside a JPanel and put the JPanel inside the GridBagLayout Panel !
Another problem with swing. How can I stop GridBagLayout from respacing components if one of them changes size? For example, I have few columns, in one of which there is a JLabel with text "text". When I change it to "texttext" layout manager resizes the whole column. I don't want it to do that. Is there any way to prevent it?
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ResizeIssue {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
It is visible while 9 -> 10 or anytime text changes width.
GridBagLayout ignores maximumWidth/Height. There's not an easy way to set the maximum size of the JLabel.
But, what I think you really want is the layout to not shift when the text in the JLabel changes.
That can be done by making the JLabel wide enough to hold the largest value it needs to display. For example:
jLabel1.setFont(new Font("monospace", Font.PLAIN, 12));
FontMetrics fm = jLabel1.getFontMetrics(jLabel1.getFont());
int w = fm.stringWidth("0000");
int h = fm.getHeight();
Dimension size = new Dimension(w, h);
jLabel1.setMinimumSize(size);
jLabel1.setPreferredSize(size);
Update:
To center the label text, just add:
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
This might work:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ResizeIssue2 {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
//*
c.gridy = 1;
int w = 32; //incButton.getPreferredSize().width;
for(c.gridx=0;c.gridx<3;c.gridx++) {
panel.add(Box.createHorizontalStrut(w), c);
}
// */
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
This code compiles and runs but it does not copy the text from the text field then place it into the text area.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NameGameFrame extends JFrame
{
static JTextField textfield = new JTextField(20);
static JTextArea textarea = new JTextArea(30,30);
public static void main( String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Name Game");
frame.setLocation(500,400);
frame.setSize(800,800);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel("Enter the Name or Partial Name to search:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(textarea,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
static class Action implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//This is the code that should perform the task
String name = textfield.getText();
textarea.append(name);
}
}
}
I am new to Java programming and I apologize if my questions are simplistic.
Appen below code to your program after ther declaration of button
ie. JButton buuton = new JButton("Search");
button.addActionListener(new ActionAdapter()
{
public void actionPerformed(ActionEvent ae)
{
textarea.setText(textfield.getText());
}
});