I have a weird problem and I have no idea what causes this.
I have a dialog class which simply shows an error/warning message to the screen. Interestingly, when I set the window center, the components does not appear (unless I re-size it).
However, when I change the screen location, components appear on the JPanel just fine.
I basically change this line to int x = (dim.width - w) / 3;and it works. But it doesn't when the width divided by 2. So, the dialog works anywhere but center. Please, let me know what I am missing here.
I appreciate any help!
Thank you!
Here's the code:
An MCVE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class UKDialog extends JDialog {
private JButton button1;
private JLabel message;
public UKDialog(String message, String buttonText) {
this.button1 = new JButton(buttonText);
this.message = new JLabel(message);
setWarning();
}
public void setWarning() {
this.setModal(true);
this.setAlwaysOnTop(true);
if (this.message.getText().length() <= 30) {
this.setMaximumSize(new Dimension(650, 300));
this.setMinimumSize(new Dimension(650, 300));
this.setPreferredSize(new Dimension(650, 300));
} else if (this.message.getText().length() > 30) {
this.setMaximumSize(new Dimension(870, 300));
this.setMinimumSize(new Dimension(870, 300));
this.setPreferredSize(new Dimension(870, 300));
}
this.setLayout(new BorderLayout());
JPanel messagePanel = new JPanel();
messagePanel.setBorder(BorderFactory.createEtchedBorder());
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.setBorder(BorderFactory.createEtchedBorder());
buttonPanel.setPreferredSize(new Dimension(600, 100));
this.message.setFont(new Font("Calibri", Font.BOLD, 40));
this.button1.setPreferredSize(new Dimension(230, 80));
this.button1.setFont(new Font("Calibri", Font.BOLD, 45));
this.button1.setBackground(new java.awt.Color(139, 71, 137));
this.button1.setForeground(java.awt.Color.white);
this.button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(evt);
}
});
messagePanel.add(this.message, BorderLayout.CENTER);
buttonPanel.add(this.button1);
this.add(messagePanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
// calculate the new location of the window
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = this.getSize().width;
int h = this.getSize().height;
int x = (dim.width - w) / 2;
int y = (dim.height - h) / 5;
this.setLocation(x, y);
this.setVisible(true);
}
protected void okActionPerformed(ActionEvent evt) {
UKDialog.this.dispose();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame("Main GUI");
JButton button = new JButton(new AbstractAction("Push Me") {
#Override
public void actionPerformed(ActionEvent e) {
String message = "Message is Long Enough???";
String buttonText = "Button";
UKDialog ukDialog = new UKDialog(message, buttonText);
}
});
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 400));
panel.add(button);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
This is my class calls the warning class with the main method.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneLayout;
import javax.swing.WindowConstants;
public class PAndDeliveryNotification extends JDialog {
private JButton button1;
private JLabel messageTitle;
private JTextField text;
private boolean reply;
private String typedText;
private ArrayList<String[]> remainingInvoices;
private String stopNum = null;
private String currentStopNum, lastStopNum;
public PAndDeliveryNotification(ArrayList<String[]> rInvoices, String buttonText1) {
this.button1 = new JButton(buttonText1);
this.remainingInvoices = rInvoices;
}
public void setDelivStopNo() throws IOException {
BufferedImage image = null;
try {
image = ImageIO.read(new File("images/uk.png"));
} catch (IOException e) {
}
this.setIconImage(image);
//frame properties
this.setModal(true);
this.setAlwaysOnTop(true);
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.setLayout(new BorderLayout());
//frame size
this.setPreferredSize(new Dimension(900, 600));
this.setMaximumSize(new Dimension(900, 600));
this.setMinimumSize(new Dimension(900, 600));
JPanel upperPanel = new JPanel(new WrapLayout());
upperPanel.setBorder(BorderFactory.createEtchedBorder());
for (int i = 0; i < this.remainingInvoices.size(); i++) {
String[] invoice;
invoice = (String[]) this.remainingInvoices.get(i);
if (i == 0) {
this.currentStopNum = invoice[0];
}
if (i == this.remainingInvoices.size() - 1) {
this.lastStopNum = invoice[0];
}
StopItem item = new StopItem(invoice);
item.setPreferredSize(new Dimension(770, 120));
upperPanel.add(item);
}
upperPanel.repaint();
upperPanel.revalidate();
JScrollPane pane = new JScrollPane(upperPanel);
pane.setPreferredSize(new Dimension(770, 600));
pane.getVerticalScrollBar().setPreferredSize(new Dimension(50, 0));
pane.setLayout(new ScrollPaneLayout());
this.add(pane, BorderLayout.CENTER);
JPanel lowerPanel = new JPanel(new BorderLayout());
lowerPanel.setBorder(BorderFactory.createEtchedBorder());
lowerPanel.setPreferredSize(new Dimension(600, 100));
JPanel messagePanel = new JPanel(new FlowLayout());
messagePanel.setPreferredSize(new Dimension(600, 80));
JPanel buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(240, 80));
this.messageTitle = new JLabel("Enter Delivery Stop Number:");
this.messageTitle.setFont(new Font("Calibri", Font.BOLD, 40));
this.messageTitle.setPreferredSize(new Dimension(480, 80));
this.text = new JTextField(3);
this.text.setPreferredSize(new Dimension(100, 80));
this.text.setFont(new Font("Calibri", Font.BOLD, 40));
this.text.setHorizontalAlignment(JTextField.CENTER);
this.text.requestFocus();
Runtime.getRuntime().exec("cmd /c tabtip.exe");
this.button1.setPreferredSize(new Dimension(230, 80));
this.button1.setFont(new Font("Calibri", Font.BOLD, 45));
this.button1.setBackground(new java.awt.Color(139, 71, 137));
this.button1.setForeground(java.awt.Color.white);
this.button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveStopNumActionPerformed(evt);
}
});
messagePanel.add(this.messageTitle);
messagePanel.add(this.text);
buttonPanel.add(this.button1);
lowerPanel.add(messagePanel, BorderLayout.WEST);
lowerPanel.add(buttonPanel, BorderLayout.EAST);
this.add(pane, BorderLayout.CENTER);
this.add(lowerPanel, BorderLayout.SOUTH);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// calculate the new location of the window
int w = this.getSize().width;
int h = this.getSize().height;
int x = (dim.width - w) / 2;
int y = 0;
this.setLocation(x, y);
this.setVisible(true);
}
private void saveStopNumActionPerformed(ActionEvent evt) {
this.stopNum = this.text.getText();
try {
if (stopNum == null) {
new UKDialog("Fields cannot be empty!", "OK");
return;
} else if (Integer.parseInt(stopNum) < Integer.parseInt(this.currentStopNum)) {
new UKDialog("Delivery cannot be before pick up!", "OK");
return;
} else if (Integer.parseInt(stopNum) > Integer.parseInt(this.lastStopNum) + 1) {
new UKDialog("Enter stop number between " + this.currentStopNum + 1 + " and "
+ this.lastStopNum, "OK");
return;
}
} catch (NumberFormatException e) {
new UKDialog("Please enter numeric values!", "OK");
return;
}
System.out.println(this.stopNum);
this.setVisible(false);
this.dispose();
}
public String getStopNum() {
return this.stopNum;
}
private class StopItem extends JPanel {
private JPanel numPanel = new JPanel();
private JLabel itemNumber = new JLabel();
private JPanel leftPanel = new JPanel();
private JLabel invNoLbl = new JLabel();
private JLabel consigneeLbl = new JLabel();
private JLabel locationLbl = new JLabel();
private final String pUStopNo;
private final String invoiceNo;
private final String consignee;
private final String location;
public StopItem(String[] invoice) {
this.pUStopNo = invoice[0];
this.invoiceNo = invoice[1];
this.consignee = invoice[2];
this.location = invoice[3];
//Left and numberpanels
this.numPanel.setLayout(new BorderLayout());
this.numPanel.setPreferredSize(new Dimension(80, 80));
this.leftPanel.setLayout(new BorderLayout());
this.leftPanel.setPreferredSize(new Dimension(200, 90));
//number panel
this.itemNumber.setFont(new java.awt.Font("Lucida Grande", Font.BOLD, 45));
this.itemNumber.setText(String.valueOf(" " + pUStopNo));
//this.numPanel.setBorder(BorderFactory.createEtchedBorder());
this.numPanel.add(this.itemNumber);
//Main panel
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createLineBorder(Color.black, 2));
this.invNoLbl.setText("Invoice #: " + this.invoiceNo);
this.invNoLbl.setFont(new java.awt.Font("Calibri", Font.PLAIN, 35));
this.consigneeLbl.setText("Consignee: " + this.consignee);
this.consigneeLbl.setFont(new java.awt.Font("Calibri", Font.PLAIN, 35));
this.locationLbl.setText("Location: " + this.location);
this.locationLbl.setFont(new java.awt.Font("Calibri", Font.PLAIN, 35));
this.leftPanel.add(this.invNoLbl, BorderLayout.NORTH);
this.leftPanel.add(this.consigneeLbl, BorderLayout.CENTER);
this.leftPanel.add(this.locationLbl, BorderLayout.SOUTH);
// add all the components to the frame
this.add(this.numPanel, BorderLayout.WEST);
this.add(this.leftPanel, BorderLayout.CENTER);
}
}
public static void main(String[] args) throws IOException {
String[] array1 = {"6", "444555", "Ali Murtaza Sumer", "Carson, Ca 90746"};
String[] array2 = {"7", "444666", "Hasan Huseyin Karabiber", "Los Angeles, Ca 90746"};
String[] array3 = {"8", "444777", "Mustafa Tinaztepe", "Macomb, IL 61455"};
String[] array4 = {"9", "444888", "Berkay Surmeli", "Chicago, IL 60625"};
String[] array5 = {"6", "444555", "Ali Murtaza Sumer", "Carson, Ca 90746"};
String[] array6 = {"7", "444666", "Hasan Huseyin Karabiber", "Los Angeles, Ca 90746"};
String[] array7 = {"8", "444777", "Mustafa Tinaztepe", "Macomb, IL 61455"};
String[] array8 = {"9", "444888", "Berkay Surmeli", "Chicago, IL 60625"};
ArrayList<String[]> aL = new ArrayList<>();
aL.add(array1);
aL.add(array2);
aL.add(array3);
aL.add(array4);
PAndDeliveryNotification question = new PAndDeliveryNotification(aL, "SAVE");
question.setDelivStopNo();
}
}
Edit:
You using two JDialog exending Classes. Both of them has setAlwaysOnTop(true) and setModal(true) therefore both are competing for the view. Maybe you should use a JFrame and JDialog
Related
I'm doing this as a challenge for myself. My problem is that when I click on the button, the content pane appears plain even if the JPanel has components in it.
I've tried adding the components on the frame but I get an error: >Cannot read field "parent" because "comp" is null.
I've tried other layout on JFrame and JPanel and still it didn't show.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class test implements ActionListener{
public static void main(String [] args) {
new test();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton ,backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public test(){
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080,720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void cubePanel(){
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.decode("#FAF7FH"));
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == sphereButton){
new sphereFrame();
frame.dispose();
}
if(e.getSource() == rightCylinderButton){
new rightCylinderFrame();
frame.dispose();
}
if(e.getSource() == rightConeButton){
new rightConeFrame();
frame.dispose();
}
if(e.getSource() == rectangularPrismButton){
new rectangularPrismFrame();
frame.dispose();
}
if(e.getSource() == triangularPrismButton){
new triangularPrismFrame();
frame.dispose();
}
if(e.getSource() == cubeButton){
frame.getContentPane().removeAll();
frame.add(cubePanel);
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
Here's the GUI I created.
Press the "Cube" button to bring up the page for the cube calculation.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The JFrame has a default BorderLayout and holds the main JPanel. The main JPanel uses a CardLayout to display the various calculation JPanels. Using a CardLayout is much easier than managing multiple JFrames and provides a nicer user experience.
I used Swing layout managers to position the Swing components on the various JPanels.
The start JPanel consists of two subordinate JPanels. The title JPanel uses a FlowLayout to display the title. The button JPanel uses a GridLayout to display the various calculation JButtons. You can create complex JPanels by nesting multiple simple JPanels.
The cube calculation JPanel was the only one you had in your code, so it was the only one I created. I made it a method, but you can create a separate class for each of the calculations. The cube calculation JPanel uses a GridBagLayout to create a form-like JPanel. I used lambda expressions to create the ActionListener for each of the JButtons, since they were so simple.
I made the start JPanel button ActionListener a separate class just to get the code away from the for loop that creates the JButtons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class CardLayoutGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutGUI());
}
private CardLayout cardLayout;
private JTextField edgeTextField, surfaceAreaSolutionTextField;
private JPanel mainPanel;
#Override
public void run() {
JFrame frame = new JFrame("Calculating for Surface Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createStartPanel(), "Start");
panel.add(createCubeCalculationPanel(), "Cube");
return panel;
}
private JPanel createStartPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createTitlePanel(), BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(Font.DIALOG, Font.PLAIN, 36);
JLabel label = new JLabel("Calculator for the Surface Area of:");
label.setFont(font);
panel.add(label);
return panel;
}
private JPanel createButtonPanel() {
String[] text = { "Sphere", "Right Cylinder", "Right Cone",
"Rectangular Prism", "Triangular Prism", "Cube",
"Square Pyramid", "Rectangular Pyramid", "Ellipsoid",
"Tetrahedron" };
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(null, Font.PLAIN, 24);
ButtonListener listener = new ButtonListener();
for (String s : text) {
JButton button = new JButton(s);
button.addActionListener(listener);
button.setFont(font);
panel.add(button);
}
return panel;
}
private JPanel createCubeCalculationPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font titleFont = new Font(null, Font.PLAIN, 32);
Font font = new Font(null, Font.PLAIN, 16);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.weighty = 1.0;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("SA = 6a²");
label.setFont(titleFont);
panel.add(label, gbc);
gbc.gridwidth = 1;
gbc.gridy++;
label = new JLabel("Edge:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
edgeTextField = new JTextField(10);
edgeTextField.setFont(font);
panel.add(edgeTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("SA:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
surfaceAreaSolutionTextField = new JTextField(10);
surfaceAreaSolutionTextField.setFont(font);
surfaceAreaSolutionTextField.setEditable(false);
panel.add(surfaceAreaSolutionTextField, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(event -> {
double edge = Double.valueOf(edgeTextField.getText());
double sa = 6.0 * edge * edge;
surfaceAreaSolutionTextField.setText(Double.toString(sa));
});
calculateButton.setFont(font);
panel.add(calculateButton, gbc);
gbc.gridy++;
JButton backButton = new JButton("Back");
backButton.addActionListener(event -> {
cardLayout.show(mainPanel, "Start");
});
backButton.setFont(font);
panel.add(backButton, gbc);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
cardLayout.show(mainPanel, text);
}
}
}
Try this :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class Test2 implements ActionListener {
public static void main(String[] args) {
new Test2();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton, backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public Test2() {
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public Container cubePanel() {
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.getColor("#FAF7FH"));
return container;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sphereButton) {
new sphereFrame();
frame.dispose();
}
if (e.getSource() == rightCylinderButton) {
new rightCylinderFrame();
frame.dispose();
}
if (e.getSource() == rightConeButton) {
new rightConeFrame();
frame.dispose();
}
if (e.getSource() == rectangularPrismButton) {
new rectangularPrismFrame();
frame.dispose();
}
if (e.getSource() == triangularPrismButton) {
//new triangularPrismFrame();
frame.dispose();
}
if (e.getSource() == cubeButton) {
frame.getContentPane().removeAll();
frame.add(cubePanel());
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
}
I'm making a street fighter game in java, I have all the background pictures finished, and I'm trying to add the characters onto the background, but in the output the character picture keeps appearing next to the background instead of on top of it. I want the character to appear on top of the background, just like a normal street fighter game.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.Border;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class CastleFighter extends JFrame {
Image image;
public static void main(String[] args) {
CastleFighter angela = new CastleFighter();
angela.runIt();
}
public void runIt() {
final JFrame frame = new JFrame("Castle Fighter");
frame.setSize(500, 477);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pa = new JPanel();
JButton ba1 = new JButton("Start");
ba1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
final JFrame frame2 = new JFrame("Menu");
frame2.setDefaultCloseOperation(HIDE_ON_CLOSE);
JPanel pa2 = new JPanel();
frame2.add(pa2);
ImageIcon iii = new ImageIcon(this.getClass().getResource("fight.gif"));
JLabel imageLabel2 = new JLabel();
imageLabel2.setIcon(iii);
pa2.add(imageLabel2, java.awt.BorderLayout.CENTER);
frame2.setVisible(true);
frame2.pack();
frame2.requestFocus();
imageLabel2.setLayout(new GridLayout(3, 0));
JButton ba2 = new JButton("How to play");
ba2.setFont(new Font("Merriweather", Font.PLAIN, 28));
imageLabel2.add(ba2, BorderLayout.SOUTH);
ba2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2.dispose();
final JFrame frame3 = new JFrame("How to play");
frame3.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel pa3 = new JPanel();
frame3.add(pa3);
JButton ba5 = new JButton("Return to menu");
ba5.setFont(new Font("Merriweather", Font.PLAIN, 28));
ba5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame3.dispose();
frame2.setVisible(true);
}
});
pa3.setLayout(new BorderLayout());
pa3.add(ba5, BorderLayout.SOUTH);
ImageIcon iiiii = new ImageIcon(this.getClass().getResource("ezgif.com-crop-7.gif"));
JLabel imageLabel4 = new JLabel();
imageLabel4.setIcon(iiiii);
pa3.add(imageLabel4, java.awt.BorderLayout.CENTER);
frame3.setVisible(true);
frame3.pack();
frame3.requestFocus();
}
});
JButton ba3 = new JButton("Start game");
ba3.setFont(new Font("RussoOne", Font.PLAIN, 28));
imageLabel2.add(ba3, BorderLayout.CENTER);
ba3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2.dispose();
final JFrame frame4 = new JFrame("Level one");
frame4.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel pa4 = new JPanel();
frame4.add(pa4);
ImageIcon iiii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-7.gif"));
JLabel imageLabel3 = new JLabel();
imageLabel3.setIcon(iiii);
pa4.add(imageLabel3, java.awt.BorderLayout.CENTER);
ImageIcon i14 = new ImageIcon(this.getClass().getResource("fightercharacter.gif"));
JLabel imageLabel14 = new JLabel();
imageLabel14.setIcon(i14);
pa4.add(imageLabel14, java.awt.BorderLayout.NORTH);
JButton ba6 = new JButton("menu");
ba6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame4.dispose();
frame2.setVisible(true);
}
});
pa4.add(ba6);
JButton ba7 = new JButton("Level two");
ba7.setSize(400, 200);
pa4.add(ba7);
ba7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame4.dispose();
final JFrame frame6 = new JFrame("Level two");
frame6.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame6.setVisible(true);
JPanel pa6 = new JPanel();
frame6.add(pa6);
ImageIcon iiiiiii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-6.gif"));
JLabel imageLabel6 = new JLabel();
imageLabel6.setIcon(iiiiiii);
pa6.add(imageLabel6, BorderLayout.CENTER);
frame6.pack();
frame6.requestFocus();
JButton ba7 = new JButton("menu");
pa6.add(ba7, BorderLayout.SOUTH);
ba7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame6.dispose();
frame2.setVisible(true);
}
});
JButton ba9 = new JButton("Level one");
pa6.add(ba9, BorderLayout.SOUTH);
ba9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame6.dispose();
frame4.setVisible(true);
}
});
frame6.setVisible(true);
frame6.pack();
frame6.requestFocus();
}
});
frame4.setVisible(true);
frame4.pack();
frame4.requestFocus();
}
});
JButton ba4 = new JButton("Quit game");
ba4.setFont(new Font("MerriWeather", Font.PLAIN, 28));
imageLabel2.add(ba4, BorderLayout.WEST);
ba4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame2.requestFocus();
ba2.setOpaque(false);
ba2.setContentAreaFilled(false);
ba2.setBorderPainted(false);
ba2.setForeground(Color.WHITE);
ba3.setOpaque(false);
ba3.setContentAreaFilled(false);
ba3.setBorderPainted(false);
ba3.setForeground(Color.WHITE);
ba4.setOpaque(false);
ba4.setContentAreaFilled(false);
ba4.setBorderPainted(false);
ba4.setForeground(Color.WHITE);
}
});
ba1.setPreferredSize(new Dimension(100, 100));
ba1.setFont(new Font("RussoOne", Font.PLAIN, 28));
ba1.setBackground(Color.BLUE);
ba1.setOpaque(true);
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(ba1, BorderLayout.SOUTH);
ImageIcon ii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-2.gif"));
JLabel imageLabel = new JLabel();
imageLabel.setIcon(ii);
pa.add(imageLabel, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
frame.requestFocus();
}
}
I am trying to get some Java skills back because i worked for a long time in webdevelopment. Now I am just create a main Jframe where are a little Menu and a Class createSchueler extends JPanel.
So what I want to do if you go into the Menu click Neu > Schueler
A new Jpanel should be created and added to the Window
Main Class
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 807, 541);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel createSchueler = new createSchueler();
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Neu");
mnNewMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
createSchueler.setVisible(true);
frame.getContentPane().add(createSchueler);
}
});
menuBar.add(mnNewMenu);
JMenuItem mntmSchler = new JMenuItem("Sch\u00FCler");
mnNewMenu.add(mntmSchler);
JMenu mnBearbeiten = new JMenu("Bearbeiten");
menuBar.add(mnBearbeiten);
JMenuItem mntmSchler_1 = new JMenuItem("Sch\u00FCler");
mnBearbeiten.add(mntmSchler_1);
}
}
The createSchueler Class extends JPanel that i want to add to the frame
public class createSchueler extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Create the panel.
*/
public createSchueler() {
setLayout(null);
JLabel lblNeuenSchuelerErstellen = new JLabel("Neuen Schueler erstellen");
lblNeuenSchuelerErstellen.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblNeuenSchuelerErstellen.setBounds(29, 27, 268, 27);
add(lblNeuenSchuelerErstellen);
JLabel lblVorname = new JLabel("Vorname");
lblVorname.setBounds(29, 102, 46, 14);
add(lblVorname);
textField = new JTextField();
textField.setBounds(97, 99, 172, 20);
add(textField);
textField.setColumns(10);
JLabel lblNachname = new JLabel("Nachname");
lblNachname.setBounds(29, 133, 69, 14);
add(lblNachname);
textField_1 = new JTextField();
textField_1.setBounds(97, 130, 172, 20);
add(textField_1);
textField_1.setColumns(10);
JLabel lblGeburtstag = new JLabel("Geburtstag");
lblGeburtstag.setBounds(29, 169, 69, 14);
add(lblGeburtstag);
textField_2 = new JTextField();
textField_2.setBounds(97, 166, 172, 20);
add(textField_2);
textField_2.setColumns(10);
ButtonGroup bg = new ButtonGroup();
JRadioButton rdbtnMnnlich = new JRadioButton("M\u00E4nnlich");
rdbtnMnnlich.setBounds(29, 206, 69, 23);
bg.add(rdbtnMnnlich);
JRadioButton rdbtnWeiblich = new JRadioButton("Weiblich");
rdbtnWeiblich.setBounds(97, 206, 109, 23);
bg.add(rdbtnWeiblich);
}
}
Everything is important hopefully :D
Use a CardLayout to swap JPanels rather than adding them by hand. If you must add them by hand, be sure that the receiving container's layout manager is up to the task and handles the addition well. For example BorderLayout would take it fine, but GroupLayout won't. If you do add or remove by hand, call revalidate(); and repaint() on the container after these changes.
Also you're using null layout in your added JPanel and contentPane which will completely ruin it's preferredSize calculation. Never use this layout. Learn to use and then use the layout managers. This is your main mistake.
For more on this, please read: Why is it frowned upon to use a null layout in Swing?
For example:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MainGui {
public static final String SCHUELER_PANEL = "Schueler Panel";
public static final String EMPTY = "Empty Panel";
private JPanel mainPanel = new JPanel();
private JMenuBar menuBar = new JMenuBar();
private CardLayout cardLayout = new CardLayout();
private SchuelerPanel schuelerPanel = new SchuelerPanel();
public MainGui() {
mainPanel.setLayout(cardLayout);
mainPanel.add(new JLabel(), EMPTY); // empty label
mainPanel.add(schuelerPanel, SCHUELER_PANEL);
JMenu menu = new JMenu("Panel");
menu.add(new JMenuItem(new SwapPanelAction(EMPTY)));
menu.add(new JMenuItem(new SwapPanelAction(SCHUELER_PANEL)));
menuBar.add(menu);
}
public JPanel getMainPanel() {
return mainPanel;
}
public JMenuBar getMenuBar() {
return menuBar;
}
#SuppressWarnings("serial")
private class SwapPanelAction extends AbstractAction {
public SwapPanelAction(String title) {
super(title);
int mnemonic = (int) title.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(mainPanel, (String) getValue(NAME));
}
}
private static void createAndShowGui() {
MainGui mainGui = new MainGui();
JFrame frame = new JFrame("Main Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainGui.getMainPanel());
frame.setJMenuBar(mainGui.getMenuBar());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
and
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class SchuelerPanel extends JPanel {
private static final String TITLE_TEXT = "Lorem Ipsum Dolor Sit Amet";
public static final String[] LABEL_STRINGS = {"Monday", "Tuesday", "Wednesday"};
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public SchuelerPanel() {
JLabel titleLabel = new JLabel(TITLE_TEXT, JLabel.CENTER);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
for (int i = 0; i < LABEL_STRINGS.length; i++) {
addToPanel(labelFieldPanel, LABEL_STRINGS[i], i);
}
// Don't do what I'm doing here: avoid "magic" numbers!
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(10, 10));
add(titleLabel, BorderLayout.PAGE_START);
add(labelFieldPanel, BorderLayout.CENTER);
}
// get the text from the JTextField based on the JLabel associated with it
public String getText(String labelText) {
JTextField textField = labelFieldMap.get(labelText);
if (textField == null) {
throw new IllegalArgumentException("For labelText: " + labelText);
}
return textField.getText();
}
private void addToPanel(JPanel gblUsingPanel, String labelString, int row) {
JLabel label = new JLabel(labelString);
label.setFont(label.getFont().deriveFont(Font.BOLD));
JTextField textField = new JTextField(10);
labelFieldMap.put(labelString, textField);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(5, 5, 5, 5);
gblUsingPanel.add(label, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gblUsingPanel.add(textField, gbc);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SchuelerPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SchuelerPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
when I compile and run my code everything seems to work fine except the JButton does not appear. I'm adding it to a JPanel that is on the frame. I'm new so I might not know what to lookout for here. Thanks!
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class TemperatureConverter extends JFrame{
//declarations
private JLabel celJLabel, farJLabel;
private JTextField celJTextField, farJTextField;
private JSlider sliderJSlider;
private JButton closeButton;
private TitledBorder border;
private JPanel topPanel, bottomPanel;
double celsiusDegrees, farenheitDegrees, sliderValue;
DecimalFormat decimalFormat = new DecimalFormat("#.0");
public TemperatureConverter()
{
createUserInterface();
}
public void createUserInterface()
{
//create the JFrame
Container frame = getContentPane();
frame.setBackground(Color.white);
frame.setLayout(null);
border = new TitledBorder("Convert between C & F");
border.setTitleColor(Color.black);
border.setTitleFont(new Font("Default", Font.ITALIC, 12));
border.setTitleJustification(TitledBorder.LEFT);
border.setTitlePosition(TitledBorder.TOP);
topPanel = new JPanel();
topPanel.setBounds(20,10,360,300);
topPanel.setForeground(Color.black);
topPanel.setBackground(Color.white);
topPanel.setLayout(null);
topPanel.setBorder(border);
frame.add(topPanel);
bottomPanel = new JPanel();
bottomPanel.setBounds(20,310,360,50);
bottomPanel.setForeground(Color.black);
bottomPanel.setBackground(Color.white);
bottomPanel.setLayout(null);
frame.add(bottomPanel);
celJLabel = new JLabel();
celJLabel.setBounds(120, 200, 60, 20);
celJLabel.setBackground(Color.white);
celJLabel.setFont(new Font("Default", Font.PLAIN, 12));
celJLabel.setText("Celcius");
celJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(celJLabel);
farJLabel = new JLabel();
farJLabel.setBounds(120, 220, 60, 20);
farJLabel.setBackground(Color.white);
farJLabel.setFont(new Font("Default", Font.PLAIN, 12));
farJLabel.setText("Faranheit");
farJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(farJLabel);
celJTextField = new JTextField();
celJTextField.setBounds(195,200, 50, 15);
celJTextField.setFont(new Font("Default", Font.PLAIN, 12));
celJTextField.setHorizontalAlignment(JTextField.CENTER);
celJTextField.setForeground(Color.black);
celJTextField.setBackground(Color.white);
topPanel.add(celJTextField);
farJTextField = new JTextField();
farJTextField.setBounds(195,225, 50, 15);
farJTextField.setFont(new Font("Default", Font.PLAIN, 12));
farJTextField.setHorizontalAlignment(JTextField.CENTER);
farJTextField.setForeground(Color.black);
farJTextField.setBackground(Color.white);
topPanel.add(farJTextField);
sliderJSlider = new JSlider(JSlider.HORIZONTAL, 0,100,0);
sliderJSlider.setBounds(20, 20, 310, 120);
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
sliderJSlider.setForeground(Color.black);
sliderJSlider.setBackground(Color.white);
topPanel.add(sliderJSlider);
sliderJSlider.addChangeListener(
new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
sliderStateChanged(event);
}
}
);
closeButton = new JButton();
closeButton.setBounds(140, 250, 75, 20);
closeButton.setFont(new Font("Default", Font.PLAIN,12));
closeButton.setText("Close");
closeButton.setForeground(Color.black);
closeButton.setBackground(Color.white);
bottomPanel.add(closeButton);
closeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
closeActionPerformed(event);
}
}
);
setTitle("Temperature Converter");
setSize(400,400);
setVisible(true);
}
public static void main(String[] args)
{
TemperatureConverter application = new TemperatureConverter();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void sliderStateChanged(ChangeEvent event)
{
farenheitDegrees = sliderJSlider.getValue();
calculateCelsiusTemperature();
}
public void calculateCelsiusTemperature()
{
celsiusDegrees = (farenheitDegrees - 32)*5.0/9.0;
outputTemps();
}
public void outputTemps()
{
celJTextField.setText(decimalFormat.format(celsiusDegrees));
farJTextField.setText(decimalFormat.format(farenheitDegrees));
}
public void closeActionPerformed(ActionEvent event)
{
TemperatureConverter.this.dispose();
}
}
I'd follow the advice from the comments, use a proper layout manager.
The actual fault, is the placement of the close button within the bottom panel.
closeButton.setBounds(140, 250, 75, 20);
This might be a typo or a misunderstanding of the coordinate system, each new panel has its own private system where (0,0) is the top left of at component. The button is at (140, 250), however bottomPanel is only 360 x 50, so it is outside the visible bounds..
Try changing to
closeButton.setBounds(0, 0, 75, 20);
Your first and major mistake is this: topPanel.setLayout(null);. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
The solution is simple: learn about and how to use the layout managers, and then use them. You can find links to the Swing tutorials including those for the layout managers and other Swing resources here: Swing Info
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
JPanel textFieldWrapperPanel = new JPanel(new GridBagLayout());
textFieldWrapperPanel.add(textFieldPanel);
JPanel conversionPanel = new JPanel(new BorderLayout());
conversionPanel.setBorder(BorderFactory.createTitledBorder("Foo"));
conversionPanel.setLayout(new BorderLayout());
conversionPanel.add(sliderJSlider, BorderLayout.PAGE_START);
conversionPanel.add(textFieldWrapperPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomPanel.add(closeButton);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(conversionPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
return gbc;
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
;
if (isPreferredSizeSet()) {
super.getPreferredSize();
}
int prefW = Math.max(PREF_W, superSize.width);
return new Dimension(prefW, superSize.height);
}
private static void createAndShowGui() {
TempConverter mainPanel = new TempConverter();
JFrame frame = new JFrame("TempConverter");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Now you might say that this looks more complicated, and perhaps it is, but what happens when you want to add another JTextField and JLabel to represent the Kelvin temperature scale? For your GUI, you'll need to resize the GUI and recalculate the position of any component that may be effected by adding the new components. For my GUI, you just need to add a few new lines, and the chance of the changes causing a bug in my code is much smaller than that of your changes. e.g. please note the changes below just require 3 lines of code. Everything else remains the same:
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JTextField KelvinJTextField = new JTextField(10); // !!! Added
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
// !!! added
textFieldPanel.add(new JLabel("Kelvin:"), createGbc(0, 2));
textFieldPanel.add(KelvinJTextField, createGbc(1, 2));
So, I have a program with JTextArea with DocumentFilter. It should (among other things) filter out tab characters and prevent them to be entered in the JTextArea completely.
Well, it works well when I type, but I can still paste it in. i shouldn't be able to, according to the code...
Below is kind of a SSCCE. Just run it, press ctrl+n and enter. All the colored fileds are JTextAreas with same DocumentFilter. The filter itself is the first class (DefaultDocFilter), only thing you need to look into.
package core;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
class DefaultDocFilter extends DocumentFilter
{
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
System.out.print(str);
fb.insertString(offs, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
str.substring(0, spaceLeft);
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.insertString(offs, str, a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n") || str.equals("\t"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 200)
{
str.replaceAll("\n", " ");
str.replaceAll("\t", " ");
fb.replace(offs, length, str, a);
}
else
{
int spaceLeft = 200 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
}
}
#SuppressWarnings("serial")
class DefaultFont extends Font
{
public DefaultFont()
{
super("Arial", PLAIN, 20);
}
}
#SuppressWarnings("serial")
class Page extends JPanel
{
public JPanel largePage;
public int content;
public Page(JPanel panel, int index)
{
largePage = new JPanel();
largePage.setLayout(new BoxLayout(largePage, BoxLayout.Y_AXIS));
largePage.setMaximumSize(new Dimension(794, 1123));
largePage.setPreferredSize(new Dimension(794, 1123));
largePage.setAlignmentX(Component.CENTER_ALIGNMENT);
largePage.setBackground(Color.WHITE);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
setMaximumSize(new Dimension(556, 931));
setBackground(Color.LIGHT_GRAY);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new Box.Filler(new Dimension(556, 0), new Dimension(556, 931), new Dimension(556, 931)));
largePage.add(this);
largePage.add(new Box.Filler(new Dimension(0, 96), new Dimension(0, 96), new Dimension(0, 96)));
panel.add(largePage, index);
panel.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
content = 0;
Main.pages.add(this);
}
}
#SuppressWarnings("serial")
class Heading extends JTextArea
{
public boolean type;
public AbstractDocument doc;
public ArrayList<JPanel/*Question*/> questions;
public ArrayList<JPanel/*List*/> list;
public Heading(boolean segment, Page page)
{
type = segment;
setBackground(Color.RED);
setFont(new Font("Arial", Font.BOLD, 20));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 10, 0, Color.WHITE);
setBorder(BorderFactory.createCompoundBorder(out, in));
setLineWrap(true);
setWrapStyleWord(true);
setText("Heading 1 Heading 1 Heading 1 Heading 1");
doc = (AbstractDocument)this.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
page.add(this, 0);
page.content++;
if (type)
{
questions = new ArrayList<JPanel>();
}
else
{
list = new ArrayList<JPanel>();
}
}
}
#SuppressWarnings("serial")
class Question extends JPanel
{
public JPanel questionArea, numberArea, answerArea;
public JLabel number;
public JTextArea question;
public AbstractDocument doc;
public Question(Page page, int pageNum, int index)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE));
questionArea = new JPanel();
questionArea.setLayout(new BoxLayout(questionArea, BoxLayout.X_AXIS));
questionArea.setBorder(BorderFactory.createMatteBorder(0, 0, 8, 0, Color.WHITE));
numberArea = new JPanel();
numberArea.setLayout(new BorderLayout());
numberArea.setBackground(Color.WHITE);
number = new JLabel(pageNum+". ", JLabel.RIGHT);
number.setMinimumSize(new Dimension(100, 20));
number.setPreferredSize(new Dimension(100, 20));
number.setMaximumSize(new Dimension(100, 20));
number.setFont(new Font("Arial", Font.PLAIN, 17));
numberArea.add(number, BorderLayout.NORTH);
questionArea.add(numberArea);
question = new JTextArea();
question.setFont(new Font("Arial", Font.PLAIN, 17));
question.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setBackground(Color.GREEN);
question.setText("Is this the first question?");
doc = (AbstractDocument)question.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
questionArea.add(question);
add(questionArea);
answerArea = new JPanel();
answerArea.setLayout(new BoxLayout(answerArea, BoxLayout.Y_AXIS));
add(answerArea);
page.add(this, index);
page.content++;
}
}
#SuppressWarnings("serial")
class Answer extends JPanel
{
public JPanel letterArea;
public JLabel letter;
public JTextArea answer;
public AbstractDocument doc;
public Answer(Question q, int index)
{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
letterArea = new JPanel();
letterArea.setLayout(new BorderLayout());
letterArea.setBackground(Color.WHITE);
letter = new JLabel((char)(index+96)+") ", JLabel.RIGHT);
letter.setMinimumSize(new Dimension(150, 20));
letter.setPreferredSize(new Dimension(150, 20));
letter.setMaximumSize(new Dimension(150, 20));
letter.setFont(new Font("Arial", Font.PLAIN, 17));
letterArea.add(letter, BorderLayout.NORTH);
add(letterArea);
answer = new JTextArea();
answer.setFont(new Font("Arial", Font.PLAIN, 17));
Border in = BorderFactory.createDashedBorder(Color.BLACK);
Border out = BorderFactory.createMatteBorder(0, 0, 5, 0, Color.WHITE);
answer.setBorder(BorderFactory.createCompoundBorder(out, in));
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
System.out.print(((JTextComponent) arg0.getSource()).getText());
if (arg0.getKeyCode() == KeyEvent.VK_ENTER)
{
String JLabelText = ((JLabel) ((JPanel) ((JPanel) ((Component) arg0.getSource()).getParent()).getComponent(0)).getComponent(0)).getText();
int ansNum = (int)JLabelText.charAt(0)-95;
if (ansNum < 6)
{
Answer k = new Answer((Question) ((JTextArea) arg0.getSource()).getParent().getParent().getParent(), ansNum);
k.answer.grabFocus();
Main.mWindow.repaint();
Main.mWindow.validate();
}
}
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
doc = (AbstractDocument)answer.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
answer.setBackground(Color.PINK);
add(answer);
q.answerArea.add(this, index-1);
}
}
public class Main
{
public static Properties config;
public static Locale currentLocale;
public static ResourceBundle lang;
public static JFrame mWindow;
public static JMenuBar menu;
public static JMenu menuFile, menuEdit;
public static JMenuItem itmNew, itmClose, itmLoad, itmSave, itmSaveAs, itmExit, itmCut, itmCopy, itmPaste, itmProperties;
public static JDialog newDoc;
public static JLabel newDocText1, newDocText2;
public static JRadioButton questions, list;
public static ButtonGroup newDocButtons;
public static JButton newDocOk;
public static Boolean firstSegment;
public static JPanel workspace;
public static JScrollPane scroll;
public static ArrayList<Page> pages;
public static void newDocumentForm()
{
//new document dialog
mWindow.setEnabled(false);
newDoc = new JDialog(mWindow, "newDoc");
newDoc.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
newDoc.addWindowListener(new WindowListener ()
{
public void windowActivated(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0)
{
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
});
newDoc.setSize(400, 200);
newDoc.setLocationRelativeTo(null);
newDoc.setResizable(false);
newDoc.setLayout(null);
newDoc.setVisible(true);
newDocText1 = new JLabel("newDocText1");
newDocText1.setBounds(5, 0, 400, 20);
newDocText2 = new JLabel("newDocText2");
newDocText2.setBounds(5, 20, 400, 20);
newDoc.add(newDocText1);
newDoc.add(newDocText2);
firstSegment = true;
questions = new JRadioButton("questions");
questions.setSelected(true);
questions.setFocusPainted(false);
questions.setBounds(10, 60, 400, 20);
questions.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = true;
}
});
list = new JRadioButton("list");
list.setFocusPainted(false);
list.setBounds(10, 80, 400, 20);
list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
firstSegment = false;
}
});
newDoc.add(questions);
newDoc.add(list);
newDocButtons = new ButtonGroup();
newDocButtons.add(questions);
newDocButtons.add(list);
newDocOk = new JButton("ok");
newDocOk.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
newDocOk.doClick();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
newDocOk.setFocusPainted(false);
newDocOk.setBounds(160, 120, 80, 40);
newDocOk.setMnemonic(KeyEvent.VK_ACCEPT);
newDocOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
createNewDocument();
}
});
newDoc.add(newDocOk);
newDocOk.requestFocus();
}
public static void createNewDocument()
{
//dispose of new document dialog
mWindow.toFront();
newDocText1 = null;
newDocText2 = null;
questions = null;
list = null;
newDocButtons = null;
newDocOk = null;
newDoc.dispose();
mWindow.setEnabled(true);
//create document display
workspace = new JPanel();
workspace.setLayout(new BoxLayout(workspace, BoxLayout.PAGE_AXIS));
workspace.add(new Box.Filler(new Dimension(0, 40), new Dimension(0, 40), new Dimension(0, 40)));
workspace.setBackground(Color.BLACK);
scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getVerticalScrollBar().setUnitIncrement(20);
scroll.setViewportView(workspace);
pages = new ArrayList<Page>();
Page p = new Page(workspace, 1);
new Heading(true, p);
Question q = new Question(p, 1, 1);
new Answer(q, 1);
mWindow.add(scroll, BorderLayout.CENTER);
mWindow.repaint();
mWindow.validate();
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mWindow.setVisible(true);
//create menu bar
menu = new JMenuBar();
menuFile = new JMenu("file");
menuEdit = new JMenu("edit");
itmNew = new JMenuItem("new");
itmNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
itmNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDocumentForm();
}
});
itmClose = new JMenuItem("close");
itmClose.setActionCommand("Close");
itmClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
itmLoad = new JMenuItem("load");
itmLoad.setActionCommand("Load");
itmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
itmSave = new JMenuItem("save");
itmSave.setActionCommand("Save");
itmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
itmSaveAs = new JMenuItem("saveAs");
itmSaveAs.setActionCommand("SaveAs");
itmExit = new JMenuItem("exit");
itmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Add confirmation window!
System.exit(0);
}
});
itmCut = new JMenuItem("cut");
itmCut.setActionCommand("Cut");
itmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
itmCopy = new JMenuItem("copy");
itmCopy.setActionCommand("Copy");
itmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
itmPaste = new JMenuItem("paste");
itmPaste.setActionCommand("Paste");
itmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
itmProperties = new JMenuItem("properties");
itmProperties.setActionCommand("properties");
itmProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
menuFile.add(itmNew);
menuFile.add(itmClose);
menuFile.addSeparator();
menuFile.add(itmLoad);
menuFile.addSeparator();
menuFile.add(itmSave);
menuFile.add(itmSaveAs);
menuFile.addSeparator();
menuFile.add(itmExit);
menuEdit.add(itmCut);
menuEdit.add(itmCopy);
menuEdit.add(itmPaste);
menuEdit.addSeparator();
menuEdit.add(itmProperties);
menu.add(menuFile);
menu.add(menuEdit);
//create actionListener for menus
mWindow.add(menu, BorderLayout.NORTH);
mWindow.repaint();
mWindow.validate();
}
}
Why don't you assign String into DocumentFilter
str = str.replaceAll()?