How do you add a XChart PieChart to an existing Java GUI? - java

Recently I asked a question similar to this but didn't give enough info and my code was too long for a code review. I have written a new file with the same bare bones as my previous post. Here I'm reaching the same issues once again.
When I attempt to click the Show Graph button, I get the following Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.knowm.xchart.XChartPanel.<init>(XChartPanel.java:65)
at testMain$1.actionPerformed(testMain.java:78)"
Here is my code:
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;
import org.knowm.xchart.PieChart;
import org.knowm.xchart.PieChartBuilder;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XChartPanel;
import org.knowm.xchart.style.PieStyler.AnnotationType;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.Styler.LegendPosition;
public class testMain extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel gui, choiceBar,insertPanel;
private XChartPanel chartPanel;
private JButton showGraph;
private PieChart chart;
public testMain() {
this.setTitle("Test Frame");
this.setSize(500, 500);
JPanel gui = new JPanel(new BorderLayout());
//choice bar testing
choiceBar = new JPanel(new FlowLayout());
// Radio button group
JRadioButton halfhalf = new JRadioButton("Split half");
JRadioButton quarters = new JRadioButton("Split quarters");
ButtonGroup group1 = new ButtonGroup();
group1.add(halfhalf); group1.add(quarters);
//add to choice bar
choiceBar.add(halfhalf); choiceBar.add(quarters);
//Side panel for inserting user values
insertPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(insertPanel);
groupLayout.setAutoCreateGaps(true);
groupLayout.setAutoCreateContainerGaps(true);
//Display Button
JButton showGraph = new JButton("Show Graph");
JLabel showGraphLabel = new JLabel("Finish");
//JTextfield for inserting value
JTextField value = new JTextField("value");
JLabel valueLabel = new JLabel("Insert value here:");
// Grouping JTextFields
GroupLayout.SequentialGroup groupH = groupLayout.createSequentialGroup();
GroupLayout.SequentialGroup groupV = groupLayout.createSequentialGroup();
groupH.addGroup(groupLayout.createParallelGroup().addComponent(valueLabel).addComponent(showGraphLabel));
groupH.addGroup(groupLayout.createParallelGroup().addComponent(value).addComponent(showGraph));
groupLayout.setHorizontalGroup(groupH);
groupV.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(valueLabel).addComponent(value));
groupV.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(showGraphLabel).addComponent(showGraph));
groupLayout.setVerticalGroup(groupV);
showGraph.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String valueText = value.getText();
double valueAmount = Double.parseDouble(valueText);
if (halfhalf.isSelected()) {
chartPanel = new XChartPanel(chart);
chart = new PieChartBuilder().width(600).height(400).title("Split By").theme(ChartTheme.GGPlot2).build();
chart.getStyler().setLegendVisible(false);
chart.getStyler().setAnnotationType(AnnotationType.LabelAndPercentage);
chart.getStyler().setAnnotationDistance(1.15);
chart.getStyler().setPlotContentSize(.7);
chart.getStyler().setStartAngleInDegrees(90);
chart.addSeries("1", valueAmount/2);
chart.addSeries("2", valueAmount/2);
new SwingWrapper(chart).displayChart();
gui.add(chartPanel, BorderLayout.SOUTH);
gui.validate();
gui.repaint();
}
else {
chartPanel = new XChartPanel(chart);
chart = new PieChartBuilder().width(600).height(400).title("Split By").theme(ChartTheme.GGPlot2).build();
chart.getStyler().setLegendVisible(false);
chart.getStyler().setAnnotationType(AnnotationType.LabelAndPercentage);
chart.getStyler().setAnnotationDistance(1.15);
chart.getStyler().setPlotContentSize(.7);
chart.getStyler().setStartAngleInDegrees(90);
chart.addSeries("1",valueAmount/4);
chart.addSeries("2", valueAmount/4);
chart.addSeries("3", valueAmount/4);
chart.addSeries("4", valueAmount/4);
new SwingWrapper(chart).displayChart();
gui.add(chartPanel, BorderLayout.SOUTH);
gui.validate();
gui.repaint();
}
}
});
// add to gui
gui.add(choiceBar, BorderLayout.NORTH);
gui.add(insertPanel, BorderLayout.WEST);
this.add(gui);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
testMain frame = new testMain();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
});
}
}
`
I'm trying to write a Java GUI where once the user clicks the button, the graph shows up on the same GUI. I still would like to implement this using nested layouts as I like the clean look. Someone mentioned that I could use cardLayout but I think that would be too cluttered.
Thanks, and any help is apprecaited.

Related

How can I draw multiple JLabels in different places? (icons don't show up)

I am trying to draw multiple icons in many different locations using for loop. For some reason they just don't show up. I don't know what I'm missing – only clue I found was about setting layout to null, but IntelliJ overwrites it.
Icons should show up in "mapa" panel. I tried adding them manually, but nothing changed.
My code:
package okna;
import logistyka.Walker;
import logistyka.errand.Errand;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class WalkerGUI extends JFrame{
private JPanel mainPanel;
private JLabel walkerName;
private JTextField walkerNameField;
private JLabel walkerAddress;
private JTextField walkerAddressField;
private JButton searchErrandsButton;
private JComboBox errandsComboBox;
private JLabel errandsList;
private JTextField walletValue;
private JLabel Wallet;
private JRadioButton archivalErrandsRadioButton;
private JRadioButton currentErrandsRadioButton;
private JButton payOutButton;
private JButton seeProfileButton;
private JPanel mapa;
ArrayList<Errand> masterErrandList = new ArrayList<>();
public WalkerGUI(Walker w, ArrayList<Errand> masterErrandList) {
setContentPane(mainPanel);
ArrayList<JLabel> errandsLabels = new ArrayList<>();
ImageIcon x = new ImageIcon(System.getProperty("user.dir") + "\\src\\x.png");
this.masterErrandList = masterErrandList;
for (Errand errand: masterErrandList) {
JLabel label = new JLabel("whtvr");
label.setIcon(x);
label.setLocation((int)errand.getAddress().getX(),(int)errand.getAddress().getY());
label.setMinimumSize(new Dimension(20,20));
label.setPreferredSize(new Dimension(20,20));
label.setVisible(true);
errandsLabels.add(label);
}
walkerNameField.setText(w.getDescription().getName());
walkerAddressField.setText(w.getDescription().getHomeRegion().getCurrentAddress().toString());
walletValue.setText(String.valueOf(w.getWalletSatus()));
seeProfileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new ProfileGUI(w);
frame.pack();
frame.setVisible(true);
}
});
payOutButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
w.setWalletSatus(0);
walletValue.setText(String.valueOf(w.getWalletSatus()));
}
});
}
}
You can use SpringLayout (rather than null layout). Method Errand.getAddress().getX() will return the distance of the left edge of the JLabel from the left edge of its container while Errand.getAddress().getY() will return the distance of the top edge of the JLabel from the top edge of its container.
The code in your question is not a minimal, reproducible example so the below code should be considered as a proof of concept.
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class SprinGui {
private void createAndDisplayGui() {
JFrame frame = new JFrame("Spring");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
Point[] points = new Point[]{new Point(5, 5),
new Point(5, 100),
new Point(225, 150),
new Point(250, 210)};
Class<?> meClass = getClass();
Icon[] icons = new Icon[4];
icons[0] = new ImageIcon(meClass.getResource("coffee.png"));
icons[1] = new ImageIcon(meClass.getResource("dollar.png"));
icons[2] = new ImageIcon(meClass.getResource("dynamite.png"));
icons[3] = new ImageIcon(meClass.getResource("soccer-player.png"));
for (int i = 0; i < 4; i++) {
JLabel label = new JLabel(icons[i]);
contentPane.add(label);
layout.putConstraint(SpringLayout.WEST,
label,
points[i].x,
SpringLayout.WEST,
contentPane);
layout.putConstraint(SpringLayout.NORTH,
label,
points[i].y,
SpringLayout.NORTH,
contentPane);
}
frame.setSize(450, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SprinGui instance = new SprinGui();
EventQueue.invokeLater(() -> instance.createAndDisplayGui());
}
}
This is how the GUI looks.
Note that How to Use Icons may also be helpful.

put two vertical JSplitPane on a frame java

I am a new java programmer and I use stackoverflow since my begin. I code a little "game", and it is a text-based game. Well, i begin a graphical interface, to case the text, and i would have this configuration
Basically, it is a double separation, with 3 horizontals elements. Actually, I have this:
and i want a separation
I have tried to put an other split pane on the top of the first one, like this:
package sample;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
class Fenetresaisie extends JFrame {
public static class Fenetre {
public final static int HT = 1024;
public final static int LG = 758;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame F = new JFrame("CORONAZE");
F.setExtendedState(JFrame.MAXIMIZED_BOTH);
F.setSize(HT, LG);
F.setVisible(true);
F.addWindowListener(new gestionFenetre());
ImageIcon icone = new ImageIcon("images.jpg");
JLabel image = new JLabel(icone);
JTextField textField = new JTextField();
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
textField.getText();
e.getKeyChar();
}
});
JLabel label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
panel.add(label);
JSplitPane topJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, label, textField);
// topJSplitPane.setDividerLocation(400);
JSplitPane bottomJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topJSplitPane, textField );
//i added it to have a double separation, but it give 2 sticked splitpane
F.add(topJSplitPane, BorderLayout.CENTER);
F.add(bottomJSplitPane, BorderLayout.SOUTH);
F.setVisible(true);
}
}
static class gestionFenetre extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
But it gives me two sticked splitpane :-/
Can you help me please? I hope you understand my message, because I learn English. Contact me below if you want a next phase to this issue, thanks! ^^ Here is the actual graphical test java class:
package sample;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
class Fenetresaisie extends JFrame {
public static class Fenetre {
public final static int HT = 1024;
public final static int LG = 758;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame F = new JFrame("CORONAZE");
F.setExtendedState(JFrame.MAXIMIZED_BOTH);
F.setSize(HT, LG);
F.setVisible(true);
F.addWindowListener(new gestionFenetre());
ImageIcon icone = new ImageIcon("images.jpg");
JLabel image = new JLabel(icone);
JTextField textField = new JTextField();
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
textField.getText();
e.getKeyChar();
}
});
JLabel label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
panel.add(label);
JSplitPane topJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, label, textField);
topJSplitPane.setDividerLocation(400);
// JSplitPane bottomJSplitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, topJSplitPane, textField );
//i added it to have a double separation, but it give 2 sticked splitpane
F.add(topJSplitPane, BorderLayout.CENTER);
// F.add(bottomJSplitPane, BorderLayout.SOUTH);
F.setVisible(true);
}
}
static class gestionFenetre extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
You wrote in your question
I am a new java programmer and I use stackoverflow since my begin
I really think that the way to learn Swing programming is to follow a learning curve that starts with the basics and gradually progresses. Everybody has his preferred way to learn, for example by attending a course or watching a video or reading a book. Personally I prefer books. If you do too, then I can recommend a few.
You also wrote in your question
I code a little "game"
I would say that is a very ambitious project for a beginner. While I'm sure that there are people who learn best by starting off with ambitious projects, I would say they are in the minority.
That said, the key to correctly implementing your GUI is having a deep understanding of how Swing works, in particular layout managers and Component sizes as well as at what point in the code can you set those Component sizes.
The below code will initially display your desired GUI, since I understand, from your question, that that is what you are trying to accomplish now.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class WindowCapture extends WindowAdapter implements Runnable {
private JFrame frame;
private JLabel label;
private JSplitPane splitPane;
private JSplitPane topPane;
#Override // java.lang.Runnable
public void run() {
showGui();
}
#Override // java.awt.event.WindowAdapter
public void windowOpened(WindowEvent event) {
int height = event.getWindow().getHeight();
splitPane.setDividerLocation(0.7);
double high = height * 0.7;
height = (int) Math.rint(high);
high = height * 0.8;
height = (int) Math.rint(high);
label.setPreferredSize(new Dimension(event.getWindow().getWidth(), height));
}
private JTextField createBottomPane() {
JTextField textField = new JTextField(20);
textField.setFont(new Font("Terminal", Font.BOLD, 30));
textField.setForeground(Color.RED);
textField.setBackground(Color.black);
return textField;
}
private JSplitPane createSplitPane() {
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, createTopPane(), createBottomPane());
splitPane.setDividerLocation(0.4);
return splitPane;
}
private JSplitPane createTopPane() {
label = new JLabel(">texte de l'histoire ici<");
label.setOpaque(true);
label.setForeground(Color.green);
label.setBackground(Color.BLACK);
topPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
label,
new JPanel());
topPane.setDividerLocation(0.9);
return topPane;
}
public void showGui() {
frame = new JFrame("Window Capture");
frame.addWindowListener(this);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.add(createSplitPane());
frame.setVisible(true);
}
/**
* Start here!
*/
public static void main(String[] args) {
EventQueue.invokeLater(new WindowCapture());
}
}
Here is a screen capture of the running app.

GridLayout JButton JOptionPane with ActionListener for each button

I am making a dating game in the style of the Japanese dating game with pictures and responses for fun and practice. I am trying to have a JOptionPane message dialog show up for each button in a grid layout as a response to each option. In this way it's like a logic tree. I am not used to using action listener as I am somewhat of a beginner. Here is my code. I am just not used to the syntax of doing this.
Can anyone help me?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.*;
//Implementations of packages
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
private static final int TITLE_POINTS = 3; //number of objects in text box
public NestedPanels() { //implemeted class
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
for (String btnText : BTN_TEXTS) { //BTN TEXT button titles linked to string btnText label
southBtnPanel.add(new JButton(btnText)); //add btnText label
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Review the following to get an idea of how to add action listener to buttons.
Please note the comments:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NestedPanels extends JPanel {
private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
//never used : private static final int TITLE_POINTS = 3;
public NestedPanels() {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1));
for (String btnText : BTN_TEXTS) {
JButton b = new JButton(btnText);
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonClicked(e);//when button clicked, invoke method
}
});
//alternative much shorter way to add action listener:
//b.addActionListener(e -> buttonClicked());
southBtnPanel.add(b);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
//this adds Box to the default BorderLayout.CENTER position
add(Box.createRigidArea(new Dimension(600, 600)));
add(southBtnPanel, BorderLayout.SOUTH);
}
//respond to button clicked
private void buttonClicked(ActionEvent e) {
String msg = ((JButton)e.getSource()).getActionCommand()+" pressed" ;
JOptionPane.showMessageDialog(this, msg ); //display button Action
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Date Sim 1.0");
//no need to invoke twice frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//no need to invoke twice frame.pack();
//no need to invoke twice frame.setVisible(true);
frame.getContentPane().add(mainPanel);
/*
* when posting images, use web resources that anyone can access
*
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
*this adds label to the default BorderLayout.CENTER position, which is already taken by
*the Box. Only one (last) component will be added
mainPanel.add(label);
*
*/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//remove all code which is not essential to the question
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
but I have already instantiated a parent class of extending the jpanel
Did you look at the example code provided in the tutorial???
The example there "
... extends JFrame implements ActionListener
So all you need is:
... extends JPanel implements ActionListener
Or in case you need multiple ActionListeners the more flexible approach to create a custom class.
You can use an "annonymous inner class" for the ActionListener. Something like:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String text = button.getText();
Window window = SwingUtilities.windowForComponent(button);
JOptionPane.showMessageDialog(window, text);
}
};
Then when you create the button you would do:
for (String btnText : BTN_TEXTS)
{
JButton button = new JButton( btnText );
button.addActionListener( al );
southBtnPanel.add( button );
}

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

How to add JPanel to JFrame from different classes

How do i add the JPanel to JFrame? It is really confusing me. I want to add the JPanel to the JFrame. I've tried all sorts of things including the extend but I cant get it to work.
events
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class events {
public static void main (String args[]) {
Time timeObject = new Time();
JFrame mainJFrame;
mainJFrame = new JFrame();
mainJFrame.setLayout(BorderLayout());
mainJFrame.setVisible(true);
mainJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainJFrame.setSize(600,400);
mainJFrame.setVisible(true);
mainJFrame.setLayout(new BorderLayout());
mainJFrame.setTitle("Travel Agent System");
mainJFrame.setBackground(Color.BLUE);
timeObject.selectButton();
}
}
Time
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Time{
public static void selectButton()
JButton timeButton = new JButton("Time");
JButton moneyButton = new JButton("Money");
JButton hotelButton = new JButton("Hotel");
JButton exitButton = new JButton("Exit");
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.add(timeButton,moneyButtons,hotelButton,exitButton);
}
Have a look over this source. Note the comments.
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class events {
public static void main (String args[]) {
Time timeObject = new Time();
JFrame mainJFrame;
mainJFrame = new JFrame();
// Coding by magic!
//mainJFrame.setLayout(BorderLayout());
mainJFrame.setLayout(new BorderLayout());
mainJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// don't do this, just call pack() later
//mainJFrame.setSize(600,400);
mainJFrame.setLayout(new BorderLayout());
mainJFrame.setTitle("Travel Agent System");
mainJFrame.setBackground(Color.BLUE);
timeObject.selectButton();
mainJFrame.add(timeObject.getGUI());
mainJFrame.pack();
// should be last.
mainJFrame.setVisible(true);
}
}
class Time {
private JPanel buttonPanel;
// don't use static unless necessary - it is not necessary.
//public static void selectButton() {
public void selectButton() {
JButton timeButton = new JButton("Time");
JButton moneyButton = new JButton("Money");
JButton hotelButton = new JButton("Hotel");
JButton exitButton = new JButton("Exit");
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.add(timeButton);
buttonPanel.add(moneyButton);
buttonPanel.add(hotelButton);
buttonPanel.add(exitButton);
}
public JComponent getGUI() {
return buttonPanel;
}
}
Pass JFrame object to selectButton() :
timeObject.selectButton(mainJFrame);
Then use that JFrame object to add JPanel to it.
public static void selectButton(JFrame frame)
{
JButton timeButton = new JButton("Time");
JButton moneyButton = new JButton("Money");
JButton hotelButton = new JButton("Hotel");
JButton exitButton = new JButton("Exit");
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.RED);
buttonPanel.add(timeButton,moneyButtons,hotelButton,exitButton);
frame.getContentPane().add(buttonPanel,BorderLayout.CENTER); // i've added to CENTER.
}
This will add JPanel to CENTER of your JFrame.
Here is a good example of implementing a JFrame class and then adding JPanels to the JFrame and to other JPanels.
Link to another StackOverflow question/answer

Categories

Resources