Using JLabel  in MVC

Hello,
i want to create an GUI with clean MVC pattern. For this each GUI element gets in my process class a model which i use to manipulate the GUI.
But what can i do with my JLabels, i didnt find a model for them so i dont know how to manipulte them.
At the moment i have in my viewclass a method to set the labels i want to set. eg.
public void setHeadline(String headline){
     this.getJLabelHeadline().setText(headline);
But i think there should be a better way to handle that.
Any ideas?
kind regards
toni

Thank you for your answear.
I understand that the JLabel doesn't need a state, my JLabels dont have a state too...
But i want that the JLabels display data, which i get from my Dataobjects. So the view doesnt know the data which have to be displayed.
Its only the Process (Controller) and the Model which know the data, but a JLabel doesn't have a Model. So i dont know how to transport the data from my process to the view-class without breaking the MVC-Rules.

Similar Messages

  • Displaying Image using JLabel in swings

    I am not understanding how to display a image in swing using JLabel Component.
    I am writing in the following manner:
    // importing necessary packages
    in init() method
    public void init()
    Container cp= getContentPane()
    JLabel jl=new JLabel("Image",new ImageIcon("<image>.gif"),JLabel.CENTER);
    cp.add(jl);
    applet is running and only label msg is displaying but not the image.
    Please help me so that i can solve this problem.where the image is to be placed??and how it has to be included?
    Please provide me the solution.

    cp.add(new JLabel("Image",new ImageIcon(new java.net.URL (getCodeBase(),"Test.gif")),JLabel.CENTER));

  • Using Datepicker in MVC 4

    Hi! I am new to MVC and scripts. I created an MVC application and now I have to add a date picker in that. I tried to use the datepicker function in jquery-ui-1.8.11.js file and applied like this:
    <script type="text/javascript" language="javascript" src="~/Scripts/jquery-ui-1.8.11.js">
    </script>
    but while running this it gives error like: JavaScript runtime error: 'jQuery' is undefined and it redirects me to 
    (function( $, undefined ) {
    in the file jquery-ui-1.8.11.js
    Please suggest in detail, how can I add date picker in my page.
    In HTML my tag is:
    <input id="test" />

    In the create you need this
    instead of razor you can use this
     <div class='input-group date' id='datetimepickerExample'>
     <input type='text' name="RealeaseDate" class="form-control" data-date-format="DD/MM/YYYY" />
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span> </div>
    @section Scripts {
        <script>
            $(function () {
                $('#datetimepickerExample').datetimepicker({ pickTime: false });
        </script>
        @Scripts.Render("~/bundles/jqueryval")

  • Painting GIF images/using JLabels for GIFs... Somehow, make it work!

    Ok, I am basically making an arena for a local multiplayer game for my friends, and across the top of the screen is a title ... lets call the title "Game Title". The entire game is contained in 1 JFrame, including the title, sidebars, and the actual "game" part in the middle. I paint all of the objects in the game by painting them in the JFrame's Graphics when the paint() method is called.
    Basically, the window looks like this:
    | /\./\./\./\./\....Game Title..../\./\./\./\./\ |
    |...........______________..............|
    |...........|.--.game area.--..|..............|
    |...........|_____________|..............|
    Where the /\./\./\'s are animated flames. I have tried to just make them as ImageIcons in JLabels, but no matter what I paint() after the labels are added, the window looks like this:
    | /\./\./\./\./\ .......................... /\./\./\./\./\ |
    |.........................................................|
    |.........................................................|
    |.........................................................|
    Where the flames are animated, but the "background" is always gray. I then tried to paint them as Images (g.drawImage(new ImageIcon(url).getImage(),0,0,null), but that only leaves the first frame of the animated GIF (in other words, its not animated).
    What do I do? I have been reading around the forums, but I cannot find a case where somebody needed the GIF inside a Component that they used for painting...
    Thanks for any help that you give!

    If you're going to paint use a graphic component to do your painting in and don't add any components to it. The 'paint' method in JFrame is called by swing to draw the JFrame and its components. Using it to do custom painting is tricky. You'll need to call 'super.paint' to allow the container to paint its children. See the method detail in the JFrame api (link is in the Container section of the api). Also check the 'paintComponent' and 'paint' methods in the JComponent api method details section.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Painting extends JPanel
        BufferedImage image;
        public Painting(BufferedImage image)
            this.image = image;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            g.drawImage(image, 125, 175, this);
        private JPanel getTitlePanel()
            JLabel title = new JLabel("Game Title", JLabel.CENTER);
            JLabel flame1 = new JLabel("flames");
            JLabel flame2 = new JLabel("flames");
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            panel.add(flame1, gbc);
            panel.add(title, gbc);
            panel.add(flame2, gbc);
            return panel;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            BufferedImage bi = ImageIO.read(Painting.class.getResource(path));
            Painting painting = new Painting(bi);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(painting.getTitlePanel(), "North");
            f.getContentPane().add(painting);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Using JLabel[] to create an array of image labels

    Hello, I am quite new to Java so I am not sure if the following is even the best way to do what i am trying to do ... but please advise:
    I am making a JLayeredPane mapArea with grid lines where the user will be able to change the scale of the map and the grid lines can move along. The way I approached it is to create JLabel arrays that contains every single gird line i am going to use, add them to the map panel at the bottom-most layer and position them according to the scale. Below is the code that I wrote:
    int i = 0;     //local index variable for the for loops below
    JLabel[] vlineArray = new JLabel[50];
    JLabel[] hlineArray = new JLabel[50];
    ImageIcon[] vlineImageArray = new ImageIcon[50];
    ImageIcon[] hlineImageArray = new ImageIcon[50];
    for( i=0; i<50; i++ ){
         vlineImageArray[ i ] = new ImageIcon(GUI.class.getResource("vline.gif")); 
         hlineImageArray[ i ] = new ImageIcon(GUI.class.getResource("hline.gif")); 
    // vertical line array
         for( i=0; i<50; i++){
         vlineArray [ i ] = new JLabel(vlineImageArray[ i ]);
    mapArea.add(vlineArray[ i ],1);
    // horizontal line array
    for( i=0; i<50; i++){
         hlineArray [ i ]= new JLabel(hlineImageArray[ i ]);
         mapArea.add(hlineArray [ i ],1);
    }}I tried to position these Jlabels in the array using setBounds:
    i.e. vlineArray.setBounds(......)
    But nothing showed... But if I simple create a vline by itself and add it to the map pane and setBounds. The vline shows up fine:
    // this works
    JLabel vlineImage = new JLabel(vline);
    mapArea.add(vlineImage);
    vlineImage.setBounds(.....);I also tried to post at the java programming forum
    http://forum.java.sun.com/thread.jspa?threadID=646495&tstart=15
    But nothing worked.
    Please help! Thanks a bunch!

    if I were going to draw grid lines over a map area, I would put a component the size of the layered pane in the layered pane which is transparent and can be given a scale and can override the paint method to paint the lines directly instead of trying to handle lots of labels like you're doing.

  • Using TableView and MVC

    I have a problem with TableView. I use TableView to display a table which is an attribute of my model class.
    Code in the view looks like this:
      <htmlb:tableView
           id            = "TEST_ID"
           table         = "//model/t_selected_employees"
           selectionMode = "MULTISELECT" />.
    I also have a few buttons on this view, when the button is pressed in DO_HANDLE_EVENT method I append a line to table but when the next DO_HANDLE_DATA method occurs table flushes. All other parameters stay filled.
    Thank you for future help.

    your code in do_handle_event should luk like this now :
    ************Code .
    DATA:
    lt_string_table TYPE string_table.
    CHECK NOT event IS INITIAL.
    IF htmlb_event_ex->event_name = xhtmlb_events=>buttongroup AND
    htmlb_event_ex->event_type = xhtmlb_events=>buttongroup_click.
    DATA: ls LIKE LINE OF model->t_selected_employees.
    CASE htmlb_event_ex->event_defined.
    WHEN 'TEST'.
    call model->insert_line.
    ENDCASE.
    ENDIF.
    Code ends.
    in Model class create the insert_line methos and put your append code there as  :
    mothod insert_line.
    ls-num = 55. ls-pernr = '00001280'. ls-fio = 'TEST'.
    APPEND ls t_selected_employees.
    endmethod.

  • Problem in displaying images using JLabel in Netbeans

    hi all,
    i am trying to display an image on JLabel in Netbeans.The image is visible in the design view but not displayed in the runtime.Can anyone help me out with suggestions???

    Duplicate - answer here http://forum.java.sun.com/thread.jspa?threadID=5153605&messageID=9578626#9578626

  • How use JLabel and JCombobox on one string

    package ReplacementCode;
    import java.awt.BorderLayout;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    class MainFrame extends JFrame {
    private static JTextArea text = new JTextArea(ReadingFromFile.textFromFile.size(), 40);
    private static JScrollPane forText = new JScrollPane(text);
    private static JPanel westPanel = new JPanel();
    private static JPanel forAlphabet = new JPanel();
    private static JPanel forModifyChars = new JPanel();
    private static JLabel[] labels = new JLabel[Alphabet.russianAlphabet.length()];
    private static Object[] massiveOfAlphabet = new Object[Alphabet.russianAlphabet.length()];
    private static JComboBox[] comboBoxes = new JComboBox[Alphabet.russianAlphabet.length()];
    private static JButton startButton = new JButton("!&#1079;&#1072;&#1084;&#1077;&#1085;&#1080;&#1090;&#1100;!");
    private static BoxListener[] boxListeners = new BoxListener[Alphabet.russianAlphabet.length()];
    public MainFrame() {
    super("&#1086;&#1089;&#1085;&#1074;&#1086;&#1074;&#1085;&#1086;&#1077; &#1086;&#1082;&#1085;&#1086;");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    initiasizeCenter();
    initiasizeWest();
    JLabel jlab = new JLabel(Alphabet.russianAlphabet.toUpperCase());
    jlab.setOpaque(true);
    add(forText, BorderLayout.CENTER);
    add(westPanel, BorderLayout.WEST);
    add(startButton, BorderLayout.SOUTH);
    add(jlab, BorderLayout.NORTH);
    setSize(this.getMaximumSize());
    setVisible(true);
    private void initiasizeWest() {
    putAlphabet();
    forModifyChars.setLayout(new BoxLayout(forModifyChars, BoxLayout.Y_AXIS));
    forAlphabet.setLayout(new BoxLayout(forAlphabet, BoxLayout.Y_AXIS));
    for(int ii = 0; ii < Alphabet.russianAlphabet.length(); ii++) {
    comboBoxes[ii] = new JComboBox(massiveOfAlphabet);
    comboBoxes[ii].setSelectedIndex(ii);
    boxListeners[ii] = new BoxListener();
    comboBoxes[ii].addKeyListener(boxListeners[ii]);
    forModifyChars.add(comboBoxes[ii]);
    StringBuffer sb = new StringBuffer();
    sb.append(Alphabet.russianAlphabet.charAt(ii));
    labels[ii] = new JLabel(sb.toString().toUpperCase());
    labels[ii].setOpaque(true);
    labels[ii].setHorizontalTextPosition(JLabel.LEFT);
    labels[ii].setVerticalTextPosition(JLabel.CENTER);
    westPanel.add(forAlphabet);
    westPanel.add(Box.createHorizontalGlue());
    westPanel.add(forModifyChars);
    private static void initiasizeCenter() {
    text.setLineWrap(true);
    for(int ii = 0; ii < ReadingFromFile.textFromFile.size(); ii++)
    text.append(ReadingFromFile.textFromFile.elementAt(ii) + "\n");
    private static void initiasizeSouth() {}
    private static void initiasizeNorth() {}
    private static final void putAlphabet() {
    for(int ii = 0; ii < Alphabet.russianAlphabet.length(); ii++)
    massiveOfAlphabet[ii] = Alphabet.russianAlphabet.charAt(ii);
    private class BoxListener implements KeyListener {
    public BoxListener() {
    public void keyPressed(KeyEvent e) {
    System.out.println("&#1089;&#1083;&#1091;&#1096;&#1072;&#1077;&#1090;&#1083;&#1100; &#1085;&#1072;&#1078;&#1072;&#1090;&#1080;&#1103; &#1082;&#1083;&#1072;&#1074;&#1080;&#1096;&#1080; : " + e + "\n");
    public void keyReleased(KeyEvent e) {
    System.out.println("&#1089;&#1083;&#1091;&#1096;&#1072;&#1077;&#1090;&#1083;&#1100; &#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;&#1085;&#1080;&#1103; &#1082;&#1083;&#1072;&#1074;&#1080;&#1096;&#1080; : " + e + "\n");
    public void keyTyped(KeyEvent e) {
    System.out.println("&#1089;&#1083;&#1091;&#1096;&#1072;&#1077;&#1090;&#1083;&#1100; &#1087;&#1077;&#1095;&#1072;&#1090;&#1072;&#1085;&#1080;&#1103; &#1089;&#1080;&#1084;&#1074;&#1086;&#1083;&#1072; : " + e + "\n");
    package ReplacementCode;
    import java.util.Vector;
    abstract class Alphabet {
    final static String russianAlphabet = new String("&#1072;&#1073;&#1074;&#1075;&#1076;&#1077;&#1105;&#1078;&#1079;&#1080;&#1081;&#1082;&#1083;&#1084;&#1085;&#1086;&#1087;&#1088;&#1089;&#1090;&#1091;&#1092;&#1093;&#1094;&#1095;&#1096;&#1097;&#1098;&#1099;&#1100;&#1101;&#1102;&#1103;");
    private static String replacementAlphabet;
    private static double[] ratesOfCharacters = new double[russianAlphabet.length()];
    static Vector<String> replacementedText = new Vector<String>();
    static final void generateAlphabetOfReplacement() {
    boolean[] occupancy = new boolean[russianAlphabet.length()];
    for(int ii = 0; ii < occupancy.length; ii++)
    occupancy[ii] = false;
    char[] ancillaryMassiveOfCharacters = new char[russianAlphabet.length()];
    for(int ii = 0; ii < ancillaryMassiveOfCharacters.length; ii++) {
    for(;;) {
    int ancillaryPositionOfCharacter = (int) (Math.random() * ancillaryMassiveOfCharacters.length);
    if(occupancy[ancillaryPositionOfCharacter] == false) {
    occupancy[ancillaryPositionOfCharacter] = true;
    ancillaryMassiveOfCharacters[ii] = russianAlphabet.charAt(ancillaryPositionOfCharacter);
    break;
    replacementAlphabet = new String(ancillaryMassiveOfCharacters);
    static final void workWithText(Vector<String> unreplacementText) {
    generateAlphabetOfReplacement();
    nullingOfRates();
    replacementedText.removeAllElements();
    for(int ii = 0; ii < unreplacementText.size(); ii++) {
    char[] occupancyMassive = unreplacementText.elementAt(ii).toCharArray();
    for(int jj = 0; jj < occupancyMassive.length; jj++) {
    //verification of agreement of character's in text with basic alphabet
    for(int kk = 0; kk < russianAlphabet.length(); kk++) {
    if(Character.isUpperCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == Character.toUpperCase(russianAlphabet.charAt(kk))) {
    occupancyMassive[jj] = Character.toUpperCase(replacementAlphabet.charAt(kk));
    ratesOfCharacters[kk]++;
    break;
    if(Character.isLowerCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == russianAlphabet.charAt(kk)) {
    occupancyMassive[jj] = replacementAlphabet.charAt(kk);
    ratesOfCharacters[kk]++;
    break;
    //save new replacemented text
    replacementedText.add(new String(occupancyMassive));
    //            System.out.println(unreplacementText.elementAt(ii));
    //            System.out.println(replacementedText.elementAt(ii));
    static final void workWithText(Vector<String> unreplacementText, String oldAlphabet, String newAlphabet) {
    nullingOfRates();
    replacementedText.removeAllElements();
    for(int ii = 0; ii < unreplacementText.size(); ii++) {
    char[] occupancyMassive = unreplacementText.elementAt(ii).toCharArray();
    for(int jj = 0; jj < occupancyMassive.length; jj++) {
    //verification of agreement of character's in text with basic alphabet
    for(int kk = 0; kk < oldAlphabet.length(); kk++) {
    if(Character.isUpperCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == Character.toUpperCase(oldAlphabet.charAt(kk))) {
    occupancyMassive[jj] = Character.toUpperCase(newAlphabet.charAt(kk));
    ratesOfCharacters[kk]++;
    break;
    if(Character.isLowerCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == oldAlphabet.charAt(kk)) {
    occupancyMassive[jj] = newAlphabet.charAt(kk);
    ratesOfCharacters[kk]++;
    break;
    //save new replacemented text
    replacementedText.add(new String(occupancyMassive));
    //            System.out.println(unreplacementText.elementAt(ii));
    //            System.out.println(replacementedText.elementAt(ii));
    private static void nullingOfRates() {
    for(int ii = 0; ii < ratesOfCharacters.length; ii++)
    ratesOfCharacters[ii] = 0;
    }the problem is in westPanel; how we can typed text from the Jlabel near JCombobox
    now - text from combobox we can see, and text from label - don't.
    and one of condition is don't crash massive of JCombobox and Jlabel
    please help me

    if if was different mod then only create many vertical Jpanels, with pair jlabel, jcombobox, please write...i don't want to do this because it wil bee many references on Jpanels-> many memory..

  • Using OLAP as a data source and create a JSON object

    Hi All,
    I have a question.
    I am working on an hospital assessment project which is being developed using AngularJs and MVC WEBAPI. We are using "HIGHCHARTS" for developing the required dashboards and charts by providing JSON objects which are developed using  MVC WEB-API
    (from normal SQL procedures). 
    Problem is raised when we are trying to build a chart using a table with around 1.2 million records. we are facing severe performance issue while generating the data set. Now, Here is my question "Can
    we generate a JSON object using an SSAS cube accessed using MVC"? If it can be done please help me out with some valuable procedure that can be done.
    Thanks In Advance.
    Regards
    Sunil Kumar 
    Please mark as answer if it is helpful. Thank You

    Hi,
    Here is another way of doing it using MDX code. I do not know whether this helps you but... Following MDX query produces the Sales Amount per Sub Category.
    SELECT {[Measures].[Sales Amount]} ON COLUMNS,
    NON EMPTY{[Product].[Subcategory].[Subcategory].MEMBERS} ON ROWS
    FROM [Adventure Works]
    Following MDX generates the Output As JSON object array.
    WITH MEMBER [Measures].[JSON Object_] AS "{""ProductSubCategories"":[" + Chr(13) +
    GENERATE
    NONEMPTY
    [Product].[Subcategory].[Subcategory].MEMBERS,
    [Measures].[Sales Amount]
    ), Space(10) + "{""SubCategoryName"":""" + [Product].[Subcategory].CurrentMember.Member_Name + """, ""SalesAmount"":""" + CStr([Measures].[Sales Amount]) + """}," + Chr(13)
    MEMBER [Measures].[JSON Object] AS LEFT([Measures].[JSON Object_], LEN([Measures].[JSON Object_]) -2) + Chr(13) + "]}"
    SELECT {[Measures].[JSON Object]} ON COLUMNS
    FROM
    SELECT {[Measures].[Sales Amount]} ON COLUMNS
    FROM [Adventure Works]
    WHERE {([Product].[Subcategory].[Subcategory].MEMBERS)}
    Following is the JSON Object OutPut of the above query.
    {"ProductSubCategories":[
    {"SubCategoryName":"Bib-Shorts", "SalesAmount":"166739.7086"},
    {"SubCategoryName":"Bike Racks", "SalesAmount":"237096.156"},
    {"SubCategoryName":"Bike Stands", "SalesAmount":"39591"},
    {"SubCategoryName":"Bottles and Cages", "SalesAmount":"64274.793600001"},
    {"SubCategoryName":"Bottom Brackets", "SalesAmount":"51826.374"},
    {"SubCategoryName":"Brakes", "SalesAmount":"66018.711"},
    {"SubCategoryName":"Caps", "SalesAmount":"51229.4461000002"},
    {"SubCategoryName":"Chains", "SalesAmount":"9377.7102"},
    {"SubCategoryName":"Cleaners", "SalesAmount":"18406.9725"},
    {"SubCategoryName":"Cranksets", "SalesAmount":"203942.6182"},
    {"SubCategoryName":"Derailleurs", "SalesAmount":"70209.4958"},
    {"SubCategoryName":"Fenders", "SalesAmount":"46619.5799999995"},
    {"SubCategoryName":"Forks", "SalesAmount":"77931.6896"},
    {"SubCategoryName":"Gloves", "SalesAmount":"242795.874200003"},
    {"SubCategoryName":"Handlebars", "SalesAmount":"170591.3209"},
    {"SubCategoryName":"Headsets", "SalesAmount":"60942.1984"},
    {"SubCategoryName":"Helmets", "SalesAmount":"484048.532299996"},
    {"SubCategoryName":"Hydration Packs", "SalesAmount":"105826.4185"},
    {"SubCategoryName":"Jerseys", "SalesAmount":"752259.388399975"},
    {"SubCategoryName":"Locks", "SalesAmount":"16225.22"},
    {"SubCategoryName":"Mountain Bikes", "SalesAmount":"36445443.9409015"},
    {"SubCategoryName":"Mountain Frames", "SalesAmount":"4713672.1469"},
    {"SubCategoryName":"Pedals", "SalesAmount":"147483.9098"},
    {"SubCategoryName":"Pumps", "SalesAmount":"13514.6873"},
    {"SubCategoryName":"Road Bikes", "SalesAmount":"43878790.9970001"},
    {"SubCategoryName":"Road Frames", "SalesAmount":"3849853.3438"},
    {"SubCategoryName":"Saddles", "SalesAmount":"55829.3882"},
    {"SubCategoryName":"Shorts", "SalesAmount":"413522.526999996"},
    {"SubCategoryName":"Socks", "SalesAmount":"29745.1280999999"},
    {"SubCategoryName":"Tights", "SalesAmount":"201833.006"},
    {"SubCategoryName":"Tires and Tubes", "SalesAmount":"246454.527600005"},
    {"SubCategoryName":"Touring Bikes", "SalesAmount":"14296291.2698"},
    {"SubCategoryName":"Touring Frames", "SalesAmount":"1642327.6862"},
    {"SubCategoryName":"Vests", "SalesAmount":"259488.3707"},
    {"SubCategoryName":"Wheels", "SalesAmount":"679070.065399999"}
    Best regards...
    Chandima Lakmal Fonseka

  • MVC model in Web systems and applications

    MVC model in Web systems and applications
    Object-oriented design model is experience, MVC idea is a user interface for the original. This article discusses how the major application areas in the new Web design patterns and the use of MVC framework. The article first introduced the concept of design patterns and characteristics, and MVC architecture design concepts and analysis of the MVC framework contains several key models. Based on the characteristics of Web applications on how to use patterns and MVC framework made some design ideas.??
    1. Introduction
    1.1 design model
    Object-oriented technology and the emergence of software applications has greatly enhanced the trusted and software quality. Object-oriented programming than previous models to various programming simple and efficient, but the object-oriented design methodology than the previous design methods to complex and much more skill, a good design should be both on the issue of gender, but also to take full account of the problems and needs sufficient interoperability. In the past 10 years, people in the object-oriented technology and the practical application of research to explore certain issues in relation to the creation of a number of good solutions, the so-called object-oriented design patterns. Object-oriented technology is one of the purposes of enhancing the software trusted, and to design model, design programmes in important positions from a deeper sense of meaning and essence embodies trusted. There are many people in the design model definition, which cited Christopher Alexander is the largest design model definition : Each design model is a tripartite rule, which expresses a contextual environment (Context), a problem and a solution. Design models generally following basic elements : model name, the purpose solution effect 1995-1998 code and related design models. There are several classifications design patterns can be divided into a model based on the purpose (Creational), structural type (Structural) and the type of behaviour (Behavioral) three. It is mainly used in the creation of a model-based object model-based structure to deal primarily with the category or combination of objects, used to describe behavior-based model is the main target for the category or how stress and how to allocate responsibilities. Design patterns can be divided into categories based on the scope and target mode model type model dealing with the relationship between the categories and sub-categories, these relations through the establishment of succession in Translation moment to be finalized, are static. Model is targeted at addressing the relationship between the moment of change these relations in the operation, more dynamic. Model features : through the experience acquired in a structured format to write down, avoid encountering the same problems on the first design, exist in different abstract level, in continuous improvement, can be trusted artificial product for the design and best practice in the world to be combined to address larger issues.
    1.2 MVC framework
    MVC was first used in a user interface Smalltalk-80 China. M representative models Model, representatives maps View V, C representatives controller Controller. MVC trusted code with the aim of increasing the rate of data reduction expressed, the data describing the operation and application coupled degrees. Also makes software Keweihuxing, restorative, expansionary, flexibility and packaging of greatly enhanced. Single-user applications are usually incident-driven user interface to the organizational structure. Staff development tool with an interface painting of a user interface interface code based on user input and then prepare to implement the corresponding moves, many interactive development environment encouraged to do so, because it emphasizes first and then a functional interface. Some software design model is the strategy that will be fixed before the code into the regular system of the final. Result is that the procedures and organizations around the user interface elements in the user interface elements of those moves, data storage, applications and functions of the code is used to indicate the way intertwined. In single-user system code structure can be so, because the system will not demand frequent changes. But for a large system such as large Web systems, or e-commerce systems to be applied. Model by incorporating data from a variety of access and control data can be separated to improve distributed system design. MVC design pattern is composed of three parts. Model is the application object, no user interface. Type in the screen showing that it represents the flow of data users. Controller user interface definition response to user input, the users responsible for the action against the Model into operation. Model View data updated to reflect the adoption of data changes.
    2. MVC design pattern,
    An MVC framework for the design of the system includes many models, but with MVC is most closely related to the following three models : Observer, Cambridge and Strategy.
    2.1 Observer models
    MVC through the use of purchase / notification form and the separation of the Model View. View to ensure that their content accurately reflected Model and state. Once Model content changes, there must be a mechanism to allow notification to the relevant Model View, View can be made relevant at the appropriate time updating of data. This design is also more general problems can be solved, the target separation, making a change to the target audience affect others, which targets those who do not know the details of the object being affected. This is described as Observer in the design model. Model type : Observer model is the object-oriented model, it is behaviour-based model. Model purposes : definition of hierarchical dependence relations between objects, or when a target value of the state change, all its dependent relationship with the object are notified and automatically updated. There are a variety of data may show a way, in different ways and may also show. When a way through a changed data, then the other should be able to show immediately that the data change and do accordingly.
    Effect :
    1. Abstract coupling. I only know that it has a target audience of some observers, the observers met each abstract Observer category simple interface, does not know their specific affiliation categories. This makes the coupling between goals and observers smallest and abstract.
    2. Support radio communications. Needless to notify designated observers goals, how to deal with the observer informed decisions.
    3. Possible accidents updated. We update logic, avoiding mistakes updated.
    2.2 Faculty model
    MVC is an important feature of View can nest. Nest can be used for any type of combination of local maps available, but also management of type nest. This thinking reflects the type and mix of components will be equal treatment design. This object-oriented design ideas in the area of Cambridge has been described as a design model. Model types : Cambridge model is the object-oriented model, it is also the structure type model. Model purpose : to target portfolio into tree structures to express "part-whole" level structure. Prepared for the use and combination of individual target audiences with the use of consistency.
    Effect :
    1. Definition of a target portfolio includes simple objects and the structure of the category level. Simple objects may be complex combinations of objects, and can be targeted portfolio mix. This customer-code used in the target areas can use simple combinations target.
    2. Simplify customer-code. Needless to know their customers - a mix of target audiences is a simple target or can use these items in a consistent manner.
    3. Easier to add new types of components. New components can easily be changed to a combination of customer-targeted codes.
    2.3 Strategy model
    Another important characteristic is the MVC can not change the View of changes View response to user input. This often requires a change in response to the logic of the system is very important. MVC to respond to the logic involved in the Controller. Controller of a category level structure could easily change to the original Controller appropriate, a new Controller. View Controller son used to achieve a specific example of such a response strategy. To achieve different response strategy, as long as examples of the use of different types of replacement will Controller. Also in the running time by changing the View Controller for users to change View of response strategies. This View-Controller relationship was described as an example of Strategy design pattern. Model types : Strategy model is the object-oriented model, it is behaviour-based model. Model purposes : definition of a series of algorithms, and their packaging, and ensure that they can replace each other, making algorithms can independently use its customer-change.
    Effect :
    1. Strategy category levels for Context definition of the relevant algorithms can be trusted or behaviour.
    2. Alternative methods of succession. If the direct successor Context, with different acts will be added Context act, the realization of which would algorithm mixed up with Context, Context hard to preserve and expand, but can not dynamically changing algorithms. Will be enclosed in a separate Strategy category algorithms to enable algorithm independent Context change easily cut over expansion.
    3. Can provide the same acts different date.
    4. Strategy-must understand what customers between different.
    5. Context and Strategy communications between costs.
    6. An increase in the number of targets.
    3. MVC in Web application system
    Now some of the distributed systems such as Web-based B2B e-commerce system, suitable for use MVC framework. Through analysis from the perspective of high-level applications can be a target divided into three categories. Category is shown for the target audience consists of a group of commercial rules and data, there is a category that is receiving requests to control commercial target to complete the request. These applications often need to change is shown, such as web style, color, but also need to demonstrate the contents of the display. And the business rules and data to be relatively stable. Therefore, said that the frequent need to change the View objects that the business rules and data model to be relatively stable target, and that the control of the Controller is the most stable. When the system is usually issued after the View objects by artists, designers or HTML/JSP system managers to manage. Controller target applications development personnel from the development and implementation of rules for commercial and business development personnel from the target data, database managers and experts in the field of common completed. Show in Web?? or customers - control logic can be Servlet or JSP, dynamically generated Html. Generally used Servlet better than using JSP. JSP will be better with the Html code of separate codes for page designers and developers of separation efficiency. Servlet and JSP can complete all complete functions, actually JSP eventually converted into a Servlet. And control of the target system exists in every level, the coordination of cross-layer moves. Contain business rules and data objects exist in the EJB layer (EJB-centred model) or Web?? (Web-centred model).
    3.1 View in the Web application system
    View of the system shows that it fully exist in Web??. General by JSP, Java Bean and Custom Tag. JSP can generate dynamic web content using Java Custom Tag easier Bean, but it can show the logic of packaging, and more conducive to modular trusted. Some well-designed in a number of JSP Custom Tag can even be used in different system duplication. Model for control of JSP and Java Bean objects. JSP through Java Bean objects to retrieve the data model, the Model and Controller object is responsible for updating the data on Java Bean. In general, can we devise all possible screen that users can see all the elements of the system. Based on these elements, to identify the public part of passive components and dynamics. Can consider the use of templates means to separate the content generated JSP public, also need to change their generation Html or JSP from a JSP templates to dynamically introduce these different parts (include methods). Another issue to consider is screen option, when dealing with End users request template automatically available to show that the concern that users must know what is the screen components. So can consider all screens on the definition of a centralized document, such as a document or text document java. Taking into account the possibility of changes in future document definition screens, the best use of text documents such as a XML document, so future changes to the recompilation. According to the URL and user input parameters to shine upon the results of a screen, of course, likely to be made on the basis of the outcome of the implementation of actions to choose different results screen. Therefore, the need for a request for matching resources with document (XML), if a URL request several different results, it must specify in the document need to control the flow (a controller object), as well as the corresponding screen different flows.
    3.2 Model in the Web application system
    Model objects represent business rules and business data exist in EJB layer and Web??. In J2EE norms, the system needs some data stored in the database, such as user account information (account model), the company's data (company model), some not recorded in the database. If a user browsing the current catalogue (catalog model), the contents of his shopping (shopping cart model). Which one of these models exist in the data according to their life cycle and scope to decide. In Web?? a HttpSession and ServletContext and Java Bean objects to store data in the EJB layer is a data storage and logic EJB to. Web?? the Java Bean objects stored in the model layer model of the EJB object data copy. Because there are many different EJB tier model targets, so Web?? through a ModelManager to control the EJB layer object model in ModelManger background model can be used for packaging methods. In the EJB layer and the rules have all the data into EJB model is inappropriate. If the database can visit the Dao object model into objects. Dao can be encapsulated and the specific details of the database in the world, if we can write a different table, a number of databases, or even multiple databases. If the orders can be a model for OrderDAO, it may have to deal with Order table, table and OrderItemLines OrderStatus table. Value can also consider the use of targets. Value can be a target of securing long-range targets, because every time the remote object attributes could be a long-range redeployment process will consume network resources. EJB objects in the distance can be used instead target. In the distance, one-time items to be targeted instead of the value of all attributes.
    3.3 Controller in Web application system
    Coordination with the Model View Controller object to the request of users into the system to identify incidents. In Web?? generally a MainServlet (or Main.jsp), and receiving all requests, it can use screen flow management devices (ScreenFlowManger) decided next screen. There is a general request processors RequestProcessor contains all requests are needed to be done to deal with logic, such as the request translated into system events (RequestToEvent). Acting processors usually also includes a request for ClientControlWebImpl, it is logical to deal with the EJB layer in Web?? Acting. In EJB layer, a layer for EJB tier Web ClientController provide the CD visit. Another StateMachine used to create and delete ejb handle Web?? sent to the incident. Controller Another important function is synchronous View and Model data. ModelManger contained in a ModelUpdateManger, it puts events into a Model System assembly that all the needs of synchronous Model, and then notify Listeners do synchronous operation.
    4. Concluding remarks
    In recent years, with the Internet technology development and the emergence of new business models, the Web is based on a large number of applications. On how to design these systems architecture, and gradually there has been some convergence of opinion, the most important point is that its structure should be rational in the open. Demand than ever faster development of technology and design concepts, systems for the future, the cost of upgrading the smallest, research software systems architecture still very useful and necessary.

    Bravo. And your point is?

  • [HELP] using multiple value parameter in c:import tag

    I need to pass a multi-value parameter to a included page. e.g.
    http://myhost/MyContext/dir1/page1.jsp?abc=value1&abc=value2/dir1/page1.jsp includes /dir2/page2.jsp, and would like to pass this multi-value parameter over, but change the name to xyz, some what like
    <c:import url="/dir2/page2.jsp?xyz=value1&xyz=value2"/>The problem is that the number of values is not fix number, so I have to write some logic to iterate thru its parameter values. But the <c:import> tag body allows only simple listed <c:param> tags, it doesn't allow other logic/condition/iteration.
    <!-- gives java.io.IOException: javax.servlet.jsp.JspException: The taglib validator rejected the page: "Illegal child tag in "c_rt:import" tag: "c:forEach" tag at runtime -->
    <c:import url="/dir2/page2.jsp">
    <c:forEach var="xyz" items="${paramValues.abc}">
    <c:param name="xyz" value="${xyz}"/>
    </c:forEach>
    </c:import>{code}
    I also tried <c:url> tag. The good news is that it supports jsp logic in body:
    {code}<c:url var="url" value="/dir2/page2.jsp">
    <c:forEach var="xyz" items="${paramValues.abc}">
    <c:param name="xyz" value="${xyz}"/>
    </c:forEach>
    </c:url>
    <c:out value="${url}"/>{code}but it prefixes the url with the current context:
    {code}/MyContext/dir2/page2.jsp?xyz=value1&xyz=value2{code}
    Now I run into a dead end. It seems the only way out is to use <% %> scriptlet to do my own url composite, which is pretty similar to <c:url> but avoid the context part.
    Any suggestion?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    out.println("<html>");
    out.println("<head>");
    out.println("<script language=\"JavaScript\">");
    out.println("function altSubmit() {");
    out.println("document.MyForm.action = \"Second.html\";");
    out.println("document.MyForm.submit();");
    out.println("}");
    out.println("</script>");
    out.println("</head>");
    out.println("<body>");
    My personal suggestion is to use follow the MVC (Model View Control) pattern where in you can write all your "html" part in a JSP.
    Model -> Bean
    View -> JSP
    Control -> Servlet

  • Upgrade to MVC 5.0 causes @Html.Partial razor to no longer render on the server (locally runs fine)

    I've recently upgraded my MVC 4 application to MVC 5.  When debugging locally (IIS Express or full), the application runs as before.  When deploying, via Visual Studio, to our development box, I get the following error from IIS:
    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
    Compiler Error Message: CS1928: 'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'Partial' and the best extension method overload 'System.Web.Mvc.Html.PartialExtensions.Partial(System.Web.Mvc.HtmlHelper, string)' has some invalid arguments
    Source Error:
    Line 25: <body>
    Line 26: <div id="applicationHost">
    Line 27: @Html.Partial("_splash")
    Line 28: </div>
    Line 29:
    The detailed compiler output shows the following:
    Microsoft (R) Visual C# Compiler version 4.0.30319.17929
    for Microsoft (R) .NET Framework 4.5
    Copyright (C) Microsoft Corporation. All rights reserved.
    d:\websites\mvcapp\Views\ItemCard\index.cshtml(27,10): error CS1928: 'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'Partial' and the best extension method overload 'System.Web.Mvc.Html.PartialExtensions.Partial(System.Web.Mvc.HtmlHelper, string)' has some invalid arguments
    d:\websites\mvcapp\Views\ItemCard\index.cshtml(27,10): error CS1929: Instance argument: cannot convert from 'System.Web.WebPages.Html.HtmlHelper' to 'System.Web.Mvc.HtmlHelper'
    d:\websites\mvcapp\Views\ItemCard\index.cshtml(32,83): error CS0103: The name 'Url' does not exist in the current context
    It looks as if there is perhaps a namespace collision in the compiled temp assembly.  
    The code of the .cshtml file in question is as follows:
    @using System.Web.Mvc
    @using System.Web.Mvc.Html
    @using System.Web.Optimization
    <!DOCTYPE html>
    <html>
    <head>
    <title>MVC App</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="format-detection" content="telephone=no"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    @Styles.Render("~/Content/css")
    <script type="text/javascript">
    if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
    var msViewportStyle = document.createElement("style");
    var mq = "@@-ms-viewport{width:auto!important}";
    msViewportStyle.appendChild(document.createTextNode(mq));
    document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
    </script>
    </head>
    <body>
    <div id="applicationHost">
    @Html.Partial("_splash")
    </div>
    @Scripts.Render("~/scripts/vendor")
    @if(HttpContext.Current.IsDebuggingEnabled) {
    <script type="text/javascript" src="~/Scripts/require.js" data-main="@Url.Content("~/App/main")"></script>
    } else {
    @Scripts.Render("~/Scripts/main-built")
    </body>
    IIS on the server is running a 4.0 apppool, and .NET 4.5 is installed on the box.
    Thanks,
    Josh

    Hi Pianomanjh,
    Microsoft-Web-Helpers has been replaced with Microsoft.AspNet.WebHelpers. You should remove the old package first, and then install the newer package. Please see how to upgrade an MVC 4 project to MVC 5 and follow the
    steps on the following link.
    http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2.
    By the way, this thread is specific to ASP. NET forum. This form is to discuss problems about CLR development. If you have any questions about ASP.NET, please post a new thread on that forum for more effective response.
    http://forums.asp.net/.
    Thank you for your understanding.
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 1) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

  • MVC �Best Practice� (handling multiple views per action/event)

    Looking for the best approach for handling multiple views for one action/event class? Background: I have a small application using a basic MVC model, one controller servlet, multiple event classes, and multiple JSP views. For performance reasons, the controller Servlet is loaded once, and each event class is an instance within it. Each event has an �eventProcess()� and an �eventForward()� method called by the controller, standard stuff.
    However, because event classes should not use instance variables, how should I communicate which view to forward to should based upon eventProcess() logic (e.g. if error, error.jsp, if success, success.sjp)? Currently, there is only one view mapped per event, and I'm having to put error handling logic in the JSP, which goes against the JSP being for just view only.
    My though was 1) A session object/variable that the eventProcess() sets, and the eventForward() reads, or 2) Have eventProcess() return a mapping key and have the conroller lookup a view page based upon that key, as opposed to 1-1 event/view mapping.
    Would like your thoughts!
    Thanks
    bRi

    Your solution seems ok to me, but maybe the Struts framework from Apache
    that implements MVC for JSP is a better solution for you:
    http://jakarta.apache.org/struts/index.html
    You should take a look at it. It has in addition some useful taglibs that makes life much easier.
    We have successfully used it in a project with about 50 pages.

  • Using text as a hyperlink to call a program (Notepad)

    I am making a About Dialog which contains some text.
    A small part of the text must be a hyperlink (blue and underlined). When clicked, Notepad must open with the license agreement.
    This I will do, nothing else (no discussion on this).
    But how to do it?
    I could overwrite paint method of the JDialog, but I cannot use easily underlined text with g.drawString...
    Next I had the idea of using JLabels. But it would be a lot of assembling the labels and configuring the layout manager.
    Then I thought about using subclass of Document with a JTextPane. But I don't know if I can use hyperlinks that way for my purpose.
    What do you think about the three ideas, or do you have a solution?

    The labels idea seems like the simplest to me. I know there's a way to do hyperlinks in an HTMLEditorPane (don't know if this is exactly the right classname) but it isn't simple, and I have no experience with it myself. I really like your idea of displaying the licence agreement in Notepad though, it gives the licencee a chance to modify it before agreeing to it. Other licences I have agreed to are so rigid, they don't let you change anything.

Maybe you are looking for