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 am trying to make a program that populates a JPanel with GridLayout with the contents of a HashMap that contains String keys to JButton values. Because the size of the HashMap may change, I can't just use setText() for each button. So far I've called .removeAll() to remove the JPanel of all buttons, then I loop through the HashMap to repopulate the JPanel. I then call revalidate() on the JPanel and repaint() on the JFrame.
Current Code:
public class GUI implements Runnable, ActionListener
{
private ToDo td;
JFrame frame;
Thread t=null;
int fontsize = 18;
private Container contentPane;
private JPanel topPane;
private JButton main;
private JButton add;
private JButton settings;
private JPanel centerPane;
private JScrollPane centerScroll;
private JPanel scrollable;
private HashMap<String, JButton> items;
public static void main(String[] args) {
new GUI();
}
public GUI(){
td = new ToDo();
frame = new JFrame();
t = new Thread(this);
t.start();
frame.setMinimumSize(new Dimension(480, 640));
frame.setLayout(null);
frame.setVisible(true);
contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
topPane = new JPanel();
topPane.setLayout(new GridLayout(1, 3));
topPane.setPreferredSize(new Dimension(480, 40));
main = new JButton("View Tasks");
main.setFont(new Font("Sans Serif", Font.PLAIN, fontsize));
add = new JButton("Add Task");
add.setFont(new Font("Sans Serif", Font.PLAIN, fontsize));
settings = new JButton("Settings");
settings.setFont(new Font("Sans Serif", Font.PLAIN, fontsize));
topPane.add(main);
topPane.add(add);
topPane.add(settings);
contentPane.add(topPane, BorderLayout.NORTH);
centerPane = new JPanel();
centerPane.setPreferredSize(new Dimension(480, 600));
items = new HashMap<>();
HashMap<String, Assignment> assignments = td.getAssignments();
scrollable = new JPanel();
scrollable.setLayout(new GridLayout(assignments.size(), 1));
centerScroll = new JScrollPane(scrollable);
for(String key: assignments.keySet()){
Assignment a = assignments.get(key);
JButton button = new JButton(a.getTitle() + " | " + a.getDetails() + " | " + a.getClassification().getCls() + " | " + a.getStatus().getStatus());
button.addActionListener(this);
items.put(key, button);
scrollable.add(button);
}
centerPane.add(centerScroll);
contentPane.add(centerPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public void update(int i){
HashMap<String, Assignment> assignments = td.getAssignments();
scrollable.removeAll();
scrollable.setLayout(new GridLayout(assignments.size(), 1));
for(String key: assignments.keySet()){
Assignment a = assignments.get(key);
JButton button = new JButton(Integer.toString(i));
button.addActionListener(this);
items.put(key, button);
scrollable.add(button);
}
scrollable.revalidate();
frame.repaint();
}
#Override
public void run(){
int counter = 0;
try {
while (true) {
update(counter);
t.sleep( 1000 ); // interval given in milliseconds
counter++;
}
}
catch (Exception e) {
System.out.println();
}
}
#Override
public void actionPerformed(ActionEvent e){
for(String s: items.keySet()){
if(items.get(s) == e.getSource()){
EventMenu em = new EventMenu(td, s);
}
}
}
}
The problem is that the buttons are not updating. I expect that the JPanel should be constantly repopulating with updated JButtons with different text, but it seems that the program hangs and doesn't update.
I tried making a simpler example which I modified from here, with different results:
public class DigitalWatch implements Runnable{
JFrame f;
JPanel p;
Thread t=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton b;
DigitalWatch(){
f=new JFrame();
p = new JPanel();
t = new Thread(this);
t.start();
b=new JButton();
b.setBounds(100,100,100,50);
p.add(b);
f.add(p);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
p.removeAll();
b=new JButton(timeString);
b.setBounds(100,100,100,50);
p.add(b);
f.add(p);
p.revalidate();
f.repaint();
//printTime();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new DigitalWatch();
}
}
This snippet fails to draw anything, unlike the first which at least draws the objects created in the constructor.
How can I make a list or grid JPanel update procedurally and in real time and populate buttons? I know I could change the text of each button every time, but the number of buttons may change at any time.
Full code here.
you are violating Swing's single thread rule - you are not supposed to do any UI related stuff outside Swing's event dispatch thread.
Read up on it here and here.
Below is a working example. Not sure why they chose to use a button to show the time though. :-)
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
public class DigitalWatch extends JFrame {
private DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
public DigitalWatch() {
JButton btn = new JButton(getCurrentTime());
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(btn);
this.setPreferredSize(new Dimension(200, 150));
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null); // center it on the screen
new Timer(500, e -> btn.setText(getCurrentTime())).start();
}
private String getCurrentTime() {
return formatter.format(LocalTime.now());
}
public static void main(String[] args) {
new DigitalWatch().setVisible(true);
}
}
A frame which includes panels where buttons are located in a column on the left side of the frame:
I tried to make this picture in real Java code but failed.
I can't find the right solution for this issue...
BorderLayout borderLayout = new BorderLayout();
GridBagLayout gridBagLayout = new GridBagLayout();
GridLayout gridLayout = new GridLayout();
CardLayout cardLayout = new CardLayout();
JPanel panelMain = new JPanel();
JPanel panelLeft = new JPanel();
JPanel panelInnerLeft = new JPanel();
JPanel panelRight = new JPanel();
panelMain.setLayout(borderLayout);
panelLeft.setLayout(gridBagLayout);
panelInnerLeft.setLayout(gridLayout);
panelRight.setLayout(cardLayout);
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button4 = new JButton("Button 4");
panelInnerLeft.add(button1,gridLayout);
panelInnerLeft.add(button2,gridLayout);
panelInnerLeft.add(button3,gridLayout);
panelInnerLeft.add(button4,gridLayout);
panelLeft.add(panelInnerLeft);
panelMain.add(panelLeft);
panelMain.add(panelRight);
add(panelMain);
This is the exact code used to make that screenshot.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CompoundLayout01 {
private JComponent ui = null;
CompoundLayout01() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new TitledBorder("BorderLayout"));
CardLayout cardLayout = new CardLayout();
JPanel cards = new JPanel(cardLayout);
cards.setBorder(new TitledBorder("CardLayout"));
ui.add(cards);
JPanel lineStart = new JPanel(new GridBagLayout());
lineStart.setBorder(new TitledBorder("GridBagLayout"));
// will appear on the left, in a LTR text orientation locale
ui.add(lineStart, BorderLayout.LINE_START);
JPanel buttonsCentered = new JPanel(new GridLayout(0, 1, 10, 10));
buttonsCentered.setBorder(new TitledBorder("GridLayout"));
// as single component added w/no constraint, will be centered
lineStart.add(buttonsCentered);
for (int ii=1; ii<5; ii++) {
JButton b = new JButton("Button " + ii);
buttonsCentered.add(b);
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
CompoundLayout01 o = new CompoundLayout01();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
panelMain.setLayout(borderLayout);
...
panelMain.add(panelLeft);
panelMain.add(panelRight);
Read the Swing tutorial on Layout Managers.
It will show you how to use the BorderLayout.
You need to specify the "constraint" when you add each component. Like BorderLayout.LINE_START, or BorderLayout.CENTER.
The following is also wrong:
panelInnerLeft.setLayout(gridLayout);
...
panelInnerLeft.add(button1,gridLayout);
panelInnerLeft.add(button2,gridLayout);
panelInnerLeft.add(button3,gridLayout);
panelInnerLeft.add(button4,gridLayout);
Read the section on GridLayout. A GridLayout does not require a constraint.
I don't know if you need some specific layout, but if you want more control, you can take a look at my example. Note that I have to handle some sizes myself. Also if you need even more control you can always use null as layout.
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.SwingUtilities;
public class NewJFrame extends javax.swing.JFrame {
private JPanel jPanel1;
private JButton jButton1;
private JButton jButton2;
private JButton jButton3;
private JPanel jPanel2;
private JButton jButton4;
private JPanel ButtonsPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
NewJFrame inst = new NewJFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public NewJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jPanel1 = new JPanel();
getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.setLayout(null);
ButtonsPanel = new JPanel();
FlowLayout ButtonsPanelLayout = new FlowLayout();
jPanel1.add(ButtonsPanel);
ButtonsPanel.setLayout(ButtonsPanelLayout);
ButtonsPanel.setBounds(12, 23, 104, 215);
ButtonsPanel.setBorder(
BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
jButton1 = new JButton();
ButtonsPanel.add(jButton1);
jButton1.setText("jButton1");
jButton1.setPreferredSize(new java.awt.Dimension(85, 23));
jButton2 = new JButton();
ButtonsPanel.add(jButton2);
jButton2.setText("jButton2");
jButton2.setPreferredSize(new java.awt.Dimension(85, 23));
jButton3 = new JButton();
ButtonsPanel.add(jButton3);
jButton3.setText("jButton3");
jButton3.setPreferredSize(new java.awt.Dimension(85, 23));
jButton4 = new JButton();
ButtonsPanel.add(jButton4);
jButton4.setText("jButton4");
jButton4.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel2 = new JPanel();
jPanel1.add(jPanel2);
jPanel2.setLayout(null);
jPanel2.setBounds(122, 23, 250, 215);
jPanel2.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
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
I want to set some text at a specified offset in my JTextArea. Let's say I have already in my edit "aaa bbb" and I want to overwrite "bbb" with "house", how can I do that in Java?
You could use replaceRange()
public void replaceRange(String str,
int start,
int end)
Replaces text from the indicated start to end position with the new text specified. Does nothing if the model is null. Simply does a delete if the new string is null or empty.
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
You need to take a look at three methods setSelectionStart(...), setSelectionEnd(...) and replaceSelection(...).
Here is a small sample program to help your cause :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaSelection
{
private JTextField replaceTextField;
private JTextField startIndexField;
private JTextField endIndexField;
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("JTextArea Selection");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setOpaque(true);
final JTextArea tarea = new JTextArea(10, 10);
tarea.setText("aaa bbb");
final JButton updateButton = new JButton("UPDATE TEXT");
updateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//tarea.setSelectionStart(4);
//tarea.setSelectionEnd(7);
//tarea.replaceSelection("house");
int selection = JOptionPane.showConfirmDialog(null, getPanel());
if (selection == JOptionPane.OK_OPTION)
{
if (replaceTextField.getDocument().getLength() > 0
&& startIndexField.getDocument().getLength() > 0
&& endIndexField.getDocument().getLength() > 0)
{
String text = replaceTextField.getText().trim();
int start = Integer.parseInt(startIndexField.getText().trim());
int end = Integer.parseInt(endIndexField.getText().trim());
tarea.replaceRange(text, start, end);
}
}
}
});
contentPane.add(tarea, BorderLayout.CENTER);
contentPane.add(updateButton, BorderLayout.PAGE_END);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
}
private JPanel getPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 2, 2));
JLabel replaceLabel = new JLabel("Enter new String : "
, JLabel.CENTER);
replaceTextField = new JTextField(10);
JLabel startIndexLabel = new JLabel("Enter Start Index : "
, JLabel.CENTER);
startIndexField = new JTextField(10);
JLabel endIndexLabel = new JLabel("Enter End Index : ");
endIndexField = new JTextField(10);
panel.add(replaceLabel);
panel.add(replaceTextField);
panel.add(startIndexLabel);
panel.add(startIndexField);
panel.add(endIndexLabel);
panel.add(endIndexField);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaSelection().createAndDisplayGUI();
}
});
}
}